blob: 2d9c93341fdfa086512f509f9f1254fade4745ea [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>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000024#include <unistd.h>
25
26#include <string_view>
27
Steven Moreland826367f2021-09-10 14:05:31 -070028#include <android-base/hex.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000029#include <android-base/macros.h>
Steven Moreland27a8bc72021-09-29 16:07:41 -070030#include <android-base/scopeguard.h>
Steven Moreland4f622fe2021-09-13 17:38:09 -070031#include <binder/BpBinder.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000032#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000033#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070034#include <binder/RpcTransportRaw.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000035#include <binder/Stability.h>
Andrei Homescu1d935e82022-04-25 04:58:23 +000036#include <utils/Compat.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000037#include <utils/String8.h>
38
Yifan Hong8c950422021-08-05 17:13:55 -070039#include "FdTrigger.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000040#include "RpcSocketAddress.h"
41#include "RpcState.h"
42#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070043#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000044
Andrei Homescu47f8c4f2022-04-30 01:38:24 +000045#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -070046#include <android_runtime/vm.h>
47#include <jni.h>
48#endif
49
Steven Morelandbdb53ab2021-05-05 17:57:41 +000050namespace android {
51
52using base::unique_fd;
53
Yifan Hongecf937d2021-08-11 17:29:28 -070054RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000055 LOG_RPC_DETAIL("RpcSession created %p", this);
56
Steven Moreland27a8bc72021-09-29 16:07:41 -070057 mRpcBinderState = std::make_unique<RpcState>();
Steven Morelandbdb53ab2021-05-05 17:57:41 +000058}
59RpcSession::~RpcSession() {
60 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
61
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000062 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070063 LOG_ALWAYS_FATAL_IF(mConnections.mIncoming.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000064 "Should not be able to destroy a session with servers in use.");
65}
66
Yifan Hongecf937d2021-08-11 17:29:28 -070067sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070068 // Default is without TLS.
Yifan Hongfdd9f692021-09-09 15:12:52 -070069 return make(RpcTransportCtxFactoryRaw::make());
Yifan Hongecf937d2021-08-11 17:29:28 -070070}
71
Yifan Hongfdd9f692021-09-09 15:12:52 -070072sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070073 auto ctx = rpcTransportCtxFactory->newClientCtx();
74 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070075 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000076}
77
Yifan Hong10423062021-10-08 16:26:32 -070078void RpcSession::setMaxIncomingThreads(size_t threads) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000079 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070080 LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
Yifan Hong10423062021-10-08 16:26:32 -070081 "Must set max incoming threads before setting up connections, but has %zu "
82 "client(s) and %zu server(s)",
Steven Morelanda59937e2021-10-04 17:42:30 -070083 mConnections.mOutgoing.size(), mConnections.mIncoming.size());
Yifan Hong10423062021-10-08 16:26:32 -070084 mMaxIncomingThreads = threads;
Steven Moreland103424e2021-06-02 18:16:19 +000085}
86
Yifan Hong10423062021-10-08 16:26:32 -070087size_t RpcSession::getMaxIncomingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000088 RpcMutexLockGuard _l(mMutex);
Yifan Hong10423062021-10-08 16:26:32 -070089 return mMaxIncomingThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000090}
91
Yifan Hong1f44f982021-10-08 17:16:47 -070092void RpcSession::setMaxOutgoingThreads(size_t threads) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000093 RpcMutexLockGuard _l(mMutex);
Yifan Hong1f44f982021-10-08 17:16:47 -070094 LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
95 "Must set max outgoing threads before setting up connections, but has %zu "
96 "client(s) and %zu server(s)",
97 mConnections.mOutgoing.size(), mConnections.mIncoming.size());
98 mMaxOutgoingThreads = threads;
99}
100
101size_t RpcSession::getMaxOutgoingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000102 RpcMutexLockGuard _l(mMutex);
Yifan Hong1f44f982021-10-08 17:16:47 -0700103 return mMaxOutgoingThreads;
104}
105
Steven Morelandbf57bce2021-07-26 15:26:12 -0700106bool RpcSession::setProtocolVersion(uint32_t version) {
107 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
108 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
109 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
110 "is %u).",
111 version, RPC_WIRE_PROTOCOL_VERSION);
112 return false;
113 }
114
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000115 RpcMutexLockGuard _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -0700116 if (mProtocolVersion && version > *mProtocolVersion) {
117 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
118 *mProtocolVersion, version);
119 return false;
120 }
121
Steven Morelandbf57bce2021-07-26 15:26:12 -0700122 mProtocolVersion = version;
123 return true;
124}
125
126std::optional<uint32_t> RpcSession::getProtocolVersion() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000127 RpcMutexLockGuard _l(mMutex);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700128 return mProtocolVersion;
129}
130
Frederick Mayle69a0c992022-05-26 20:38:39 +0000131void RpcSession::setFileDescriptorTransportMode(FileDescriptorTransportMode mode) {
132 mFileDescriptorTransportMode = mode;
133}
134
135RpcSession::FileDescriptorTransportMode RpcSession::getFileDescriptorTransportMode() {
136 return mFileDescriptorTransportMode;
137}
138
Steven Moreland2372f9d2021-08-05 15:42:01 -0700139status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000140 return setupSocketClient(UnixSocketAddress(path));
141}
142
Steven Moreland2372f9d2021-08-05 15:42:01 -0700143status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000144 return setupSocketClient(VsockSocketAddress(cid, port));
145}
146
Steven Moreland2372f9d2021-08-05 15:42:01 -0700147status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000148 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700149 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000150 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
151 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700152 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000153 }
154 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 -0700155 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000156}
157
Steven Moreland2372f9d2021-08-05 15:42:01 -0700158status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
Frederick Mayle297c2772022-05-05 01:21:04 +0000159 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700160 if (!fd.ok()) {
161 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700162 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700163 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700164 if (auto res = setNonBlocking(fd); !res.ok()) {
165 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
166 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
167 }
Frederick Mayle297c2772022-05-05 01:21:04 +0000168 status_t status = initAndAddConnection(std::move(fd), sessionId, incoming);
169 fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
170 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700171 });
172}
173
Steven Moreland2372f9d2021-08-05 15:42:01 -0700174status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700175 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700176 if (auto status = initShutdownTrigger(); status != OK) return status;
177
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000178 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
179
180 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700181 int savedErrno = errno;
182 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
183 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000184 }
185
Yifan Hongecf937d2021-08-11 17:29:28 -0700186 auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700187 if (server == nullptr) {
188 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700189 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700190 }
191 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000192}
193
194sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000195 ExclusiveConnection connection;
196 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
197 ConnectionUse::CLIENT, &connection);
198 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000199 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000200}
201
Steven Moreland1be91352021-05-11 22:12:15 +0000202status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000203 ExclusiveConnection connection;
204 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
205 ConnectionUse::CLIENT, &connection);
206 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000207 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000208}
209
Steven Morelandc9d7b532021-06-04 20:57:41 +0000210bool RpcSession::shutdownAndWait(bool wait) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000211 RpcMutexUniqueLock _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000212 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000213
214 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000215
Steven Morelandc9d7b532021-06-04 20:57:41 +0000216 if (wait) {
217 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700218 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700219
Steven Morelanda59937e2021-10-04 17:42:30 -0700220 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000221 }
222
223 _l.unlock();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000224
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 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000259 RpcMutexLockGuard _l(mMutex);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000260 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
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000285void RpcSession::WaitForShutdownListener::waitForShutdown(RpcMutexUniqueLock& lock,
Steven Moreland791e4662021-09-13 15:22:58 -0700286 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
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000296void RpcSession::preJoinThreadOwnership(RpcMaybeThread thread) {
297 LOG_ALWAYS_FATAL_IF(thread.get_id() != rpc_this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000298
Steven Morelanda63ff932021-05-12 00:03:15 +0000299 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000300 RpcMutexLockGuard _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 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000407 RpcMutexLockGuard _l(session->mMutex);
408 auto it = session->mConnections.mThreads.find(rpc_this_thread::get_id());
Steven Morelanda59937e2021-10-04 17:42:30 -0700409 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 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000441 RpcMutexLockGuard _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
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000503#ifdef BINDER_RPC_SINGLE_THREADED
504 constexpr size_t outgoingThreads = 1;
505#else // BINDER_RPC_SINGLE_THREADED
Yifan Hong1f44f982021-10-08 17:16:47 -0700506 size_t outgoingThreads = std::min(numThreadsAvailable, mMaxOutgoingThreads);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000507#endif // BINDER_RPC_SINGLE_THREADED
Yifan Hong1f44f982021-10-08 17:16:47 -0700508 ALOGI_IF(outgoingThreads != numThreadsAvailable,
509 "Server hints client to start %zu outgoing threads, but client will only start %zu "
510 "because it is preconfigured to start at most %zu outgoing threads.",
511 numThreadsAvailable, outgoingThreads, mMaxOutgoingThreads);
512
Steven Morelanda5036f02021-06-08 02:26:57 +0000513 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000514 // instead of all at once - the other side should be responsible for setting
515 // up additional connections. We need to create at least one (unless 0 are
516 // requested to be set) in order to allow the other side to reliably make
517 // any requests at all.
518
Steven Moreland4198a122021-08-03 17:37:58 -0700519 // we've already setup one client
Yifan Hong1f44f982021-10-08 17:16:47 -0700520 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing (server max: %zu) and %zu "
521 "incoming threads",
522 outgoingThreads, numThreadsAvailable, mMaxIncomingThreads);
523 for (size_t i = 0; i + 1 < outgoingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700524 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700525 }
526
Yifan Hong10423062021-10-08 16:26:32 -0700527 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700528 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000529 }
530
Steven Moreland27a8bc72021-09-29 16:07:41 -0700531 cleanup.Disable();
532
Steven Moreland2372f9d2021-08-05 15:42:01 -0700533 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000534}
535
Steven Moreland2372f9d2021-08-05 15:42:01 -0700536status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700537 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700538 return setupOneSocketConnection(addr, sessionId, incoming);
539 });
540}
541
Steven Moreland2372f9d2021-08-05 15:42:01 -0700542status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700543 const std::vector<uint8_t>& sessionId,
544 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000545 for (size_t tries = 0; tries < 5; tries++) {
546 if (tries > 0) usleep(10000);
547
Yifan Hongb675ffe2021-08-05 16:37:17 -0700548 unique_fd serverFd(TEMP_FAILURE_RETRY(
549 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000550 if (serverFd == -1) {
551 int savedErrno = errno;
552 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
553 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700554 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000555 }
556
557 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700558 int connErrno = errno;
559 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
560 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
561 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
562 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
563 if (pollStatus != OK) {
564 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
565 statusToString(pollStatus).c_str());
566 return pollStatus;
567 }
568 // Set connErrno to the errno that connect() would have set if the fd were blocking.
569 socklen_t connErrnoLen = sizeof(connErrno);
570 int ret =
571 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
572 if (ret == -1) {
573 int savedErrno = errno;
574 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
575 "(Original error from connect() is: %s)",
576 strerror(savedErrno), strerror(connErrno));
577 return -savedErrno;
578 }
579 // Retrieved the real connErrno as if connect() was called with a blocking socket
580 // fd. Continue checking connErrno.
581 }
582 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000583 ALOGW("Connection reset on %s", addr.toString().c_str());
584 continue;
585 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700586 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
587 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700588 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700589 strerror(connErrno));
590 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700591 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000592 }
Yifan Hong702115c2021-06-24 15:39:18 -0700593 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
594
Steven Moreland4198a122021-08-03 17:37:58 -0700595 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000596 }
597
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000598 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700599 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000600}
601
Steven Moreland826367f2021-09-10 14:05:31 -0700602status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700603 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700604 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700605 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700606 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700607 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700608 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700609 }
610
611 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
612
Steven Moreland826367f2021-09-10 14:05:31 -0700613 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
614 ALOGE("Session ID too big %zu", sessionId.size());
615 return BAD_VALUE;
616 }
617
Steven Moreland4198a122021-08-03 17:37:58 -0700618 RpcConnectionHeader header{
619 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
620 .options = 0,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000621 .fileDescriptorTransportMode = static_cast<uint8_t>(mFileDescriptorTransportMode),
Steven Moreland826367f2021-09-10 14:05:31 -0700622 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700623 };
Steven Moreland4198a122021-08-03 17:37:58 -0700624
Steven Moreland826367f2021-09-10 14:05:31 -0700625 if (incoming) {
626 header.options |= RPC_CONNECTION_OPTION_INCOMING;
627 }
Steven Moreland4198a122021-08-03 17:37:58 -0700628
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000629 iovec headerIov{&header, sizeof(header)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000630 auto sendHeaderStatus = server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1,
631 std::nullopt, nullptr);
Yifan Hong8c950422021-08-05 17:13:55 -0700632 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700633 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700634 statusToString(sendHeaderStatus).c_str());
635 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700636 }
637
Steven Moreland826367f2021-09-10 14:05:31 -0700638 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000639 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
640 sessionId.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000641 auto sendSessionIdStatus =
642 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1,
643 std::nullopt, nullptr);
Steven Moreland826367f2021-09-10 14:05:31 -0700644 if (sendSessionIdStatus != OK) {
645 ALOGE("Could not write session ID ('%s') to socket: %s",
646 base::HexString(sessionId.data(), sessionId.size()).c_str(),
647 statusToString(sendSessionIdStatus).c_str());
648 return sendSessionIdStatus;
649 }
650 }
651
Steven Moreland4198a122021-08-03 17:37:58 -0700652 LOG_RPC_DETAIL("Socket at client: header sent");
653
654 if (incoming) {
655 return addIncomingConnection(std::move(server));
656 } else {
657 return addOutgoingConnection(std::move(server), true /*init*/);
658 }
659}
660
Steven Moreland2372f9d2021-08-05 15:42:01 -0700661status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000662 RpcMutex mutex;
663 RpcConditionVariable joinCv;
664 RpcMutexUniqueLock lock(mutex);
665 RpcMaybeThread thread;
Steven Morelandfba6f772021-07-15 22:45:09 +0000666 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
667 bool ownershipTransferred = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000668 thread = RpcMaybeThread([&]() {
669 RpcMutexUniqueLock threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700670 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000671 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
672 sp<RpcSession> session = thiz;
673 session->preJoinThreadOwnership(std::move(thread));
674
675 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700676 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000677
678 ownershipTransferred = true;
679 threadLock.unlock();
680 joinCv.notify_one();
681 // do not use & vars below
682
683 RpcSession::join(std::move(session), std::move(setupResult));
684 });
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000685 rpcJoinIfSingleThreaded(thread);
Steven Morelandfba6f772021-07-15 22:45:09 +0000686 joinCv.wait(lock, [&] { return ownershipTransferred; });
687 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700688 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000689}
690
Yifan Hong832521e2021-08-05 14:55:40 -0700691status_t RpcSession::initShutdownTrigger() {
692 // first client connection added, but setForServer not called, so
693 // initializaing for a client.
694 if (mShutdownTrigger == nullptr) {
695 mShutdownTrigger = FdTrigger::make();
696 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
697 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
698 }
699 return OK;
700}
701
Steven Moreland2372f9d2021-08-05 15:42:01 -0700702status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000703 sp<RpcConnection> connection = sp<RpcConnection>::make();
704 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000705 RpcMutexLockGuard _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700706 connection->rpcTransport = std::move(rpcTransport);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000707 connection->exclusiveTid = rpcGetThreadId();
Steven Morelanda59937e2021-10-04 17:42:30 -0700708 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000709 }
710
Steven Morelandb86e26b2021-06-12 00:35:58 +0000711 status_t status = OK;
712 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700713 status =
714 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000715 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000716
Andrei Homescuc8490872022-06-23 05:18:51 +0000717 clearConnectionTid(connection);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000718
Steven Moreland2372f9d2021-08-05 15:42:01 -0700719 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000720}
721
Steven Morelanda8b44292021-06-08 01:27:53 +0000722bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700723 const std::vector<uint8_t>& sessionId,
724 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000725 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
726 LOG_ALWAYS_FATAL_IF(server == nullptr);
727 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
728 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000729 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Andrei Homescu5e301462022-05-12 00:52:34 +0000730 LOG_ALWAYS_FATAL_IF(mCtx != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000731
732 mShutdownTrigger = FdTrigger::make();
733 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000734
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000735 mId = sessionId;
736 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000737 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700738 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000739 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000740}
741
Yifan Hong702115c2021-06-24 15:39:18 -0700742sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
743 std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000744 RpcMutexLockGuard _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700745
Yifan Hong10423062021-10-08 16:26:32 -0700746 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700747 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700748 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700749 return nullptr;
750 }
751
Steven Morelanddd67b942021-07-23 17:15:41 -0700752 // Don't accept any more connections, some have shutdown. Usually this
753 // happens when new connections are still being established as part of a
754 // very short-lived session which shuts down after it already started
755 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700756 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700757 return nullptr;
758 }
759
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000760 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700761 session->rpcTransport = std::move(rpcTransport);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000762 session->exclusiveTid = rpcGetThreadId();
Steven Morelanddd67b942021-07-23 17:15:41 -0700763
Steven Morelanda59937e2021-10-04 17:42:30 -0700764 mConnections.mIncoming.push_back(session);
765 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000766
767 return session;
768}
769
Steven Moreland19fc9f72021-06-10 03:57:30 +0000770bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000771 RpcMutexUniqueLock _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700772 if (auto it =
773 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
774 it != mConnections.mIncoming.end()) {
775 mConnections.mIncoming.erase(it);
776 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000777 sp<EventListener> listener = mEventListener.promote();
778 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700779 _l.unlock();
780 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000781 }
Steven Morelandee78e762021-05-05 21:12:51 +0000782 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000783 return true;
784 }
785 return false;
786}
787
Andrei Homescuc8490872022-06-23 05:18:51 +0000788void RpcSession::clearConnectionTid(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000789 RpcMutexUniqueLock _l(mMutex);
Andrei Homescuc8490872022-06-23 05:18:51 +0000790 connection->exclusiveTid = std::nullopt;
791 if (mConnections.mWaitingThreads > 0) {
792 _l.unlock();
793 mAvailableConnectionCv.notify_one();
794 }
795}
796
Yifan Hong9734cfc2021-09-13 16:14:09 -0700797std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700798 return mCtx->getCertificate(format);
799}
800
Steven Moreland195edb82021-06-08 02:44:39 +0000801status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
802 ExclusiveConnection* connection) {
803 connection->mSession = session;
804 connection->mConnection = nullptr;
805 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000806
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000807 uint64_t tid = rpcGetThreadId();
808 RpcMutexUniqueLock _l(session->mMutex);
Steven Moreland195edb82021-06-08 02:44:39 +0000809
Steven Morelanda59937e2021-10-04 17:42:30 -0700810 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000811 while (true) {
812 sp<RpcConnection> exclusive;
813 sp<RpcConnection> available;
814
815 // CHECK FOR DEDICATED CLIENT SOCKET
816 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000817 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700818 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
819 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000820
821 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700822 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000823 //
824 // Imagine we have more than one thread in play, and a single thread
825 // sends a synchronous, then an asynchronous command. Imagine the
826 // asynchronous command is sent on the first client connection. Then, if
827 // we naively send a synchronous command to that same connection, the
828 // thread on the far side might be busy processing the asynchronous
829 // command. So, we move to considering the second available thread
830 // for subsequent calls.
831 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700832 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
833 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000834 }
835
Steven Morelandc7d40132021-06-10 03:42:11 +0000836 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000837 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000838 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000839 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000840 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700841 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000842
843 // asynchronous calls cannot be nested, we currently allow ref count
844 // calls to be nested (so that you can use this without having extra
845 // threads). Note 'drainCommands' is used so that these ref counts can't
846 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000847 if (exclusiveIncoming != nullptr) {
848 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000849 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000850 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000851 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
852 // prefer available socket, but if we don't have one, don't
853 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000854 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000855 }
856 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000857 }
858
Steven Moreland85e067b2021-05-26 17:43:53 +0000859 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000860 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000861 connection->mConnection = exclusive;
862 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000863 break;
864 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000865 connection->mConnection = available;
866 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000867 break;
868 }
869
Steven Morelanda59937e2021-10-04 17:42:30 -0700870 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000871 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
872 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
873 "reason: %d. Incoming connections: %zu. %s.",
874 static_cast<int>(use), session->mConnections.mIncoming.size(),
875 (session->server()
876 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
877 "for the corresponding client"
878 : "This is a client session, so see RpcSession::setMaxOutgoingThreads "
879 "for this client or RpcServer::setMaxThreads for the corresponding "
880 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000881 return WOULD_BLOCK;
882 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000883
Steven Moreland85e067b2021-05-26 17:43:53 +0000884 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700885 session->mConnections.mOutgoing.size(),
886 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000887 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000888 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700889 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000890
891 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000892}
893
Andrei Homescue922b232022-04-23 03:41:09 +0000894void RpcSession::ExclusiveConnection::findConnection(uint64_t tid, sp<RpcConnection>* exclusive,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000895 sp<RpcConnection>* available,
896 std::vector<sp<RpcConnection>>& sockets,
897 size_t socketsIndexHint) {
898 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
899 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
900
901 if (*exclusive != nullptr) return; // consistent with break below
902
903 for (size_t i = 0; i < sockets.size(); i++) {
904 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
905
Steven Moreland85e067b2021-05-26 17:43:53 +0000906 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000907 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
908 *available = socket;
909 continue;
910 }
911
Steven Moreland85e067b2021-05-26 17:43:53 +0000912 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000913 // (nested transactions)
914 if (exclusive && socket->exclusiveTid == tid) {
915 *exclusive = socket;
916 break; // consistent with return above
917 }
918 }
919}
920
921RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000922 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000923 // is using this fd, and it retains the right to it. So, we don't give up
924 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000925 if (!mReentrant && mConnection != nullptr) {
Andrei Homescuc8490872022-06-23 05:18:51 +0000926 mSession->clearConnectionTid(mConnection);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000927 }
928}
929
930} // namespace android