blob: d40778a3d8a79e7c13a706f6bb914e72e07baa15 [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>
37#include <utils/String8.h>
38
Yifan Hong8c950422021-08-05 17:13:55 -070039#include "FdTrigger.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000040#include "RpcSocketAddress.h"
41#include "RpcState.h"
42#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070043#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000044
45#ifdef __GLIBC__
46extern "C" pid_t gettid();
47#endif
48
Yifan Hongd258e682021-11-01 18:34:42 -070049#ifndef __ANDROID_RECOVERY__
50#include <android_runtime/vm.h>
51#include <jni.h>
52#endif
53
Steven Morelandbdb53ab2021-05-05 17:57:41 +000054namespace android {
55
56using base::unique_fd;
57
Yifan Hongecf937d2021-08-11 17:29:28 -070058RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000059 LOG_RPC_DETAIL("RpcSession created %p", this);
60
Steven Moreland27a8bc72021-09-29 16:07:41 -070061 mRpcBinderState = std::make_unique<RpcState>();
Steven Morelandbdb53ab2021-05-05 17:57:41 +000062}
63RpcSession::~RpcSession() {
64 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
65
66 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070067 LOG_ALWAYS_FATAL_IF(mConnections.mIncoming.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000068 "Should not be able to destroy a session with servers in use.");
69}
70
Yifan Hongecf937d2021-08-11 17:29:28 -070071sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070072 // Default is without TLS.
Yifan Hongfdd9f692021-09-09 15:12:52 -070073 return make(RpcTransportCtxFactoryRaw::make());
Yifan Hongecf937d2021-08-11 17:29:28 -070074}
75
Yifan Hongfdd9f692021-09-09 15:12:52 -070076sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070077 auto ctx = rpcTransportCtxFactory->newClientCtx();
78 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070079 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000080}
81
Yifan Hong10423062021-10-08 16:26:32 -070082void RpcSession::setMaxIncomingThreads(size_t threads) {
Steven Moreland103424e2021-06-02 18:16:19 +000083 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070084 LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
Yifan Hong10423062021-10-08 16:26:32 -070085 "Must set max incoming threads before setting up connections, but has %zu "
86 "client(s) and %zu server(s)",
Steven Morelanda59937e2021-10-04 17:42:30 -070087 mConnections.mOutgoing.size(), mConnections.mIncoming.size());
Yifan Hong10423062021-10-08 16:26:32 -070088 mMaxIncomingThreads = threads;
Steven Moreland103424e2021-06-02 18:16:19 +000089}
90
Yifan Hong10423062021-10-08 16:26:32 -070091size_t RpcSession::getMaxIncomingThreads() {
Steven Moreland103424e2021-06-02 18:16:19 +000092 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong10423062021-10-08 16:26:32 -070093 return mMaxIncomingThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000094}
95
Yifan Hong1f44f982021-10-08 17:16:47 -070096void RpcSession::setMaxOutgoingThreads(size_t threads) {
97 std::lock_guard<std::mutex> _l(mMutex);
98 LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
99 "Must set max outgoing threads before setting up connections, but has %zu "
100 "client(s) and %zu server(s)",
101 mConnections.mOutgoing.size(), mConnections.mIncoming.size());
102 mMaxOutgoingThreads = threads;
103}
104
105size_t RpcSession::getMaxOutgoingThreads() {
106 std::lock_guard<std::mutex> _l(mMutex);
107 return mMaxOutgoingThreads;
108}
109
Steven Morelandbf57bce2021-07-26 15:26:12 -0700110bool RpcSession::setProtocolVersion(uint32_t version) {
111 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
112 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
113 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
114 "is %u).",
115 version, RPC_WIRE_PROTOCOL_VERSION);
116 return false;
117 }
118
119 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -0700120 if (mProtocolVersion && version > *mProtocolVersion) {
121 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
122 *mProtocolVersion, version);
123 return false;
124 }
125
Steven Morelandbf57bce2021-07-26 15:26:12 -0700126 mProtocolVersion = version;
127 return true;
128}
129
130std::optional<uint32_t> RpcSession::getProtocolVersion() {
131 std::lock_guard<std::mutex> _l(mMutex);
132 return mProtocolVersion;
133}
134
Steven Moreland2372f9d2021-08-05 15:42:01 -0700135status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000136 return setupSocketClient(UnixSocketAddress(path));
137}
138
Steven Moreland2372f9d2021-08-05 15:42:01 -0700139status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000140 return setupSocketClient(VsockSocketAddress(cid, port));
141}
142
Steven Moreland2372f9d2021-08-05 15:42:01 -0700143status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000144 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700145 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000146 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
147 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700148 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000149 }
150 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 -0700151 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000152}
153
Steven Moreland2372f9d2021-08-05 15:42:01 -0700154status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
Jiyong Park5970d0a2022-03-08 16:56:13 +0900155 // Why passing raw fd? When fd is passed as reference, Clang analyzer sees that the variable
156 // `fd` is a moved-from object. To work-around the issue, unwrap the raw fd from the outer `fd`,
157 // pass the raw fd by value to the lambda, and then finally wrap it in unique_fd inside the
158 // lambda.
159 return setupClient([&, raw = fd.release()](const std::vector<uint8_t>& sessionId,
160 bool incoming) -> status_t {
161 unique_fd fd(raw);
Steven Moreland4198a122021-08-03 17:37:58 -0700162 if (!fd.ok()) {
163 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700164 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700165 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700166 if (auto res = setNonBlocking(fd); !res.ok()) {
167 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
168 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
169 }
Steven Moreland4198a122021-08-03 17:37:58 -0700170 return initAndAddConnection(std::move(fd), sessionId, incoming);
171 });
172}
173
Steven Moreland2372f9d2021-08-05 15:42:01 -0700174status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700175 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700176 if (auto status = initShutdownTrigger(); status != OK) return status;
177
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000178 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
179
180 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700181 int savedErrno = errno;
182 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
183 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000184 }
185
Yifan Hongecf937d2021-08-11 17:29:28 -0700186 auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700187 if (server == nullptr) {
188 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700189 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700190 }
191 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000192}
193
194sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000195 ExclusiveConnection connection;
196 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
197 ConnectionUse::CLIENT, &connection);
198 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000199 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000200}
201
Steven Moreland1be91352021-05-11 22:12:15 +0000202status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000203 ExclusiveConnection connection;
204 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
205 ConnectionUse::CLIENT, &connection);
206 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000207 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000208}
209
Steven Morelandc9d7b532021-06-04 20:57:41 +0000210bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000211 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000212 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000213
214 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000215
Steven Morelandc9d7b532021-06-04 20:57:41 +0000216 if (wait) {
217 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700218 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700219
Steven Morelanda59937e2021-10-04 17:42:30 -0700220 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000221 }
222
223 _l.unlock();
Steven Moreland27a8bc72021-09-29 16:07:41 -0700224 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000225
Steven Moreland659416d2021-05-11 00:47:50 +0000226 return true;
227}
228
Steven Morelandf5174272021-05-25 00:39:28 +0000229status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000230 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000231 ExclusiveConnection connection;
232 status_t status =
233 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
234 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
235 : ConnectionUse::CLIENT,
236 &connection);
237 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000238 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000239 sp<RpcSession>::fromExisting(this), reply, flags);
240}
241
Steven Moreland4f622fe2021-09-13 17:38:09 -0700242status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000243 // target is 0 because this is used to free BpBinder objects
244 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700245}
246
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000247status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000248 ExclusiveConnection connection;
249 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
250 ConnectionUse::CLIENT_REFCOUNT, &connection);
251 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000252 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
253 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000254}
255
256status_t RpcSession::readId() {
257 {
258 std::lock_guard<std::mutex> _l(mMutex);
259 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
260 }
261
Steven Moreland195edb82021-06-08 02:44:39 +0000262 ExclusiveConnection connection;
263 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
264 ConnectionUse::CLIENT, &connection);
265 if (status != OK) return status;
266
Steven Moreland826367f2021-09-10 14:05:31 -0700267 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000268 if (status != OK) return status;
269
Steven Moreland826367f2021-09-10 14:05:31 -0700270 LOG_RPC_DETAIL("RpcSession %p has id %s", this,
271 base::HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000272 return OK;
273}
274
Steven Morelanddd67b942021-07-23 17:15:41 -0700275void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000276 const sp<RpcSession>& session) {
277 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000278}
279
Steven Moreland19fc9f72021-06-10 03:57:30 +0000280void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000281 mCv.notify_all();
282}
283
Steven Moreland791e4662021-09-13 15:22:58 -0700284void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock,
285 const sp<RpcSession>& session) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700286 while (session->mConnections.mIncoming.size() > 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000287 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700288 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
289 "still.",
Steven Morelanda59937e2021-10-04 17:42:30 -0700290 session->mConnections.mIncoming.size());
Steven Moreland659416d2021-05-11 00:47:50 +0000291 }
292 }
293}
294
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000295void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000296 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000297
Steven Morelanda63ff932021-05-12 00:03:15 +0000298 {
299 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700300 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000301 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000302}
Steven Morelanda63ff932021-05-12 00:03:15 +0000303
Yifan Hong702115c2021-06-24 15:39:18 -0700304RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
305 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000306 // must be registered to allow arbitrary client code executing commands to
307 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700308 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000309
Steven Morelanddd67b942021-07-23 17:15:41 -0700310 status_t status;
311
312 if (connection == nullptr) {
313 status = DEAD_OBJECT;
314 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700315 status =
316 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700317 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000318
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000319 return PreJoinSetupResult{
320 .connection = std::move(connection),
321 .status = status,
322 };
323}
324
Yifan Hong194acf22021-06-29 18:44:56 -0700325namespace {
Yifan Hongd258e682021-11-01 18:34:42 -0700326#ifdef __ANDROID_RECOVERY__
327class JavaThreadAttacher {};
328#else
Yifan Hong194acf22021-06-29 18:44:56 -0700329// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
330// Android Runtime doesn't exist, no-op.
331class JavaThreadAttacher {
332public:
333 JavaThreadAttacher() {
334 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
335 // libbinder.
336 auto vm = getJavaVM();
337 if (vm == nullptr) return;
338
339 char threadName[16];
340 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
341 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
342 memcpy(threadName, defaultThreadName,
343 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
344 }
345 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
346 JavaVMAttachArgs args;
347 args.version = JNI_VERSION_1_2;
348 args.name = threadName;
349 args.group = nullptr;
350 JNIEnv* env;
351
352 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
353 "Cannot attach thread %s to JVM", threadName);
354 mAttached = true;
355 }
356 ~JavaThreadAttacher() {
357 if (!mAttached) return;
358 auto vm = getJavaVM();
359 LOG_ALWAYS_FATAL_IF(vm == nullptr,
360 "Unable to detach thread. No JavaVM, but it was present before!");
361
362 LOG_RPC_DETAIL("Detaching current thread from JVM");
363 if (vm->DetachCurrentThread() != JNI_OK) {
364 mAttached = false;
365 } else {
366 ALOGW("Unable to detach current thread from JVM");
367 }
368 }
369
370private:
371 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
372 bool mAttached = false;
373
374 static JavaVM* getJavaVM() {
375 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
376 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
377 if (fn == nullptr) return nullptr;
378 return fn();
379 }
380};
Yifan Hongd258e682021-11-01 18:34:42 -0700381#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700382} // namespace
383
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000384void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
385 sp<RpcConnection>& connection = setupResult.connection;
386
387 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700388 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700389 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000390 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000391 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000392 RpcState::CommandType::ANY);
393 if (status != OK) {
394 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
395 statusToString(status).c_str());
396 break;
397 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000398 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000399 } else {
400 ALOGE("Connection failed to init, closing with status %s",
401 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000402 }
403
Steven Moreland659416d2021-05-11 00:47:50 +0000404 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000405 {
Steven Moreland659416d2021-05-11 00:47:50 +0000406 std::lock_guard<std::mutex> _l(session->mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700407 auto it = session->mConnections.mThreads.find(std::this_thread::get_id());
408 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000409 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700410 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000411
Steven Moreland659416d2021-05-11 00:47:50 +0000412 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000413 }
414
Steven Morelanddd67b942021-07-23 17:15:41 -0700415 // done after all cleanup, since session shutdown progresses via callbacks here
416 if (connection != nullptr) {
417 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
418 "bad state: connection object guaranteed to be in list");
419 }
420
Steven Moreland659416d2021-05-11 00:47:50 +0000421 session = nullptr;
422
423 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000424 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000425 }
426}
427
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000428sp<RpcServer> RpcSession::server() {
429 RpcServer* unsafeServer = mForServer.unsafe_get();
430 sp<RpcServer> server = mForServer.promote();
431
432 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
433 "wp<> is to avoid strong cycle only");
434 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000435}
436
Steven Moreland826367f2021-09-10 14:05:31 -0700437status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
438 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000439 {
440 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700441 LOG_ALWAYS_FATAL_IF(mConnections.mOutgoing.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000442 "Must only setup session once, but already has %zu clients",
Steven Morelanda59937e2021-10-04 17:42:30 -0700443 mConnections.mOutgoing.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000444 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700445
Yifan Hong832521e2021-08-05 14:55:40 -0700446 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000447
Steven Moreland27a8bc72021-09-29 16:07:41 -0700448 auto oldProtocolVersion = mProtocolVersion;
449 auto cleanup = base::ScopeGuard([&] {
450 // if any threads are started, shut them down
451 (void)shutdownAndWait(true);
452
453 mShutdownListener = nullptr;
454 mEventListener.clear();
455
456 mId.clear();
457
458 mShutdownTrigger = nullptr;
459 mRpcBinderState = std::make_unique<RpcState>();
460
461 // protocol version may have been downgraded - if we reuse this object
462 // to connect to another server, force that server to request a
463 // downgrade again
464 mProtocolVersion = oldProtocolVersion;
465
Steven Morelanda59937e2021-10-04 17:42:30 -0700466 mConnections = {};
Steven Moreland27a8bc72021-09-29 16:07:41 -0700467 });
468
Steven Moreland826367f2021-09-10 14:05:31 -0700469 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000470
Steven Morelandbf57bce2021-07-26 15:26:12 -0700471 {
472 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700473 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
474 ConnectionUse::CLIENT, &connection);
475 status != OK)
476 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700477
478 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700479 if (status_t status =
480 state()->readNewSessionResponse(connection.get(),
481 sp<RpcSession>::fromExisting(this), &version);
482 status != OK)
483 return status;
484 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700485 }
486
Steven Morelanda5036f02021-06-08 02:26:57 +0000487 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000488 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000489 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000490 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700491 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000492 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700493 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000494 }
495
496 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700497 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000498 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700499 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000500 }
501
Yifan Hong1f44f982021-10-08 17:16:47 -0700502 size_t outgoingThreads = std::min(numThreadsAvailable, mMaxOutgoingThreads);
503 ALOGI_IF(outgoingThreads != numThreadsAvailable,
504 "Server hints client to start %zu outgoing threads, but client will only start %zu "
505 "because it is preconfigured to start at most %zu outgoing threads.",
506 numThreadsAvailable, outgoingThreads, mMaxOutgoingThreads);
507
Steven Morelanda5036f02021-06-08 02:26:57 +0000508 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000509 // instead of all at once - the other side should be responsible for setting
510 // up additional connections. We need to create at least one (unless 0 are
511 // requested to be set) in order to allow the other side to reliably make
512 // any requests at all.
513
Steven Moreland4198a122021-08-03 17:37:58 -0700514 // we've already setup one client
Yifan Hong1f44f982021-10-08 17:16:47 -0700515 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing (server max: %zu) and %zu "
516 "incoming threads",
517 outgoingThreads, numThreadsAvailable, mMaxIncomingThreads);
518 for (size_t i = 0; i + 1 < outgoingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700519 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700520 }
521
Yifan Hong10423062021-10-08 16:26:32 -0700522 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700523 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000524 }
525
Steven Moreland27a8bc72021-09-29 16:07:41 -0700526 cleanup.Disable();
527
Steven Moreland2372f9d2021-08-05 15:42:01 -0700528 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000529}
530
Steven Moreland2372f9d2021-08-05 15:42:01 -0700531status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700532 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700533 return setupOneSocketConnection(addr, sessionId, incoming);
534 });
535}
536
Steven Moreland2372f9d2021-08-05 15:42:01 -0700537status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700538 const std::vector<uint8_t>& sessionId,
539 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000540 for (size_t tries = 0; tries < 5; tries++) {
541 if (tries > 0) usleep(10000);
542
Yifan Hongb675ffe2021-08-05 16:37:17 -0700543 unique_fd serverFd(TEMP_FAILURE_RETRY(
544 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000545 if (serverFd == -1) {
546 int savedErrno = errno;
547 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
548 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700549 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000550 }
551
552 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700553 int connErrno = errno;
554 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
555 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
556 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
557 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
558 if (pollStatus != OK) {
559 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
560 statusToString(pollStatus).c_str());
561 return pollStatus;
562 }
563 // Set connErrno to the errno that connect() would have set if the fd were blocking.
564 socklen_t connErrnoLen = sizeof(connErrno);
565 int ret =
566 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
567 if (ret == -1) {
568 int savedErrno = errno;
569 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
570 "(Original error from connect() is: %s)",
571 strerror(savedErrno), strerror(connErrno));
572 return -savedErrno;
573 }
574 // Retrieved the real connErrno as if connect() was called with a blocking socket
575 // fd. Continue checking connErrno.
576 }
577 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000578 ALOGW("Connection reset on %s", addr.toString().c_str());
579 continue;
580 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700581 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
582 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700583 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700584 strerror(connErrno));
585 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700586 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000587 }
Yifan Hong702115c2021-06-24 15:39:18 -0700588 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
589
Steven Moreland4198a122021-08-03 17:37:58 -0700590 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000591 }
592
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000593 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700594 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000595}
596
Steven Moreland826367f2021-09-10 14:05:31 -0700597status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700598 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700599 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700600 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700601 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700602 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700603 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700604 }
605
606 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
607
Steven Moreland826367f2021-09-10 14:05:31 -0700608 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
609 ALOGE("Session ID too big %zu", sessionId.size());
610 return BAD_VALUE;
611 }
612
Steven Moreland4198a122021-08-03 17:37:58 -0700613 RpcConnectionHeader header{
614 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
615 .options = 0,
Steven Moreland826367f2021-09-10 14:05:31 -0700616 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700617 };
Steven Moreland4198a122021-08-03 17:37:58 -0700618
Steven Moreland826367f2021-09-10 14:05:31 -0700619 if (incoming) {
620 header.options |= RPC_CONNECTION_OPTION_INCOMING;
621 }
Steven Moreland4198a122021-08-03 17:37:58 -0700622
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000623 iovec headerIov{&header, sizeof(header)};
Yifan Hong8c950422021-08-05 17:13:55 -0700624 auto sendHeaderStatus =
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000625 server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1, {});
Yifan Hong8c950422021-08-05 17:13:55 -0700626 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700627 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700628 statusToString(sendHeaderStatus).c_str());
629 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700630 }
631
Steven Moreland826367f2021-09-10 14:05:31 -0700632 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000633 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
634 sessionId.size()};
Steven Moreland826367f2021-09-10 14:05:31 -0700635 auto sendSessionIdStatus =
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000636 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1, {});
Steven Moreland826367f2021-09-10 14:05:31 -0700637 if (sendSessionIdStatus != OK) {
638 ALOGE("Could not write session ID ('%s') to socket: %s",
639 base::HexString(sessionId.data(), sessionId.size()).c_str(),
640 statusToString(sendSessionIdStatus).c_str());
641 return sendSessionIdStatus;
642 }
643 }
644
Steven Moreland4198a122021-08-03 17:37:58 -0700645 LOG_RPC_DETAIL("Socket at client: header sent");
646
647 if (incoming) {
648 return addIncomingConnection(std::move(server));
649 } else {
650 return addOutgoingConnection(std::move(server), true /*init*/);
651 }
652}
653
Steven Moreland2372f9d2021-08-05 15:42:01 -0700654status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000655 std::mutex mutex;
656 std::condition_variable joinCv;
657 std::unique_lock<std::mutex> lock(mutex);
658 std::thread thread;
659 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
660 bool ownershipTransferred = false;
661 thread = std::thread([&]() {
662 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700663 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000664 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
665 sp<RpcSession> session = thiz;
666 session->preJoinThreadOwnership(std::move(thread));
667
668 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700669 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000670
671 ownershipTransferred = true;
672 threadLock.unlock();
673 joinCv.notify_one();
674 // do not use & vars below
675
676 RpcSession::join(std::move(session), std::move(setupResult));
677 });
678 joinCv.wait(lock, [&] { return ownershipTransferred; });
679 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700680 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000681}
682
Yifan Hong832521e2021-08-05 14:55:40 -0700683status_t RpcSession::initShutdownTrigger() {
684 // first client connection added, but setForServer not called, so
685 // initializaing for a client.
686 if (mShutdownTrigger == nullptr) {
687 mShutdownTrigger = FdTrigger::make();
688 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
689 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
690 }
691 return OK;
692}
693
Steven Moreland2372f9d2021-08-05 15:42:01 -0700694status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000695 sp<RpcConnection> connection = sp<RpcConnection>::make();
696 {
697 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700698 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000699 connection->exclusiveTid = gettid();
Steven Morelanda59937e2021-10-04 17:42:30 -0700700 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000701 }
702
Steven Morelandb86e26b2021-06-12 00:35:58 +0000703 status_t status = OK;
704 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700705 status =
706 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000707 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000708
709 {
710 std::lock_guard<std::mutex> _l(mMutex);
711 connection->exclusiveTid = std::nullopt;
712 }
713
Steven Moreland2372f9d2021-08-05 15:42:01 -0700714 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000715}
716
Steven Morelanda8b44292021-06-08 01:27:53 +0000717bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700718 const std::vector<uint8_t>& sessionId,
719 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000720 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
721 LOG_ALWAYS_FATAL_IF(server == nullptr);
722 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
723 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000724 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000725
726 mShutdownTrigger = FdTrigger::make();
727 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000728
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000729 mId = sessionId;
730 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000731 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700732 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000733 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000734}
735
Yifan Hong702115c2021-06-24 15:39:18 -0700736sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
737 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000738 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700739
Yifan Hong10423062021-10-08 16:26:32 -0700740 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700741 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700742 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700743 return nullptr;
744 }
745
Steven Morelanddd67b942021-07-23 17:15:41 -0700746 // Don't accept any more connections, some have shutdown. Usually this
747 // happens when new connections are still being established as part of a
748 // very short-lived session which shuts down after it already started
749 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700750 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700751 return nullptr;
752 }
753
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000754 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700755 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000756 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700757
Steven Morelanda59937e2021-10-04 17:42:30 -0700758 mConnections.mIncoming.push_back(session);
759 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000760
761 return session;
762}
763
Steven Moreland19fc9f72021-06-10 03:57:30 +0000764bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700765 std::unique_lock<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700766 if (auto it =
767 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
768 it != mConnections.mIncoming.end()) {
769 mConnections.mIncoming.erase(it);
770 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000771 sp<EventListener> listener = mEventListener.promote();
772 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700773 _l.unlock();
774 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000775 }
Steven Morelandee78e762021-05-05 21:12:51 +0000776 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000777 return true;
778 }
779 return false;
780}
781
Yifan Hong9734cfc2021-09-13 16:14:09 -0700782std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700783 return mCtx->getCertificate(format);
784}
785
Steven Moreland195edb82021-06-08 02:44:39 +0000786status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
787 ExclusiveConnection* connection) {
788 connection->mSession = session;
789 connection->mConnection = nullptr;
790 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000791
Steven Moreland195edb82021-06-08 02:44:39 +0000792 pid_t tid = gettid();
793 std::unique_lock<std::mutex> _l(session->mMutex);
794
Steven Morelanda59937e2021-10-04 17:42:30 -0700795 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000796 while (true) {
797 sp<RpcConnection> exclusive;
798 sp<RpcConnection> available;
799
800 // CHECK FOR DEDICATED CLIENT SOCKET
801 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000802 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700803 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
804 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000805
806 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700807 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000808 //
809 // Imagine we have more than one thread in play, and a single thread
810 // sends a synchronous, then an asynchronous command. Imagine the
811 // asynchronous command is sent on the first client connection. Then, if
812 // we naively send a synchronous command to that same connection, the
813 // thread on the far side might be busy processing the asynchronous
814 // command. So, we move to considering the second available thread
815 // for subsequent calls.
816 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700817 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
818 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000819 }
820
Steven Morelandc7d40132021-06-10 03:42:11 +0000821 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000822 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000823 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000824 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000825 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700826 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000827
828 // asynchronous calls cannot be nested, we currently allow ref count
829 // calls to be nested (so that you can use this without having extra
830 // threads). Note 'drainCommands' is used so that these ref counts can't
831 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000832 if (exclusiveIncoming != nullptr) {
833 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000834 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000835 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000836 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
837 // prefer available socket, but if we don't have one, don't
838 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000839 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000840 }
841 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000842 }
843
Steven Moreland85e067b2021-05-26 17:43:53 +0000844 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000845 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000846 connection->mConnection = exclusive;
847 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000848 break;
849 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000850 connection->mConnection = available;
851 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000852 break;
853 }
854
Steven Morelanda59937e2021-10-04 17:42:30 -0700855 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000856 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
857 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
858 "reason: %d. Incoming connections: %zu. %s.",
859 static_cast<int>(use), session->mConnections.mIncoming.size(),
860 (session->server()
861 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
862 "for the corresponding client"
863 : "This is a client session, so see RpcSession::setMaxOutgoingThreads "
864 "for this client or RpcServer::setMaxThreads for the corresponding "
865 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000866 return WOULD_BLOCK;
867 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000868
Steven Moreland85e067b2021-05-26 17:43:53 +0000869 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700870 session->mConnections.mOutgoing.size(),
871 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000872 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000873 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700874 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000875
876 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000877}
878
879void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
880 sp<RpcConnection>* available,
881 std::vector<sp<RpcConnection>>& sockets,
882 size_t socketsIndexHint) {
883 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
884 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
885
886 if (*exclusive != nullptr) return; // consistent with break below
887
888 for (size_t i = 0; i < sockets.size(); i++) {
889 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
890
Steven Moreland85e067b2021-05-26 17:43:53 +0000891 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000892 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
893 *available = socket;
894 continue;
895 }
896
Steven Moreland85e067b2021-05-26 17:43:53 +0000897 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000898 // (nested transactions)
899 if (exclusive && socket->exclusiveTid == tid) {
900 *exclusive = socket;
901 break; // consistent with return above
902 }
903 }
904}
905
906RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000907 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000908 // is using this fd, and it retains the right to it. So, we don't give up
909 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000910 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000911 std::unique_lock<std::mutex> _l(mSession->mMutex);
912 mConnection->exclusiveTid = std::nullopt;
Steven Morelanda59937e2021-10-04 17:42:30 -0700913 if (mSession->mConnections.mWaitingThreads > 0) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000914 _l.unlock();
915 mSession->mAvailableConnectionCv.notify_one();
916 }
917 }
918}
919
920} // namespace android