blob: 9b7b5e1ceb29771a58bc804cf7ca70f4c69b5d8f [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
Steven Morelandbf57bce2021-07-26 15:26:12 -070096bool RpcSession::setProtocolVersion(uint32_t version) {
97 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
98 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
99 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
100 "is %u).",
101 version, RPC_WIRE_PROTOCOL_VERSION);
102 return false;
103 }
104
105 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -0700106 if (mProtocolVersion && version > *mProtocolVersion) {
107 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
108 *mProtocolVersion, version);
109 return false;
110 }
111
Steven Morelandbf57bce2021-07-26 15:26:12 -0700112 mProtocolVersion = version;
113 return true;
114}
115
116std::optional<uint32_t> RpcSession::getProtocolVersion() {
117 std::lock_guard<std::mutex> _l(mMutex);
118 return mProtocolVersion;
119}
120
Steven Moreland2372f9d2021-08-05 15:42:01 -0700121status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000122 return setupSocketClient(UnixSocketAddress(path));
123}
124
Steven Moreland2372f9d2021-08-05 15:42:01 -0700125status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000126 return setupSocketClient(VsockSocketAddress(cid, port));
127}
128
Steven Moreland2372f9d2021-08-05 15:42:01 -0700129status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000130 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700131 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000132 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
133 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700134 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000135 }
136 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 -0700137 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000138}
139
Steven Moreland2372f9d2021-08-05 15:42:01 -0700140status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
Steven Moreland826367f2021-09-10 14:05:31 -0700141 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700142 // std::move'd from fd becomes -1 (!ok())
143 if (!fd.ok()) {
144 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700145 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700146 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700147 if (auto res = setNonBlocking(fd); !res.ok()) {
148 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
149 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
150 }
Steven Moreland4198a122021-08-03 17:37:58 -0700151 return initAndAddConnection(std::move(fd), sessionId, incoming);
152 });
153}
154
Steven Moreland2372f9d2021-08-05 15:42:01 -0700155status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700156 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700157 if (auto status = initShutdownTrigger(); status != OK) return status;
158
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000159 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
160
161 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700162 int savedErrno = errno;
163 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
164 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000165 }
166
Yifan Hongecf937d2021-08-11 17:29:28 -0700167 auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700168 if (server == nullptr) {
169 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700170 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700171 }
172 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000173}
174
175sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000176 ExclusiveConnection connection;
177 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
178 ConnectionUse::CLIENT, &connection);
179 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000180 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000181}
182
Steven Moreland1be91352021-05-11 22:12:15 +0000183status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000184 ExclusiveConnection connection;
185 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
186 ConnectionUse::CLIENT, &connection);
187 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000188 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000189}
190
Steven Morelandc9d7b532021-06-04 20:57:41 +0000191bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000192 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000193 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000194
195 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000196
Steven Morelandc9d7b532021-06-04 20:57:41 +0000197 if (wait) {
198 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700199 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700200
Steven Morelanda59937e2021-10-04 17:42:30 -0700201 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000202 }
203
204 _l.unlock();
Steven Moreland27a8bc72021-09-29 16:07:41 -0700205 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000206
Steven Moreland659416d2021-05-11 00:47:50 +0000207 return true;
208}
209
Steven Morelandf5174272021-05-25 00:39:28 +0000210status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000211 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000212 ExclusiveConnection connection;
213 status_t status =
214 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
215 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
216 : ConnectionUse::CLIENT,
217 &connection);
218 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000219 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000220 sp<RpcSession>::fromExisting(this), reply, flags);
221}
222
Steven Moreland4f622fe2021-09-13 17:38:09 -0700223status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000224 // target is 0 because this is used to free BpBinder objects
225 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700226}
227
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000228status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000229 ExclusiveConnection connection;
230 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
231 ConnectionUse::CLIENT_REFCOUNT, &connection);
232 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000233 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
234 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000235}
236
237status_t RpcSession::readId() {
238 {
239 std::lock_guard<std::mutex> _l(mMutex);
240 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
241 }
242
Steven Moreland195edb82021-06-08 02:44:39 +0000243 ExclusiveConnection connection;
244 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
245 ConnectionUse::CLIENT, &connection);
246 if (status != OK) return status;
247
Steven Moreland826367f2021-09-10 14:05:31 -0700248 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000249 if (status != OK) return status;
250
Steven Moreland826367f2021-09-10 14:05:31 -0700251 LOG_RPC_DETAIL("RpcSession %p has id %s", this,
252 base::HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000253 return OK;
254}
255
Steven Morelanddd67b942021-07-23 17:15:41 -0700256void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000257 const sp<RpcSession>& session) {
258 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000259}
260
Steven Moreland19fc9f72021-06-10 03:57:30 +0000261void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000262 mCv.notify_all();
263}
264
Steven Moreland791e4662021-09-13 15:22:58 -0700265void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock,
266 const sp<RpcSession>& session) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700267 while (session->mConnections.mIncoming.size() > 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000268 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700269 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
270 "still.",
Steven Morelanda59937e2021-10-04 17:42:30 -0700271 session->mConnections.mIncoming.size());
Steven Moreland659416d2021-05-11 00:47:50 +0000272 }
273 }
274}
275
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000276void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000277 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000278
Steven Morelanda63ff932021-05-12 00:03:15 +0000279 {
280 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700281 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000282 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000283}
Steven Morelanda63ff932021-05-12 00:03:15 +0000284
Yifan Hong702115c2021-06-24 15:39:18 -0700285RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
286 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000287 // must be registered to allow arbitrary client code executing commands to
288 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700289 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000290
Steven Morelanddd67b942021-07-23 17:15:41 -0700291 status_t status;
292
293 if (connection == nullptr) {
294 status = DEAD_OBJECT;
295 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700296 status =
297 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700298 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000299
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000300 return PreJoinSetupResult{
301 .connection = std::move(connection),
302 .status = status,
303 };
304}
305
Yifan Hong194acf22021-06-29 18:44:56 -0700306namespace {
Yifan Hongd258e682021-11-01 18:34:42 -0700307#ifdef __ANDROID_RECOVERY__
308class JavaThreadAttacher {};
309#else
Yifan Hong194acf22021-06-29 18:44:56 -0700310// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
311// Android Runtime doesn't exist, no-op.
312class JavaThreadAttacher {
313public:
314 JavaThreadAttacher() {
315 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
316 // libbinder.
317 auto vm = getJavaVM();
318 if (vm == nullptr) return;
319
320 char threadName[16];
321 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
322 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
323 memcpy(threadName, defaultThreadName,
324 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
325 }
326 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
327 JavaVMAttachArgs args;
328 args.version = JNI_VERSION_1_2;
329 args.name = threadName;
330 args.group = nullptr;
331 JNIEnv* env;
332
333 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
334 "Cannot attach thread %s to JVM", threadName);
335 mAttached = true;
336 }
337 ~JavaThreadAttacher() {
338 if (!mAttached) return;
339 auto vm = getJavaVM();
340 LOG_ALWAYS_FATAL_IF(vm == nullptr,
341 "Unable to detach thread. No JavaVM, but it was present before!");
342
343 LOG_RPC_DETAIL("Detaching current thread from JVM");
344 if (vm->DetachCurrentThread() != JNI_OK) {
345 mAttached = false;
346 } else {
347 ALOGW("Unable to detach current thread from JVM");
348 }
349 }
350
351private:
352 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
353 bool mAttached = false;
354
355 static JavaVM* getJavaVM() {
356 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
357 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
358 if (fn == nullptr) return nullptr;
359 return fn();
360 }
361};
Yifan Hongd258e682021-11-01 18:34:42 -0700362#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700363} // namespace
364
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000365void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
366 sp<RpcConnection>& connection = setupResult.connection;
367
368 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700369 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700370 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000371 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000372 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000373 RpcState::CommandType::ANY);
374 if (status != OK) {
375 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
376 statusToString(status).c_str());
377 break;
378 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000379 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000380 } else {
381 ALOGE("Connection failed to init, closing with status %s",
382 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000383 }
384
Steven Moreland659416d2021-05-11 00:47:50 +0000385 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000386 {
Steven Moreland659416d2021-05-11 00:47:50 +0000387 std::lock_guard<std::mutex> _l(session->mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700388 auto it = session->mConnections.mThreads.find(std::this_thread::get_id());
389 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000390 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700391 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000392
Steven Moreland659416d2021-05-11 00:47:50 +0000393 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000394 }
395
Steven Morelanddd67b942021-07-23 17:15:41 -0700396 // done after all cleanup, since session shutdown progresses via callbacks here
397 if (connection != nullptr) {
398 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
399 "bad state: connection object guaranteed to be in list");
400 }
401
Steven Moreland659416d2021-05-11 00:47:50 +0000402 session = nullptr;
403
404 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000405 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000406 }
407}
408
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000409sp<RpcServer> RpcSession::server() {
410 RpcServer* unsafeServer = mForServer.unsafe_get();
411 sp<RpcServer> server = mForServer.promote();
412
413 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
414 "wp<> is to avoid strong cycle only");
415 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000416}
417
Steven Moreland826367f2021-09-10 14:05:31 -0700418status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
419 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420 {
421 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700422 LOG_ALWAYS_FATAL_IF(mConnections.mOutgoing.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000423 "Must only setup session once, but already has %zu clients",
Steven Morelanda59937e2021-10-04 17:42:30 -0700424 mConnections.mOutgoing.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000425 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700426
Yifan Hong832521e2021-08-05 14:55:40 -0700427 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000428
Steven Moreland27a8bc72021-09-29 16:07:41 -0700429 auto oldProtocolVersion = mProtocolVersion;
430 auto cleanup = base::ScopeGuard([&] {
431 // if any threads are started, shut them down
432 (void)shutdownAndWait(true);
433
434 mShutdownListener = nullptr;
435 mEventListener.clear();
436
437 mId.clear();
438
439 mShutdownTrigger = nullptr;
440 mRpcBinderState = std::make_unique<RpcState>();
441
442 // protocol version may have been downgraded - if we reuse this object
443 // to connect to another server, force that server to request a
444 // downgrade again
445 mProtocolVersion = oldProtocolVersion;
446
Steven Morelanda59937e2021-10-04 17:42:30 -0700447 mConnections = {};
Steven Moreland27a8bc72021-09-29 16:07:41 -0700448 });
449
Steven Moreland826367f2021-09-10 14:05:31 -0700450 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000451
Steven Morelandbf57bce2021-07-26 15:26:12 -0700452 {
453 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700454 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
455 ConnectionUse::CLIENT, &connection);
456 status != OK)
457 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700458
459 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700460 if (status_t status =
461 state()->readNewSessionResponse(connection.get(),
462 sp<RpcSession>::fromExisting(this), &version);
463 status != OK)
464 return status;
465 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700466 }
467
Steven Morelanda5036f02021-06-08 02:26:57 +0000468 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000469 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000470 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000471 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700472 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000473 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700474 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000475 }
476
477 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700478 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000479 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700480 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000481 }
482
Steven Morelanda5036f02021-06-08 02:26:57 +0000483 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000484 // instead of all at once - the other side should be responsible for setting
485 // up additional connections. We need to create at least one (unless 0 are
486 // requested to be set) in order to allow the other side to reliably make
487 // any requests at all.
488
Steven Moreland4198a122021-08-03 17:37:58 -0700489 // we've already setup one client
490 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700491 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700492 }
493
Yifan Hong10423062021-10-08 16:26:32 -0700494 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700495 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000496 }
497
Steven Moreland27a8bc72021-09-29 16:07:41 -0700498 cleanup.Disable();
499
Steven Moreland2372f9d2021-08-05 15:42:01 -0700500 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000501}
502
Steven Moreland2372f9d2021-08-05 15:42:01 -0700503status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700504 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700505 return setupOneSocketConnection(addr, sessionId, incoming);
506 });
507}
508
Steven Moreland2372f9d2021-08-05 15:42:01 -0700509status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700510 const std::vector<uint8_t>& sessionId,
511 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000512 for (size_t tries = 0; tries < 5; tries++) {
513 if (tries > 0) usleep(10000);
514
Yifan Hongb675ffe2021-08-05 16:37:17 -0700515 unique_fd serverFd(TEMP_FAILURE_RETRY(
516 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000517 if (serverFd == -1) {
518 int savedErrno = errno;
519 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
520 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700521 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000522 }
523
524 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700525 int connErrno = errno;
526 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
527 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
528 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
529 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
530 if (pollStatus != OK) {
531 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
532 statusToString(pollStatus).c_str());
533 return pollStatus;
534 }
535 // Set connErrno to the errno that connect() would have set if the fd were blocking.
536 socklen_t connErrnoLen = sizeof(connErrno);
537 int ret =
538 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
539 if (ret == -1) {
540 int savedErrno = errno;
541 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
542 "(Original error from connect() is: %s)",
543 strerror(savedErrno), strerror(connErrno));
544 return -savedErrno;
545 }
546 // Retrieved the real connErrno as if connect() was called with a blocking socket
547 // fd. Continue checking connErrno.
548 }
549 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000550 ALOGW("Connection reset on %s", addr.toString().c_str());
551 continue;
552 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700553 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
554 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700555 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700556 strerror(connErrno));
557 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700558 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000559 }
Yifan Hong702115c2021-06-24 15:39:18 -0700560 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
561
Steven Moreland4198a122021-08-03 17:37:58 -0700562 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000563 }
564
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000565 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700566 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000567}
568
Steven Moreland826367f2021-09-10 14:05:31 -0700569status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700570 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700571 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700572 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700573 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700574 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700575 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700576 }
577
578 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
579
Steven Moreland826367f2021-09-10 14:05:31 -0700580 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
581 ALOGE("Session ID too big %zu", sessionId.size());
582 return BAD_VALUE;
583 }
584
Steven Moreland4198a122021-08-03 17:37:58 -0700585 RpcConnectionHeader header{
586 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
587 .options = 0,
Steven Moreland826367f2021-09-10 14:05:31 -0700588 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700589 };
Steven Moreland4198a122021-08-03 17:37:58 -0700590
Steven Moreland826367f2021-09-10 14:05:31 -0700591 if (incoming) {
592 header.options |= RPC_CONNECTION_OPTION_INCOMING;
593 }
Steven Moreland4198a122021-08-03 17:37:58 -0700594
Yifan Hong8c950422021-08-05 17:13:55 -0700595 auto sendHeaderStatus =
Steven Moreland43921d52021-09-27 17:15:56 -0700596 server->interruptableWriteFully(mShutdownTrigger.get(), &header, sizeof(header), {});
Yifan Hong8c950422021-08-05 17:13:55 -0700597 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700598 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700599 statusToString(sendHeaderStatus).c_str());
600 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700601 }
602
Steven Moreland826367f2021-09-10 14:05:31 -0700603 if (sessionId.size() > 0) {
604 auto sendSessionIdStatus =
605 server->interruptableWriteFully(mShutdownTrigger.get(), sessionId.data(),
Steven Moreland43921d52021-09-27 17:15:56 -0700606 sessionId.size(), {});
Steven Moreland826367f2021-09-10 14:05:31 -0700607 if (sendSessionIdStatus != OK) {
608 ALOGE("Could not write session ID ('%s') to socket: %s",
609 base::HexString(sessionId.data(), sessionId.size()).c_str(),
610 statusToString(sendSessionIdStatus).c_str());
611 return sendSessionIdStatus;
612 }
613 }
614
Steven Moreland4198a122021-08-03 17:37:58 -0700615 LOG_RPC_DETAIL("Socket at client: header sent");
616
617 if (incoming) {
618 return addIncomingConnection(std::move(server));
619 } else {
620 return addOutgoingConnection(std::move(server), true /*init*/);
621 }
622}
623
Steven Moreland2372f9d2021-08-05 15:42:01 -0700624status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000625 std::mutex mutex;
626 std::condition_variable joinCv;
627 std::unique_lock<std::mutex> lock(mutex);
628 std::thread thread;
629 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
630 bool ownershipTransferred = false;
631 thread = std::thread([&]() {
632 std::unique_lock<std::mutex> threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700633 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000634 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
635 sp<RpcSession> session = thiz;
636 session->preJoinThreadOwnership(std::move(thread));
637
638 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700639 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000640
641 ownershipTransferred = true;
642 threadLock.unlock();
643 joinCv.notify_one();
644 // do not use & vars below
645
646 RpcSession::join(std::move(session), std::move(setupResult));
647 });
648 joinCv.wait(lock, [&] { return ownershipTransferred; });
649 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700650 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000651}
652
Yifan Hong832521e2021-08-05 14:55:40 -0700653status_t RpcSession::initShutdownTrigger() {
654 // first client connection added, but setForServer not called, so
655 // initializaing for a client.
656 if (mShutdownTrigger == nullptr) {
657 mShutdownTrigger = FdTrigger::make();
658 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
659 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
660 }
661 return OK;
662}
663
Steven Moreland2372f9d2021-08-05 15:42:01 -0700664status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000665 sp<RpcConnection> connection = sp<RpcConnection>::make();
666 {
667 std::lock_guard<std::mutex> _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700668 connection->rpcTransport = std::move(rpcTransport);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000669 connection->exclusiveTid = gettid();
Steven Morelanda59937e2021-10-04 17:42:30 -0700670 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000671 }
672
Steven Morelandb86e26b2021-06-12 00:35:58 +0000673 status_t status = OK;
674 if (init) {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700675 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000676 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000677
678 {
679 std::lock_guard<std::mutex> _l(mMutex);
680 connection->exclusiveTid = std::nullopt;
681 }
682
Steven Moreland2372f9d2021-08-05 15:42:01 -0700683 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000684}
685
Steven Morelanda8b44292021-06-08 01:27:53 +0000686bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland826367f2021-09-10 14:05:31 -0700687 const std::vector<uint8_t>& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000688 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
689 LOG_ALWAYS_FATAL_IF(server == nullptr);
690 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
691 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000692 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000693
694 mShutdownTrigger = FdTrigger::make();
695 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000696
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000697 mId = sessionId;
698 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000699 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000700 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000701}
702
Yifan Hong702115c2021-06-24 15:39:18 -0700703sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
704 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000705 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700706
Yifan Hong10423062021-10-08 16:26:32 -0700707 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700708 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700709 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700710 return nullptr;
711 }
712
Steven Morelanddd67b942021-07-23 17:15:41 -0700713 // Don't accept any more connections, some have shutdown. Usually this
714 // happens when new connections are still being established as part of a
715 // very short-lived session which shuts down after it already started
716 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700717 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700718 return nullptr;
719 }
720
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000721 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700722 session->rpcTransport = std::move(rpcTransport);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000723 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700724
Steven Morelanda59937e2021-10-04 17:42:30 -0700725 mConnections.mIncoming.push_back(session);
726 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000727
728 return session;
729}
730
Steven Moreland19fc9f72021-06-10 03:57:30 +0000731bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700732 std::unique_lock<std::mutex> _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700733 if (auto it =
734 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
735 it != mConnections.mIncoming.end()) {
736 mConnections.mIncoming.erase(it);
737 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000738 sp<EventListener> listener = mEventListener.promote();
739 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700740 _l.unlock();
741 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000742 }
Steven Morelandee78e762021-05-05 21:12:51 +0000743 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000744 return true;
745 }
746 return false;
747}
748
Yifan Hong9734cfc2021-09-13 16:14:09 -0700749std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700750 return mCtx->getCertificate(format);
751}
752
Steven Moreland195edb82021-06-08 02:44:39 +0000753status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
754 ExclusiveConnection* connection) {
755 connection->mSession = session;
756 connection->mConnection = nullptr;
757 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000758
Steven Moreland195edb82021-06-08 02:44:39 +0000759 pid_t tid = gettid();
760 std::unique_lock<std::mutex> _l(session->mMutex);
761
Steven Morelanda59937e2021-10-04 17:42:30 -0700762 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000763 while (true) {
764 sp<RpcConnection> exclusive;
765 sp<RpcConnection> available;
766
767 // CHECK FOR DEDICATED CLIENT SOCKET
768 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000769 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700770 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
771 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000772
773 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700774 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000775 //
776 // Imagine we have more than one thread in play, and a single thread
777 // sends a synchronous, then an asynchronous command. Imagine the
778 // asynchronous command is sent on the first client connection. Then, if
779 // we naively send a synchronous command to that same connection, the
780 // thread on the far side might be busy processing the asynchronous
781 // command. So, we move to considering the second available thread
782 // for subsequent calls.
783 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700784 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
785 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000786 }
787
Steven Morelandc7d40132021-06-10 03:42:11 +0000788 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000789 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000790 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000791 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000792 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700793 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000794
795 // asynchronous calls cannot be nested, we currently allow ref count
796 // calls to be nested (so that you can use this without having extra
797 // threads). Note 'drainCommands' is used so that these ref counts can't
798 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000799 if (exclusiveIncoming != nullptr) {
800 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000801 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000802 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000803 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
804 // prefer available socket, but if we don't have one, don't
805 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000806 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000807 }
808 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000809 }
810
Steven Moreland85e067b2021-05-26 17:43:53 +0000811 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000812 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000813 connection->mConnection = exclusive;
814 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000815 break;
816 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000817 connection->mConnection = available;
818 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000819 break;
820 }
821
Steven Morelanda59937e2021-10-04 17:42:30 -0700822 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000823 ALOGE("Session has no client connections. This is required for an RPC server to make "
824 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
825 "connections: %zu",
Steven Morelanda59937e2021-10-04 17:42:30 -0700826 static_cast<int>(use), session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000827 return WOULD_BLOCK;
828 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000829
Steven Moreland85e067b2021-05-26 17:43:53 +0000830 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700831 session->mConnections.mOutgoing.size(),
832 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000833 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000834 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700835 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000836
837 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000838}
839
840void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
841 sp<RpcConnection>* available,
842 std::vector<sp<RpcConnection>>& sockets,
843 size_t socketsIndexHint) {
844 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
845 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
846
847 if (*exclusive != nullptr) return; // consistent with break below
848
849 for (size_t i = 0; i < sockets.size(); i++) {
850 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
851
Steven Moreland85e067b2021-05-26 17:43:53 +0000852 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000853 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
854 *available = socket;
855 continue;
856 }
857
Steven Moreland85e067b2021-05-26 17:43:53 +0000858 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000859 // (nested transactions)
860 if (exclusive && socket->exclusiveTid == tid) {
861 *exclusive = socket;
862 break; // consistent with return above
863 }
864 }
865}
866
867RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000868 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000869 // is using this fd, and it retains the right to it. So, we don't give up
870 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000871 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000872 std::unique_lock<std::mutex> _l(mSession->mMutex);
873 mConnection->exclusiveTid = std::nullopt;
Steven Morelanda59937e2021-10-04 17:42:30 -0700874 if (mSession->mConnections.mWaitingThreads > 0) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000875 _l.unlock();
876 mSession->mAvailableConnectionCv.notify_one();
877 }
878 }
879}
880
881} // namespace android