blob: b7ca88afce2dae5916a75e58a26a1469af0aef5f [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
46#ifdef __GLIBC__
47extern "C" pid_t gettid();
48#endif
49
Yifan Hongd258e682021-11-01 18:34:42 -070050#ifndef __ANDROID_RECOVERY__
51#include <android_runtime/vm.h>
52#include <jni.h>
53#endif
54
Steven Morelandbdb53ab2021-05-05 17:57:41 +000055namespace android {
56
57using base::unique_fd;
58
Yifan Hongecf937d2021-08-11 17:29:28 -070059RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000060 LOG_RPC_DETAIL("RpcSession created %p", this);
61
Steven Moreland27a8bc72021-09-29 16:07:41 -070062 mRpcBinderState = std::make_unique<RpcState>();
Steven Morelandbdb53ab2021-05-05 17:57:41 +000063}
64RpcSession::~RpcSession() {
65 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
66
67 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070068 LOG_ALWAYS_FATAL_IF(mConnections.mIncoming.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000069 "Should not be able to destroy a session with servers in use.");
70}
71
Yifan Hongecf937d2021-08-11 17:29:28 -070072sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070073 // Default is without TLS.
Yifan Hongfdd9f692021-09-09 15:12:52 -070074 return make(RpcTransportCtxFactoryRaw::make());
Yifan Hongecf937d2021-08-11 17:29:28 -070075}
76
Yifan Hongfdd9f692021-09-09 15:12:52 -070077sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070078 auto ctx = rpcTransportCtxFactory->newClientCtx();
79 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070080 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000081}
82
Yifan Hong10423062021-10-08 16:26:32 -070083void RpcSession::setMaxIncomingThreads(size_t threads) {
Steven Moreland103424e2021-06-02 18:16:19 +000084 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070085 LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
Yifan Hong10423062021-10-08 16:26:32 -070086 "Must set max incoming threads before setting up connections, but has %zu "
87 "client(s) and %zu server(s)",
Steven Morelanda59937e2021-10-04 17:42:30 -070088 mConnections.mOutgoing.size(), mConnections.mIncoming.size());
Yifan Hong10423062021-10-08 16:26:32 -070089 mMaxIncomingThreads = threads;
Steven Moreland103424e2021-06-02 18:16:19 +000090}
91
Yifan Hong10423062021-10-08 16:26:32 -070092size_t RpcSession::getMaxIncomingThreads() {
Steven Moreland103424e2021-06-02 18:16:19 +000093 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong10423062021-10-08 16:26:32 -070094 return mMaxIncomingThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000095}
96
Yifan Hong1f44f982021-10-08 17:16:47 -070097void RpcSession::setMaxOutgoingThreads(size_t threads) {
98 std::lock_guard<std::mutex> _l(mMutex);
99 LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
100 "Must set max outgoing threads before setting up connections, but has %zu "
101 "client(s) and %zu server(s)",
102 mConnections.mOutgoing.size(), mConnections.mIncoming.size());
103 mMaxOutgoingThreads = threads;
104}
105
106size_t RpcSession::getMaxOutgoingThreads() {
107 std::lock_guard<std::mutex> _l(mMutex);
108 return mMaxOutgoingThreads;
109}
110
Steven Morelandbf57bce2021-07-26 15:26:12 -0700111bool RpcSession::setProtocolVersion(uint32_t version) {
112 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
113 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
114 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
115 "is %u).",
116 version, RPC_WIRE_PROTOCOL_VERSION);
117 return false;
118 }
119
120 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -0700121 if (mProtocolVersion && version > *mProtocolVersion) {
122 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
123 *mProtocolVersion, version);
124 return false;
125 }
126
Steven Morelandbf57bce2021-07-26 15:26:12 -0700127 mProtocolVersion = version;
128 return true;
129}
130
131std::optional<uint32_t> RpcSession::getProtocolVersion() {
132 std::lock_guard<std::mutex> _l(mMutex);
133 return mProtocolVersion;
134}
135
Steven Moreland2372f9d2021-08-05 15:42:01 -0700136status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000137 return setupSocketClient(UnixSocketAddress(path));
138}
139
Steven Moreland2372f9d2021-08-05 15:42:01 -0700140status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000141 return setupSocketClient(VsockSocketAddress(cid, port));
142}
143
Steven Moreland2372f9d2021-08-05 15:42:01 -0700144status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000145 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700146 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000147 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
148 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700149 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000150 }
151 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 -0700152 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000153}
154
Steven Moreland2372f9d2021-08-05 15:42:01 -0700155status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
Frederick Mayle297c2772022-05-05 01:21:04 +0000156 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700157 if (!fd.ok()) {
158 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700159 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700160 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700161 if (auto res = setNonBlocking(fd); !res.ok()) {
162 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
163 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
164 }
Frederick Mayle297c2772022-05-05 01:21:04 +0000165 status_t status = initAndAddConnection(std::move(fd), sessionId, incoming);
166 fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
167 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700168 });
169}
170
Steven Moreland2372f9d2021-08-05 15:42:01 -0700171status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700172 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700173 if (auto status = initShutdownTrigger(); status != OK) return status;
174
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000175 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
176
177 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700178 int savedErrno = errno;
179 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
180 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000181 }
182
Yifan Hongecf937d2021-08-11 17:29:28 -0700183 auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700184 if (server == nullptr) {
185 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700186 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700187 }
188 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000189}
190
191sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000192 ExclusiveConnection connection;
193 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
194 ConnectionUse::CLIENT, &connection);
195 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000196 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000197}
198
Steven Moreland1be91352021-05-11 22:12:15 +0000199status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000200 ExclusiveConnection connection;
201 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
202 ConnectionUse::CLIENT, &connection);
203 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000204 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000205}
206
Steven Morelandc9d7b532021-06-04 20:57:41 +0000207bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000208 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000209 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000210
211 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000212
Steven Morelandc9d7b532021-06-04 20:57:41 +0000213 if (wait) {
214 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700215 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700216
Steven Morelanda59937e2021-10-04 17:42:30 -0700217 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000218 }
219
220 _l.unlock();
Steven Moreland27a8bc72021-09-29 16:07:41 -0700221 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000222
Steven Moreland659416d2021-05-11 00:47:50 +0000223 return true;
224}
225
Steven Morelandf5174272021-05-25 00:39:28 +0000226status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000227 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000228 ExclusiveConnection connection;
229 status_t status =
230 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
231 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
232 : ConnectionUse::CLIENT,
233 &connection);
234 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000235 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000236 sp<RpcSession>::fromExisting(this), reply, flags);
237}
238
Steven Moreland4f622fe2021-09-13 17:38:09 -0700239status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000240 // target is 0 because this is used to free BpBinder objects
241 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700242}
243
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000244status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000245 ExclusiveConnection connection;
246 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
247 ConnectionUse::CLIENT_REFCOUNT, &connection);
248 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000249 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
250 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000251}
252
253status_t RpcSession::readId() {
254 {
255 std::lock_guard<std::mutex> _l(mMutex);
256 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
257 }
258
Steven Moreland195edb82021-06-08 02:44:39 +0000259 ExclusiveConnection connection;
260 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
261 ConnectionUse::CLIENT, &connection);
262 if (status != OK) return status;
263
Steven Moreland826367f2021-09-10 14:05:31 -0700264 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000265 if (status != OK) return status;
266
Steven Moreland826367f2021-09-10 14:05:31 -0700267 LOG_RPC_DETAIL("RpcSession %p has id %s", this,
268 base::HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000269 return OK;
270}
271
Steven Morelanddd67b942021-07-23 17:15:41 -0700272void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000273 const sp<RpcSession>& session) {
274 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000275}
276
Steven Moreland19fc9f72021-06-10 03:57:30 +0000277void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000278 mCv.notify_all();
279}
280
Steven Moreland791e4662021-09-13 15:22:58 -0700281void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock,
282 const sp<RpcSession>& session) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700283 while (session->mConnections.mIncoming.size() > 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000284 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700285 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
286 "still.",
Steven Morelanda59937e2021-10-04 17:42:30 -0700287 session->mConnections.mIncoming.size());
Steven Moreland659416d2021-05-11 00:47:50 +0000288 }
289 }
290}
291
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000292void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000293 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000294
Steven Morelanda63ff932021-05-12 00:03:15 +0000295 {
296 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700297 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000298 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000299}
Steven Morelanda63ff932021-05-12 00:03:15 +0000300
Yifan Hong702115c2021-06-24 15:39:18 -0700301RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
302 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000303 // must be registered to allow arbitrary client code executing commands to
304 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700305 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000306
Steven Morelanddd67b942021-07-23 17:15:41 -0700307 status_t status;
308
309 if (connection == nullptr) {
310 status = DEAD_OBJECT;
311 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700312 status =
313 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700314 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000315
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000316 return PreJoinSetupResult{
317 .connection = std::move(connection),
318 .status = status,
319 };
320}
321
Yifan Hong194acf22021-06-29 18:44:56 -0700322namespace {
Yifan Hongd258e682021-11-01 18:34:42 -0700323#ifdef __ANDROID_RECOVERY__
324class JavaThreadAttacher {};
325#else
Yifan Hong194acf22021-06-29 18:44:56 -0700326// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
327// Android Runtime doesn't exist, no-op.
328class JavaThreadAttacher {
329public:
330 JavaThreadAttacher() {
331 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
332 // libbinder.
333 auto vm = getJavaVM();
334 if (vm == nullptr) return;
335
336 char threadName[16];
337 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
338 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
339 memcpy(threadName, defaultThreadName,
340 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
341 }
342 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
343 JavaVMAttachArgs args;
344 args.version = JNI_VERSION_1_2;
345 args.name = threadName;
346 args.group = nullptr;
347 JNIEnv* env;
348
349 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
350 "Cannot attach thread %s to JVM", threadName);
351 mAttached = true;
352 }
353 ~JavaThreadAttacher() {
354 if (!mAttached) return;
355 auto vm = getJavaVM();
356 LOG_ALWAYS_FATAL_IF(vm == nullptr,
357 "Unable to detach thread. No JavaVM, but it was present before!");
358
359 LOG_RPC_DETAIL("Detaching current thread from JVM");
360 if (vm->DetachCurrentThread() != JNI_OK) {
361 mAttached = false;
362 } else {
363 ALOGW("Unable to detach current thread from JVM");
364 }
365 }
366
367private:
368 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
369 bool mAttached = false;
370
371 static JavaVM* getJavaVM() {
372 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
373 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
374 if (fn == nullptr) return nullptr;
375 return fn();
376 }
377};
Yifan Hongd258e682021-11-01 18:34:42 -0700378#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700379} // namespace
380
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000381void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
382 sp<RpcConnection>& connection = setupResult.connection;
383
384 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700385 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700386 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000387 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000388 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000389 RpcState::CommandType::ANY);
390 if (status != OK) {
391 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
392 statusToString(status).c_str());
393 break;
394 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000396 } else {
397 ALOGE("Connection failed to init, closing with status %s",
398 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000399 }
400
Steven Moreland659416d2021-05-11 00:47:50 +0000401 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000402 {
Steven Moreland659416d2021-05-11 00:47:50 +0000403 std::lock_guard<std::mutex> _l(session->mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700404 auto it = session->mConnections.mThreads.find(std::this_thread::get_id());
405 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000406 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700407 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000408
Steven Moreland659416d2021-05-11 00:47:50 +0000409 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000410 }
411
Steven Morelanddd67b942021-07-23 17:15:41 -0700412 // done after all cleanup, since session shutdown progresses via callbacks here
413 if (connection != nullptr) {
414 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
415 "bad state: connection object guaranteed to be in list");
416 }
417
Steven Moreland659416d2021-05-11 00:47:50 +0000418 session = nullptr;
419
420 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000421 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000422 }
423}
424
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000425sp<RpcServer> RpcSession::server() {
426 RpcServer* unsafeServer = mForServer.unsafe_get();
427 sp<RpcServer> server = mForServer.promote();
428
429 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
430 "wp<> is to avoid strong cycle only");
431 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000432}
433
Steven Moreland826367f2021-09-10 14:05:31 -0700434status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
435 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000436 {
437 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700438 LOG_ALWAYS_FATAL_IF(mConnections.mOutgoing.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000439 "Must only setup session once, but already has %zu clients",
Steven Morelanda59937e2021-10-04 17:42:30 -0700440 mConnections.mOutgoing.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000441 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700442
Yifan Hong832521e2021-08-05 14:55:40 -0700443 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000444
Steven Moreland27a8bc72021-09-29 16:07:41 -0700445 auto oldProtocolVersion = mProtocolVersion;
446 auto cleanup = base::ScopeGuard([&] {
447 // if any threads are started, shut them down
448 (void)shutdownAndWait(true);
449
450 mShutdownListener = nullptr;
451 mEventListener.clear();
452
453 mId.clear();
454
455 mShutdownTrigger = nullptr;
456 mRpcBinderState = std::make_unique<RpcState>();
457
458 // protocol version may have been downgraded - if we reuse this object
459 // to connect to another server, force that server to request a
460 // downgrade again
461 mProtocolVersion = oldProtocolVersion;
462
Steven Morelanda59937e2021-10-04 17:42:30 -0700463 mConnections = {};
Steven Moreland27a8bc72021-09-29 16:07:41 -0700464 });
465
Steven Moreland826367f2021-09-10 14:05:31 -0700466 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000467
Steven Morelandbf57bce2021-07-26 15:26:12 -0700468 {
469 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700470 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
471 ConnectionUse::CLIENT, &connection);
472 status != OK)
473 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700474
475 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700476 if (status_t status =
477 state()->readNewSessionResponse(connection.get(),
478 sp<RpcSession>::fromExisting(this), &version);
479 status != OK)
480 return status;
481 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700482 }
483
Steven Morelanda5036f02021-06-08 02:26:57 +0000484 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000485 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000486 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000487 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700488 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000489 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700490 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000491 }
492
493 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700494 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000495 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700496 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000497 }
498
Yifan Hong1f44f982021-10-08 17:16:47 -0700499 size_t outgoingThreads = std::min(numThreadsAvailable, mMaxOutgoingThreads);
500 ALOGI_IF(outgoingThreads != numThreadsAvailable,
501 "Server hints client to start %zu outgoing threads, but client will only start %zu "
502 "because it is preconfigured to start at most %zu outgoing threads.",
503 numThreadsAvailable, outgoingThreads, mMaxOutgoingThreads);
504
Steven Morelanda5036f02021-06-08 02:26:57 +0000505 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000506 // instead of all at once - the other side should be responsible for setting
507 // up additional connections. We need to create at least one (unless 0 are
508 // requested to be set) in order to allow the other side to reliably make
509 // any requests at all.
510
Steven Moreland4198a122021-08-03 17:37:58 -0700511 // we've already setup one client
Yifan Hong1f44f982021-10-08 17:16:47 -0700512 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing (server max: %zu) and %zu "
513 "incoming threads",
514 outgoingThreads, numThreadsAvailable, mMaxIncomingThreads);
515 for (size_t i = 0; i + 1 < outgoingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700516 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700517 }
518
Yifan Hong10423062021-10-08 16:26:32 -0700519 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700520 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000521 }
522
Steven Moreland27a8bc72021-09-29 16:07:41 -0700523 cleanup.Disable();
524
Steven Moreland2372f9d2021-08-05 15:42:01 -0700525 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000526}
527
Steven Moreland2372f9d2021-08-05 15:42:01 -0700528status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700529 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700530 return setupOneSocketConnection(addr, sessionId, incoming);
531 });
532}
533
Steven Moreland2372f9d2021-08-05 15:42:01 -0700534status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700535 const std::vector<uint8_t>& sessionId,
536 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000537 for (size_t tries = 0; tries < 5; tries++) {
538 if (tries > 0) usleep(10000);
539
Yifan Hongb675ffe2021-08-05 16:37:17 -0700540 unique_fd serverFd(TEMP_FAILURE_RETRY(
541 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000542 if (serverFd == -1) {
543 int savedErrno = errno;
544 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
545 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700546 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000547 }
548
549 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700550 int connErrno = errno;
551 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
552 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
553 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
554 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
555 if (pollStatus != OK) {
556 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
557 statusToString(pollStatus).c_str());
558 return pollStatus;
559 }
560 // Set connErrno to the errno that connect() would have set if the fd were blocking.
561 socklen_t connErrnoLen = sizeof(connErrno);
562 int ret =
563 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
564 if (ret == -1) {
565 int savedErrno = errno;
566 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
567 "(Original error from connect() is: %s)",
568 strerror(savedErrno), strerror(connErrno));
569 return -savedErrno;
570 }
571 // Retrieved the real connErrno as if connect() was called with a blocking socket
572 // fd. Continue checking connErrno.
573 }
574 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000575 ALOGW("Connection reset on %s", addr.toString().c_str());
576 continue;
577 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700578 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
579 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700580 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700581 strerror(connErrno));
582 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700583 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000584 }
Yifan Hong702115c2021-06-24 15:39:18 -0700585 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
586
Steven Moreland4198a122021-08-03 17:37:58 -0700587 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000588 }
589
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000590 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700591 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000592}
593
Steven Moreland826367f2021-09-10 14:05:31 -0700594status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700595 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700596 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700597 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700598 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700599 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700600 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700601 }
602
603 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
604
Steven Moreland826367f2021-09-10 14:05:31 -0700605 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
606 ALOGE("Session ID too big %zu", sessionId.size());
607 return BAD_VALUE;
608 }
609
Steven Moreland4198a122021-08-03 17:37:58 -0700610 RpcConnectionHeader header{
611 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
612 .options = 0,
Steven Moreland826367f2021-09-10 14:05:31 -0700613 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700614 };
Steven Moreland4198a122021-08-03 17:37:58 -0700615
Steven Moreland826367f2021-09-10 14:05:31 -0700616 if (incoming) {
617 header.options |= RPC_CONNECTION_OPTION_INCOMING;
618 }
Steven Moreland4198a122021-08-03 17:37:58 -0700619
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000620 iovec headerIov{&header, sizeof(header)};
Yifan Hong8c950422021-08-05 17:13:55 -0700621 auto sendHeaderStatus =
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000622 server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1, {});
Yifan Hong8c950422021-08-05 17:13:55 -0700623 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700624 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700625 statusToString(sendHeaderStatus).c_str());
626 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700627 }
628
Steven Moreland826367f2021-09-10 14:05:31 -0700629 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000630 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
631 sessionId.size()};
Steven Moreland826367f2021-09-10 14:05:31 -0700632 auto sendSessionIdStatus =
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000633 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1, {});
Steven Moreland826367f2021-09-10 14:05:31 -0700634 if (sendSessionIdStatus != OK) {
635 ALOGE("Could not write session ID ('%s') to socket: %s",
636 base::HexString(sessionId.data(), sessionId.size()).c_str(),
637 statusToString(sendSessionIdStatus).c_str());
638 return sendSessionIdStatus;
639 }
640 }
641
Steven Moreland4198a122021-08-03 17:37:58 -0700642 LOG_RPC_DETAIL("Socket at client: header sent");
643
644 if (incoming) {
645 return addIncomingConnection(std::move(server));
646 } else {
647 return addOutgoingConnection(std::move(server), true /*init*/);
648 }
649}
650
Steven Moreland2372f9d2021-08-05 15:42:01 -0700651status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000652 std::mutex mutex;
653 std::condition_variable joinCv;
654 std::unique_lock<std::mutex> lock(mutex);
655 std::thread thread;
656 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
657 bool ownershipTransferred = false;
658 thread = std::thread([&]() {
659 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700660 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000661 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
662 sp<RpcSession> session = thiz;
663 session->preJoinThreadOwnership(std::move(thread));
664
665 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700666 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000667
668 ownershipTransferred = true;
669 threadLock.unlock();
670 joinCv.notify_one();
671 // do not use & vars below
672
673 RpcSession::join(std::move(session), std::move(setupResult));
674 });
675 joinCv.wait(lock, [&] { return ownershipTransferred; });
676 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700677 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000678}
679
Yifan Hong832521e2021-08-05 14:55:40 -0700680status_t RpcSession::initShutdownTrigger() {
681 // first client connection added, but setForServer not called, so
682 // initializaing for a client.
683 if (mShutdownTrigger == nullptr) {
684 mShutdownTrigger = FdTrigger::make();
685 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
686 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
687 }
688 return OK;
689}
690
Steven Moreland2372f9d2021-08-05 15:42:01 -0700691status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000692 sp<RpcConnection> connection = sp<RpcConnection>::make();
693 {
694 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700695 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000696 connection->exclusiveTid = gettid();
Steven Morelanda59937e2021-10-04 17:42:30 -0700697 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000698 }
699
Steven Morelandb86e26b2021-06-12 00:35:58 +0000700 status_t status = OK;
701 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700702 status =
703 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000704 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000705
706 {
707 std::lock_guard<std::mutex> _l(mMutex);
708 connection->exclusiveTid = std::nullopt;
709 }
710
Steven Moreland2372f9d2021-08-05 15:42:01 -0700711 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000712}
713
Steven Morelanda8b44292021-06-08 01:27:53 +0000714bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700715 const std::vector<uint8_t>& sessionId,
716 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000717 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
718 LOG_ALWAYS_FATAL_IF(server == nullptr);
719 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
720 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000721 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000722
723 mShutdownTrigger = FdTrigger::make();
724 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000725
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000726 mId = sessionId;
727 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000728 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700729 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000730 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000731}
732
Yifan Hong702115c2021-06-24 15:39:18 -0700733sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
734 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000735 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700736
Yifan Hong10423062021-10-08 16:26:32 -0700737 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700738 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700739 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700740 return nullptr;
741 }
742
Steven Morelanddd67b942021-07-23 17:15:41 -0700743 // Don't accept any more connections, some have shutdown. Usually this
744 // happens when new connections are still being established as part of a
745 // very short-lived session which shuts down after it already started
746 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700747 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700748 return nullptr;
749 }
750
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000751 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700752 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000753 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700754
Steven Morelanda59937e2021-10-04 17:42:30 -0700755 mConnections.mIncoming.push_back(session);
756 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000757
758 return session;
759}
760
Steven Moreland19fc9f72021-06-10 03:57:30 +0000761bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700762 std::unique_lock<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700763 if (auto it =
764 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
765 it != mConnections.mIncoming.end()) {
766 mConnections.mIncoming.erase(it);
767 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000768 sp<EventListener> listener = mEventListener.promote();
769 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700770 _l.unlock();
771 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000772 }
Steven Morelandee78e762021-05-05 21:12:51 +0000773 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000774 return true;
775 }
776 return false;
777}
778
Yifan Hong9734cfc2021-09-13 16:14:09 -0700779std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700780 return mCtx->getCertificate(format);
781}
782
Steven Moreland195edb82021-06-08 02:44:39 +0000783status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
784 ExclusiveConnection* connection) {
785 connection->mSession = session;
786 connection->mConnection = nullptr;
787 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000788
Steven Moreland195edb82021-06-08 02:44:39 +0000789 pid_t tid = gettid();
790 std::unique_lock<std::mutex> _l(session->mMutex);
791
Steven Morelanda59937e2021-10-04 17:42:30 -0700792 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000793 while (true) {
794 sp<RpcConnection> exclusive;
795 sp<RpcConnection> available;
796
797 // CHECK FOR DEDICATED CLIENT SOCKET
798 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000799 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700800 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
801 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000802
803 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700804 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000805 //
806 // Imagine we have more than one thread in play, and a single thread
807 // sends a synchronous, then an asynchronous command. Imagine the
808 // asynchronous command is sent on the first client connection. Then, if
809 // we naively send a synchronous command to that same connection, the
810 // thread on the far side might be busy processing the asynchronous
811 // command. So, we move to considering the second available thread
812 // for subsequent calls.
813 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700814 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
815 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000816 }
817
Steven Morelandc7d40132021-06-10 03:42:11 +0000818 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000819 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000820 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000821 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000822 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700823 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000824
825 // asynchronous calls cannot be nested, we currently allow ref count
826 // calls to be nested (so that you can use this without having extra
827 // threads). Note 'drainCommands' is used so that these ref counts can't
828 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000829 if (exclusiveIncoming != nullptr) {
830 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000831 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000832 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000833 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
834 // prefer available socket, but if we don't have one, don't
835 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000836 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000837 }
838 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000839 }
840
Steven Moreland85e067b2021-05-26 17:43:53 +0000841 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000842 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000843 connection->mConnection = exclusive;
844 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000845 break;
846 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000847 connection->mConnection = available;
848 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000849 break;
850 }
851
Steven Morelanda59937e2021-10-04 17:42:30 -0700852 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000853 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
854 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
855 "reason: %d. Incoming connections: %zu. %s.",
856 static_cast<int>(use), session->mConnections.mIncoming.size(),
857 (session->server()
858 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
859 "for the corresponding client"
860 : "This is a client session, so see RpcSession::setMaxOutgoingThreads "
861 "for this client or RpcServer::setMaxThreads for the corresponding "
862 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000863 return WOULD_BLOCK;
864 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000865
Steven Moreland85e067b2021-05-26 17:43:53 +0000866 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700867 session->mConnections.mOutgoing.size(),
868 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000869 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000870 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700871 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000872
873 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000874}
875
876void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
877 sp<RpcConnection>* available,
878 std::vector<sp<RpcConnection>>& sockets,
879 size_t socketsIndexHint) {
880 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
881 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
882
883 if (*exclusive != nullptr) return; // consistent with break below
884
885 for (size_t i = 0; i < sockets.size(); i++) {
886 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
887
Steven Moreland85e067b2021-05-26 17:43:53 +0000888 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000889 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
890 *available = socket;
891 continue;
892 }
893
Steven Moreland85e067b2021-05-26 17:43:53 +0000894 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000895 // (nested transactions)
896 if (exclusive && socket->exclusiveTid == tid) {
897 *exclusive = socket;
898 break; // consistent with return above
899 }
900 }
901}
902
903RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000904 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000905 // is using this fd, and it retains the right to it. So, we don't give up
906 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000907 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000908 std::unique_lock<std::mutex> _l(mSession->mMutex);
909 mConnection->exclusiveTid = std::nullopt;
Steven Morelanda59937e2021-10-04 17:42:30 -0700910 if (mSession->mConnections.mWaitingThreads > 0) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000911 _l.unlock();
912 mSession->mAvailableConnectionCv.notify_one();
913 }
914 }
915}
916
917} // namespace android