blob: 6c48c8866184a2e3f31c1cd09603330f2bc45072 [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
Yifan Hongd258e682021-11-01 18:34:42 -070046#ifndef __ANDROID_RECOVERY__
47#include <android_runtime/vm.h>
48#include <jni.h>
49#endif
50
Steven Morelandbdb53ab2021-05-05 17:57:41 +000051namespace android {
52
53using base::unique_fd;
54
Yifan Hongecf937d2021-08-11 17:29:28 -070055RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000056 LOG_RPC_DETAIL("RpcSession created %p", this);
57
Steven Moreland27a8bc72021-09-29 16:07:41 -070058 mRpcBinderState = std::make_unique<RpcState>();
Steven Morelandbdb53ab2021-05-05 17:57:41 +000059}
60RpcSession::~RpcSession() {
61 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
62
63 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070064 LOG_ALWAYS_FATAL_IF(mConnections.mIncoming.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000065 "Should not be able to destroy a session with servers in use.");
66}
67
Yifan Hongecf937d2021-08-11 17:29:28 -070068sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070069 // Default is without TLS.
Yifan Hongfdd9f692021-09-09 15:12:52 -070070 return make(RpcTransportCtxFactoryRaw::make());
Yifan Hongecf937d2021-08-11 17:29:28 -070071}
72
Yifan Hongfdd9f692021-09-09 15:12:52 -070073sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070074 auto ctx = rpcTransportCtxFactory->newClientCtx();
75 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070076 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000077}
78
Yifan Hong10423062021-10-08 16:26:32 -070079void RpcSession::setMaxIncomingThreads(size_t threads) {
Steven Moreland103424e2021-06-02 18:16:19 +000080 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070081 LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
Yifan Hong10423062021-10-08 16:26:32 -070082 "Must set max incoming threads before setting up connections, but has %zu "
83 "client(s) and %zu server(s)",
Steven Morelanda59937e2021-10-04 17:42:30 -070084 mConnections.mOutgoing.size(), mConnections.mIncoming.size());
Yifan Hong10423062021-10-08 16:26:32 -070085 mMaxIncomingThreads = threads;
Steven Moreland103424e2021-06-02 18:16:19 +000086}
87
Yifan Hong10423062021-10-08 16:26:32 -070088size_t RpcSession::getMaxIncomingThreads() {
Steven Moreland103424e2021-06-02 18:16:19 +000089 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong10423062021-10-08 16:26:32 -070090 return mMaxIncomingThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000091}
92
Yifan Hong1f44f982021-10-08 17:16:47 -070093void RpcSession::setMaxOutgoingThreads(size_t threads) {
94 std::lock_guard<std::mutex> _l(mMutex);
95 LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
96 "Must set max outgoing threads before setting up connections, but has %zu "
97 "client(s) and %zu server(s)",
98 mConnections.mOutgoing.size(), mConnections.mIncoming.size());
99 mMaxOutgoingThreads = threads;
100}
101
102size_t RpcSession::getMaxOutgoingThreads() {
103 std::lock_guard<std::mutex> _l(mMutex);
104 return mMaxOutgoingThreads;
105}
106
Steven Morelandbf57bce2021-07-26 15:26:12 -0700107bool RpcSession::setProtocolVersion(uint32_t version) {
108 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
109 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
110 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
111 "is %u).",
112 version, RPC_WIRE_PROTOCOL_VERSION);
113 return false;
114 }
115
116 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -0700117 if (mProtocolVersion && version > *mProtocolVersion) {
118 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
119 *mProtocolVersion, version);
120 return false;
121 }
122
Steven Morelandbf57bce2021-07-26 15:26:12 -0700123 mProtocolVersion = version;
124 return true;
125}
126
127std::optional<uint32_t> RpcSession::getProtocolVersion() {
128 std::lock_guard<std::mutex> _l(mMutex);
129 return mProtocolVersion;
130}
131
Steven Moreland2372f9d2021-08-05 15:42:01 -0700132status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000133 return setupSocketClient(UnixSocketAddress(path));
134}
135
Steven Moreland2372f9d2021-08-05 15:42:01 -0700136status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000137 return setupSocketClient(VsockSocketAddress(cid, port));
138}
139
Steven Moreland2372f9d2021-08-05 15:42:01 -0700140status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000141 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700142 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000143 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
144 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700145 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000146 }
147 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 -0700148 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000149}
150
Steven Moreland2372f9d2021-08-05 15:42:01 -0700151status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
Frederick Mayle297c2772022-05-05 01:21:04 +0000152 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700153 if (!fd.ok()) {
154 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700155 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700156 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700157 if (auto res = setNonBlocking(fd); !res.ok()) {
158 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
159 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
160 }
Frederick Mayle297c2772022-05-05 01:21:04 +0000161 status_t status = initAndAddConnection(std::move(fd), sessionId, incoming);
162 fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
163 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700164 });
165}
166
Steven Moreland2372f9d2021-08-05 15:42:01 -0700167status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700168 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700169 if (auto status = initShutdownTrigger(); status != OK) return status;
170
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000171 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
172
173 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700174 int savedErrno = errno;
175 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
176 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000177 }
178
Yifan Hongecf937d2021-08-11 17:29:28 -0700179 auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700180 if (server == nullptr) {
181 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700182 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700183 }
184 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000185}
186
187sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000188 ExclusiveConnection connection;
189 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
190 ConnectionUse::CLIENT, &connection);
191 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000192 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000193}
194
Steven Moreland1be91352021-05-11 22:12:15 +0000195status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000196 ExclusiveConnection connection;
197 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
198 ConnectionUse::CLIENT, &connection);
199 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000200 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000201}
202
Steven Morelandc9d7b532021-06-04 20:57:41 +0000203bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000204 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000205 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000206
207 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000208
Steven Morelandc9d7b532021-06-04 20:57:41 +0000209 if (wait) {
210 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700211 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700212
Steven Morelanda59937e2021-10-04 17:42:30 -0700213 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000214 }
215
216 _l.unlock();
Steven Moreland27a8bc72021-09-29 16:07:41 -0700217 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000218
Steven Moreland659416d2021-05-11 00:47:50 +0000219 return true;
220}
221
Steven Morelandf5174272021-05-25 00:39:28 +0000222status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000223 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000224 ExclusiveConnection connection;
225 status_t status =
226 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
227 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
228 : ConnectionUse::CLIENT,
229 &connection);
230 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000231 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000232 sp<RpcSession>::fromExisting(this), reply, flags);
233}
234
Steven Moreland4f622fe2021-09-13 17:38:09 -0700235status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000236 // target is 0 because this is used to free BpBinder objects
237 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700238}
239
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000240status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000241 ExclusiveConnection connection;
242 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
243 ConnectionUse::CLIENT_REFCOUNT, &connection);
244 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000245 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
246 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000247}
248
249status_t RpcSession::readId() {
250 {
251 std::lock_guard<std::mutex> _l(mMutex);
252 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
253 }
254
Steven Moreland195edb82021-06-08 02:44:39 +0000255 ExclusiveConnection connection;
256 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
257 ConnectionUse::CLIENT, &connection);
258 if (status != OK) return status;
259
Steven Moreland826367f2021-09-10 14:05:31 -0700260 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000261 if (status != OK) return status;
262
Steven Moreland826367f2021-09-10 14:05:31 -0700263 LOG_RPC_DETAIL("RpcSession %p has id %s", this,
264 base::HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000265 return OK;
266}
267
Steven Morelanddd67b942021-07-23 17:15:41 -0700268void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000269 const sp<RpcSession>& session) {
270 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000271}
272
Steven Moreland19fc9f72021-06-10 03:57:30 +0000273void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000274 mCv.notify_all();
275}
276
Steven Moreland791e4662021-09-13 15:22:58 -0700277void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock,
278 const sp<RpcSession>& session) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700279 while (session->mConnections.mIncoming.size() > 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000280 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700281 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
282 "still.",
Steven Morelanda59937e2021-10-04 17:42:30 -0700283 session->mConnections.mIncoming.size());
Steven Moreland659416d2021-05-11 00:47:50 +0000284 }
285 }
286}
287
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000288void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000289 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000290
Steven Morelanda63ff932021-05-12 00:03:15 +0000291 {
292 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700293 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000294 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000295}
Steven Morelanda63ff932021-05-12 00:03:15 +0000296
Yifan Hong702115c2021-06-24 15:39:18 -0700297RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
298 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000299 // must be registered to allow arbitrary client code executing commands to
300 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700301 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000302
Steven Morelanddd67b942021-07-23 17:15:41 -0700303 status_t status;
304
305 if (connection == nullptr) {
306 status = DEAD_OBJECT;
307 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700308 status =
309 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700310 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000311
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000312 return PreJoinSetupResult{
313 .connection = std::move(connection),
314 .status = status,
315 };
316}
317
Yifan Hong194acf22021-06-29 18:44:56 -0700318namespace {
Yifan Hongd258e682021-11-01 18:34:42 -0700319#ifdef __ANDROID_RECOVERY__
320class JavaThreadAttacher {};
321#else
Yifan Hong194acf22021-06-29 18:44:56 -0700322// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
323// Android Runtime doesn't exist, no-op.
324class JavaThreadAttacher {
325public:
326 JavaThreadAttacher() {
327 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
328 // libbinder.
329 auto vm = getJavaVM();
330 if (vm == nullptr) return;
331
332 char threadName[16];
333 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
334 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
335 memcpy(threadName, defaultThreadName,
336 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
337 }
338 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
339 JavaVMAttachArgs args;
340 args.version = JNI_VERSION_1_2;
341 args.name = threadName;
342 args.group = nullptr;
343 JNIEnv* env;
344
345 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
346 "Cannot attach thread %s to JVM", threadName);
347 mAttached = true;
348 }
349 ~JavaThreadAttacher() {
350 if (!mAttached) return;
351 auto vm = getJavaVM();
352 LOG_ALWAYS_FATAL_IF(vm == nullptr,
353 "Unable to detach thread. No JavaVM, but it was present before!");
354
355 LOG_RPC_DETAIL("Detaching current thread from JVM");
356 if (vm->DetachCurrentThread() != JNI_OK) {
357 mAttached = false;
358 } else {
359 ALOGW("Unable to detach current thread from JVM");
360 }
361 }
362
363private:
364 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
365 bool mAttached = false;
366
367 static JavaVM* getJavaVM() {
368 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
369 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
370 if (fn == nullptr) return nullptr;
371 return fn();
372 }
373};
Yifan Hongd258e682021-11-01 18:34:42 -0700374#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700375} // namespace
376
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000377void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
378 sp<RpcConnection>& connection = setupResult.connection;
379
380 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700381 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700382 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000383 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000384 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000385 RpcState::CommandType::ANY);
386 if (status != OK) {
387 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
388 statusToString(status).c_str());
389 break;
390 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000391 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000392 } else {
393 ALOGE("Connection failed to init, closing with status %s",
394 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395 }
396
Steven Moreland659416d2021-05-11 00:47:50 +0000397 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000398 {
Steven Moreland659416d2021-05-11 00:47:50 +0000399 std::lock_guard<std::mutex> _l(session->mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700400 auto it = session->mConnections.mThreads.find(std::this_thread::get_id());
401 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000402 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700403 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000404
Steven Moreland659416d2021-05-11 00:47:50 +0000405 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000406 }
407
Steven Morelanddd67b942021-07-23 17:15:41 -0700408 // done after all cleanup, since session shutdown progresses via callbacks here
409 if (connection != nullptr) {
410 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
411 "bad state: connection object guaranteed to be in list");
412 }
413
Steven Moreland659416d2021-05-11 00:47:50 +0000414 session = nullptr;
415
416 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000417 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000418 }
419}
420
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000421sp<RpcServer> RpcSession::server() {
422 RpcServer* unsafeServer = mForServer.unsafe_get();
423 sp<RpcServer> server = mForServer.promote();
424
425 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
426 "wp<> is to avoid strong cycle only");
427 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000428}
429
Steven Moreland826367f2021-09-10 14:05:31 -0700430status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
431 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000432 {
433 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700434 LOG_ALWAYS_FATAL_IF(mConnections.mOutgoing.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000435 "Must only setup session once, but already has %zu clients",
Steven Morelanda59937e2021-10-04 17:42:30 -0700436 mConnections.mOutgoing.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000437 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700438
Yifan Hong832521e2021-08-05 14:55:40 -0700439 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440
Steven Moreland27a8bc72021-09-29 16:07:41 -0700441 auto oldProtocolVersion = mProtocolVersion;
442 auto cleanup = base::ScopeGuard([&] {
443 // if any threads are started, shut them down
444 (void)shutdownAndWait(true);
445
446 mShutdownListener = nullptr;
447 mEventListener.clear();
448
449 mId.clear();
450
451 mShutdownTrigger = nullptr;
452 mRpcBinderState = std::make_unique<RpcState>();
453
454 // protocol version may have been downgraded - if we reuse this object
455 // to connect to another server, force that server to request a
456 // downgrade again
457 mProtocolVersion = oldProtocolVersion;
458
Steven Morelanda59937e2021-10-04 17:42:30 -0700459 mConnections = {};
Steven Moreland27a8bc72021-09-29 16:07:41 -0700460 });
461
Steven Moreland826367f2021-09-10 14:05:31 -0700462 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000463
Steven Morelandbf57bce2021-07-26 15:26:12 -0700464 {
465 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700466 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
467 ConnectionUse::CLIENT, &connection);
468 status != OK)
469 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700470
471 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700472 if (status_t status =
473 state()->readNewSessionResponse(connection.get(),
474 sp<RpcSession>::fromExisting(this), &version);
475 status != OK)
476 return status;
477 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700478 }
479
Steven Morelanda5036f02021-06-08 02:26:57 +0000480 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000481 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000482 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000483 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700484 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000485 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700486 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000487 }
488
489 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700490 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000491 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700492 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000493 }
494
Yifan Hong1f44f982021-10-08 17:16:47 -0700495 size_t outgoingThreads = std::min(numThreadsAvailable, mMaxOutgoingThreads);
496 ALOGI_IF(outgoingThreads != numThreadsAvailable,
497 "Server hints client to start %zu outgoing threads, but client will only start %zu "
498 "because it is preconfigured to start at most %zu outgoing threads.",
499 numThreadsAvailable, outgoingThreads, mMaxOutgoingThreads);
500
Steven Morelanda5036f02021-06-08 02:26:57 +0000501 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000502 // instead of all at once - the other side should be responsible for setting
503 // up additional connections. We need to create at least one (unless 0 are
504 // requested to be set) in order to allow the other side to reliably make
505 // any requests at all.
506
Steven Moreland4198a122021-08-03 17:37:58 -0700507 // we've already setup one client
Yifan Hong1f44f982021-10-08 17:16:47 -0700508 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing (server max: %zu) and %zu "
509 "incoming threads",
510 outgoingThreads, numThreadsAvailable, mMaxIncomingThreads);
511 for (size_t i = 0; i + 1 < outgoingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700512 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700513 }
514
Yifan Hong10423062021-10-08 16:26:32 -0700515 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700516 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000517 }
518
Steven Moreland27a8bc72021-09-29 16:07:41 -0700519 cleanup.Disable();
520
Steven Moreland2372f9d2021-08-05 15:42:01 -0700521 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000522}
523
Steven Moreland2372f9d2021-08-05 15:42:01 -0700524status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700525 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700526 return setupOneSocketConnection(addr, sessionId, incoming);
527 });
528}
529
Steven Moreland2372f9d2021-08-05 15:42:01 -0700530status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700531 const std::vector<uint8_t>& sessionId,
532 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000533 for (size_t tries = 0; tries < 5; tries++) {
534 if (tries > 0) usleep(10000);
535
Yifan Hongb675ffe2021-08-05 16:37:17 -0700536 unique_fd serverFd(TEMP_FAILURE_RETRY(
537 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000538 if (serverFd == -1) {
539 int savedErrno = errno;
540 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
541 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700542 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000543 }
544
545 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700546 int connErrno = errno;
547 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
548 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
549 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
550 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
551 if (pollStatus != OK) {
552 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
553 statusToString(pollStatus).c_str());
554 return pollStatus;
555 }
556 // Set connErrno to the errno that connect() would have set if the fd were blocking.
557 socklen_t connErrnoLen = sizeof(connErrno);
558 int ret =
559 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
560 if (ret == -1) {
561 int savedErrno = errno;
562 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
563 "(Original error from connect() is: %s)",
564 strerror(savedErrno), strerror(connErrno));
565 return -savedErrno;
566 }
567 // Retrieved the real connErrno as if connect() was called with a blocking socket
568 // fd. Continue checking connErrno.
569 }
570 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000571 ALOGW("Connection reset on %s", addr.toString().c_str());
572 continue;
573 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700574 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
575 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700576 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700577 strerror(connErrno));
578 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700579 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000580 }
Yifan Hong702115c2021-06-24 15:39:18 -0700581 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
582
Steven Moreland4198a122021-08-03 17:37:58 -0700583 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000584 }
585
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000586 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700587 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000588}
589
Steven Moreland826367f2021-09-10 14:05:31 -0700590status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700591 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700592 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700593 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700594 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700595 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700596 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700597 }
598
599 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
600
Steven Moreland826367f2021-09-10 14:05:31 -0700601 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
602 ALOGE("Session ID too big %zu", sessionId.size());
603 return BAD_VALUE;
604 }
605
Steven Moreland4198a122021-08-03 17:37:58 -0700606 RpcConnectionHeader header{
607 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
608 .options = 0,
Steven Moreland826367f2021-09-10 14:05:31 -0700609 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700610 };
Steven Moreland4198a122021-08-03 17:37:58 -0700611
Steven Moreland826367f2021-09-10 14:05:31 -0700612 if (incoming) {
613 header.options |= RPC_CONNECTION_OPTION_INCOMING;
614 }
Steven Moreland4198a122021-08-03 17:37:58 -0700615
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000616 iovec headerIov{&header, sizeof(header)};
Yifan Hong8c950422021-08-05 17:13:55 -0700617 auto sendHeaderStatus =
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000618 server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1, {});
Yifan Hong8c950422021-08-05 17:13:55 -0700619 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700620 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700621 statusToString(sendHeaderStatus).c_str());
622 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700623 }
624
Steven Moreland826367f2021-09-10 14:05:31 -0700625 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000626 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
627 sessionId.size()};
Steven Moreland826367f2021-09-10 14:05:31 -0700628 auto sendSessionIdStatus =
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000629 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1, {});
Steven Moreland826367f2021-09-10 14:05:31 -0700630 if (sendSessionIdStatus != OK) {
631 ALOGE("Could not write session ID ('%s') to socket: %s",
632 base::HexString(sessionId.data(), sessionId.size()).c_str(),
633 statusToString(sendSessionIdStatus).c_str());
634 return sendSessionIdStatus;
635 }
636 }
637
Steven Moreland4198a122021-08-03 17:37:58 -0700638 LOG_RPC_DETAIL("Socket at client: header sent");
639
640 if (incoming) {
641 return addIncomingConnection(std::move(server));
642 } else {
643 return addOutgoingConnection(std::move(server), true /*init*/);
644 }
645}
646
Steven Moreland2372f9d2021-08-05 15:42:01 -0700647status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000648 std::mutex mutex;
649 std::condition_variable joinCv;
650 std::unique_lock<std::mutex> lock(mutex);
651 std::thread thread;
652 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
653 bool ownershipTransferred = false;
654 thread = std::thread([&]() {
655 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700656 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000657 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
658 sp<RpcSession> session = thiz;
659 session->preJoinThreadOwnership(std::move(thread));
660
661 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700662 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000663
664 ownershipTransferred = true;
665 threadLock.unlock();
666 joinCv.notify_one();
667 // do not use & vars below
668
669 RpcSession::join(std::move(session), std::move(setupResult));
670 });
671 joinCv.wait(lock, [&] { return ownershipTransferred; });
672 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700673 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000674}
675
Yifan Hong832521e2021-08-05 14:55:40 -0700676status_t RpcSession::initShutdownTrigger() {
677 // first client connection added, but setForServer not called, so
678 // initializaing for a client.
679 if (mShutdownTrigger == nullptr) {
680 mShutdownTrigger = FdTrigger::make();
681 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
682 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
683 }
684 return OK;
685}
686
Steven Moreland2372f9d2021-08-05 15:42:01 -0700687status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000688 sp<RpcConnection> connection = sp<RpcConnection>::make();
689 {
690 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700691 connection->rpcTransport = std::move(rpcTransport);
Andrei Homescue922b232022-04-23 03:41:09 +0000692 connection->exclusiveTid = base::GetThreadId();
Steven Morelanda59937e2021-10-04 17:42:30 -0700693 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000694 }
695
Steven Morelandb86e26b2021-06-12 00:35:58 +0000696 status_t status = OK;
697 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700698 status =
699 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000700 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000701
702 {
703 std::lock_guard<std::mutex> _l(mMutex);
704 connection->exclusiveTid = std::nullopt;
705 }
706
Steven Moreland2372f9d2021-08-05 15:42:01 -0700707 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000708}
709
Steven Morelanda8b44292021-06-08 01:27:53 +0000710bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700711 const std::vector<uint8_t>& sessionId,
712 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000713 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
714 LOG_ALWAYS_FATAL_IF(server == nullptr);
715 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
716 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000717 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000718
719 mShutdownTrigger = FdTrigger::make();
720 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000721
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000722 mId = sessionId;
723 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000724 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700725 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000726 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000727}
728
Yifan Hong702115c2021-06-24 15:39:18 -0700729sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
730 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000731 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700732
Yifan Hong10423062021-10-08 16:26:32 -0700733 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700734 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700735 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700736 return nullptr;
737 }
738
Steven Morelanddd67b942021-07-23 17:15:41 -0700739 // Don't accept any more connections, some have shutdown. Usually this
740 // happens when new connections are still being established as part of a
741 // very short-lived session which shuts down after it already started
742 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700743 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700744 return nullptr;
745 }
746
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000747 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700748 session->rpcTransport = std::move(rpcTransport);
Andrei Homescue922b232022-04-23 03:41:09 +0000749 session->exclusiveTid = base::GetThreadId();
Steven Morelanddd67b942021-07-23 17:15:41 -0700750
Steven Morelanda59937e2021-10-04 17:42:30 -0700751 mConnections.mIncoming.push_back(session);
752 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000753
754 return session;
755}
756
Steven Moreland19fc9f72021-06-10 03:57:30 +0000757bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700758 std::unique_lock<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700759 if (auto it =
760 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
761 it != mConnections.mIncoming.end()) {
762 mConnections.mIncoming.erase(it);
763 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000764 sp<EventListener> listener = mEventListener.promote();
765 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700766 _l.unlock();
767 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000768 }
Steven Morelandee78e762021-05-05 21:12:51 +0000769 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000770 return true;
771 }
772 return false;
773}
774
Yifan Hong9734cfc2021-09-13 16:14:09 -0700775std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700776 return mCtx->getCertificate(format);
777}
778
Steven Moreland195edb82021-06-08 02:44:39 +0000779status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
780 ExclusiveConnection* connection) {
781 connection->mSession = session;
782 connection->mConnection = nullptr;
783 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000784
Andrei Homescue922b232022-04-23 03:41:09 +0000785 uint64_t tid = base::GetThreadId();
Steven Moreland195edb82021-06-08 02:44:39 +0000786 std::unique_lock<std::mutex> _l(session->mMutex);
787
Steven Morelanda59937e2021-10-04 17:42:30 -0700788 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000789 while (true) {
790 sp<RpcConnection> exclusive;
791 sp<RpcConnection> available;
792
793 // CHECK FOR DEDICATED CLIENT SOCKET
794 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000795 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700796 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
797 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000798
799 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700800 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000801 //
802 // Imagine we have more than one thread in play, and a single thread
803 // sends a synchronous, then an asynchronous command. Imagine the
804 // asynchronous command is sent on the first client connection. Then, if
805 // we naively send a synchronous command to that same connection, the
806 // thread on the far side might be busy processing the asynchronous
807 // command. So, we move to considering the second available thread
808 // for subsequent calls.
809 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700810 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
811 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000812 }
813
Steven Morelandc7d40132021-06-10 03:42:11 +0000814 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000815 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000816 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000817 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000818 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700819 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000820
821 // asynchronous calls cannot be nested, we currently allow ref count
822 // calls to be nested (so that you can use this without having extra
823 // threads). Note 'drainCommands' is used so that these ref counts can't
824 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000825 if (exclusiveIncoming != nullptr) {
826 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000827 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000828 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000829 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
830 // prefer available socket, but if we don't have one, don't
831 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000832 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000833 }
834 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000835 }
836
Steven Moreland85e067b2021-05-26 17:43:53 +0000837 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000838 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000839 connection->mConnection = exclusive;
840 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000841 break;
842 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000843 connection->mConnection = available;
844 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000845 break;
846 }
847
Steven Morelanda59937e2021-10-04 17:42:30 -0700848 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000849 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
850 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
851 "reason: %d. Incoming connections: %zu. %s.",
852 static_cast<int>(use), session->mConnections.mIncoming.size(),
853 (session->server()
854 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
855 "for the corresponding client"
856 : "This is a client session, so see RpcSession::setMaxOutgoingThreads "
857 "for this client or RpcServer::setMaxThreads for the corresponding "
858 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000859 return WOULD_BLOCK;
860 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000861
Steven Moreland85e067b2021-05-26 17:43:53 +0000862 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700863 session->mConnections.mOutgoing.size(),
864 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000865 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000866 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700867 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000868
869 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000870}
871
Andrei Homescue922b232022-04-23 03:41:09 +0000872void RpcSession::ExclusiveConnection::findConnection(uint64_t tid, sp<RpcConnection>* exclusive,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000873 sp<RpcConnection>* available,
874 std::vector<sp<RpcConnection>>& sockets,
875 size_t socketsIndexHint) {
876 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
877 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
878
879 if (*exclusive != nullptr) return; // consistent with break below
880
881 for (size_t i = 0; i < sockets.size(); i++) {
882 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
883
Steven Moreland85e067b2021-05-26 17:43:53 +0000884 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000885 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
886 *available = socket;
887 continue;
888 }
889
Steven Moreland85e067b2021-05-26 17:43:53 +0000890 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000891 // (nested transactions)
892 if (exclusive && socket->exclusiveTid == tid) {
893 *exclusive = socket;
894 break; // consistent with return above
895 }
896 }
897}
898
899RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000900 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000901 // is using this fd, and it retains the right to it. So, we don't give up
902 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000903 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000904 std::unique_lock<std::mutex> _l(mSession->mMutex);
905 mConnection->exclusiveTid = std::nullopt;
Steven Morelanda59937e2021-10-04 17:42:30 -0700906 if (mSession->mConnections.mWaitingThreads > 0) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000907 _l.unlock();
908 mSession->mAvailableConnectionCv.notify_one();
909 }
910 }
911}
912
913} // namespace android