blob: e6dbd79ffb81507585aa59f8453a7cebb143414e [file] [log] [blame]
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "RpcSession"
18
19#include <binder/RpcSession.h>
20
Yifan Hong194acf22021-06-29 18:44:56 -070021#include <dlfcn.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000022#include <inttypes.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000023#include <poll.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000024#include <unistd.h>
25
26#include <string_view>
27
Steven Moreland826367f2021-09-10 14:05:31 -070028#include <android-base/hex.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000029#include <android-base/macros.h>
Steven Moreland27a8bc72021-09-29 16:07:41 -070030#include <android-base/scopeguard.h>
Steven Moreland4f622fe2021-09-13 17:38:09 -070031#include <binder/BpBinder.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000032#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000033#include <binder/RpcServer.h>
Yifan Hong702115c2021-06-24 15:39:18 -070034#include <binder/RpcTransportRaw.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000035#include <binder/Stability.h>
Andrei Homescu1d935e82022-04-25 04:58:23 +000036#include <utils/Compat.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000037#include <utils/String8.h>
38
Yifan Hong8c950422021-08-05 17:13:55 -070039#include "FdTrigger.h"
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000040#include "OS.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000041#include "RpcSocketAddress.h"
42#include "RpcState.h"
43#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070044#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000045
Andrei Homescu47f8c4f2022-04-30 01:38:24 +000046#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -070047#include <android_runtime/vm.h>
48#include <jni.h>
49#endif
50
Steven Morelandbdb53ab2021-05-05 17:57:41 +000051namespace android {
52
53using base::unique_fd;
54
Yifan Hongecf937d2021-08-11 17:29:28 -070055RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000056 LOG_RPC_DETAIL("RpcSession created %p", this);
57
Steven Moreland27a8bc72021-09-29 16:07:41 -070058 mRpcBinderState = std::make_unique<RpcState>();
Steven Morelandbdb53ab2021-05-05 17:57:41 +000059}
60RpcSession::~RpcSession() {
61 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
62
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000063 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070064 LOG_ALWAYS_FATAL_IF(mConnections.mIncoming.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000065 "Should not be able to destroy a session with servers in use.");
66}
67
Yifan Hongecf937d2021-08-11 17:29:28 -070068sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070069 // Default is without TLS.
Yifan Hongfdd9f692021-09-09 15:12:52 -070070 return make(RpcTransportCtxFactoryRaw::make());
Yifan Hongecf937d2021-08-11 17:29:28 -070071}
72
Yifan Hongfdd9f692021-09-09 15:12:52 -070073sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070074 auto ctx = rpcTransportCtxFactory->newClientCtx();
75 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070076 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000077}
78
Yifan Hong10423062021-10-08 16:26:32 -070079void RpcSession::setMaxIncomingThreads(size_t threads) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000080 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070081 LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
Yifan Hong10423062021-10-08 16:26:32 -070082 "Must set max incoming threads before setting up connections, but has %zu "
83 "client(s) and %zu server(s)",
Steven Morelanda59937e2021-10-04 17:42:30 -070084 mConnections.mOutgoing.size(), mConnections.mIncoming.size());
Yifan Hong10423062021-10-08 16:26:32 -070085 mMaxIncomingThreads = threads;
Steven Moreland103424e2021-06-02 18:16:19 +000086}
87
Yifan Hong10423062021-10-08 16:26:32 -070088size_t RpcSession::getMaxIncomingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000089 RpcMutexLockGuard _l(mMutex);
Yifan Hong10423062021-10-08 16:26:32 -070090 return mMaxIncomingThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000091}
92
Yifan Hong1f44f982021-10-08 17:16:47 -070093void RpcSession::setMaxOutgoingThreads(size_t threads) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000094 RpcMutexLockGuard _l(mMutex);
Yifan Hong1f44f982021-10-08 17:16:47 -070095 LOG_ALWAYS_FATAL_IF(!mConnections.mOutgoing.empty() || !mConnections.mIncoming.empty(),
96 "Must set max outgoing threads before setting up connections, but has %zu "
97 "client(s) and %zu server(s)",
98 mConnections.mOutgoing.size(), mConnections.mIncoming.size());
99 mMaxOutgoingThreads = threads;
100}
101
102size_t RpcSession::getMaxOutgoingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000103 RpcMutexLockGuard _l(mMutex);
Yifan Hong1f44f982021-10-08 17:16:47 -0700104 return mMaxOutgoingThreads;
105}
106
Steven Morelandbf57bce2021-07-26 15:26:12 -0700107bool RpcSession::setProtocolVersion(uint32_t version) {
108 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
109 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
110 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
111 "is %u).",
112 version, RPC_WIRE_PROTOCOL_VERSION);
113 return false;
114 }
115
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000116 RpcMutexLockGuard _l(mMutex);
Steven Moreland40b736e2021-07-30 14:37:10 -0700117 if (mProtocolVersion && version > *mProtocolVersion) {
118 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
119 *mProtocolVersion, version);
120 return false;
121 }
122
Steven Morelandbf57bce2021-07-26 15:26:12 -0700123 mProtocolVersion = version;
124 return true;
125}
126
127std::optional<uint32_t> RpcSession::getProtocolVersion() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000128 RpcMutexLockGuard _l(mMutex);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700129 return mProtocolVersion;
130}
131
Frederick Mayle69a0c992022-05-26 20:38:39 +0000132void RpcSession::setFileDescriptorTransportMode(FileDescriptorTransportMode mode) {
133 mFileDescriptorTransportMode = mode;
134}
135
136RpcSession::FileDescriptorTransportMode RpcSession::getFileDescriptorTransportMode() {
137 return mFileDescriptorTransportMode;
138}
139
Steven Moreland2372f9d2021-08-05 15:42:01 -0700140status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000141 return setupSocketClient(UnixSocketAddress(path));
142}
143
Steven Moreland2372f9d2021-08-05 15:42:01 -0700144status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000145 return setupSocketClient(VsockSocketAddress(cid, port));
146}
147
Steven Moreland2372f9d2021-08-05 15:42:01 -0700148status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000149 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700150 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000151 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
152 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700153 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000154 }
155 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 -0700156 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000157}
158
Steven Moreland2372f9d2021-08-05 15:42:01 -0700159status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
Frederick Mayle297c2772022-05-05 01:21:04 +0000160 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700161 if (!fd.ok()) {
162 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700163 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700164 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700165 if (auto res = setNonBlocking(fd); !res.ok()) {
166 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
167 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
168 }
Frederick Mayle297c2772022-05-05 01:21:04 +0000169 status_t status = initAndAddConnection(std::move(fd), sessionId, incoming);
170 fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
171 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700172 });
173}
174
Steven Moreland2372f9d2021-08-05 15:42:01 -0700175status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700176 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700177 if (auto status = initShutdownTrigger(); status != OK) return status;
178
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000179 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
180
181 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700182 int savedErrno = errno;
183 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
184 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000185 }
186
Yifan Hongecf937d2021-08-11 17:29:28 -0700187 auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700188 if (server == nullptr) {
189 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700190 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700191 }
192 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000193}
194
195sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000196 ExclusiveConnection connection;
197 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
198 ConnectionUse::CLIENT, &connection);
199 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000200 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000201}
202
Steven Moreland1be91352021-05-11 22:12:15 +0000203status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000204 ExclusiveConnection connection;
205 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
206 ConnectionUse::CLIENT, &connection);
207 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000208 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000209}
210
Steven Morelandc9d7b532021-06-04 20:57:41 +0000211bool RpcSession::shutdownAndWait(bool wait) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000212 RpcMutexUniqueLock _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000213 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000214
215 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000216
Steven Morelandc9d7b532021-06-04 20:57:41 +0000217 if (wait) {
218 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700219 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700220
Steven Morelanda59937e2021-10-04 17:42:30 -0700221 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000222 }
223
224 _l.unlock();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000225
Devin Moore66d5b7a2022-07-07 21:42:10 +0000226 if (status_t res = state()->sendObituaries(sp<RpcSession>::fromExisting(this)); res != OK) {
227 ALOGE("Failed to send obituaries as the RpcSession is shutting down: %s",
228 statusToString(res).c_str());
229 }
230
Steven Moreland27a8bc72021-09-29 16:07:41 -0700231 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000232
Steven Moreland659416d2021-05-11 00:47:50 +0000233 return true;
234}
235
Steven Morelandf5174272021-05-25 00:39:28 +0000236status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000237 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000238 ExclusiveConnection connection;
239 status_t status =
240 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
241 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
242 : ConnectionUse::CLIENT,
243 &connection);
244 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000245 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000246 sp<RpcSession>::fromExisting(this), reply, flags);
247}
248
Steven Moreland4f622fe2021-09-13 17:38:09 -0700249status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000250 // target is 0 because this is used to free BpBinder objects
251 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700252}
253
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000254status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000255 ExclusiveConnection connection;
256 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
257 ConnectionUse::CLIENT_REFCOUNT, &connection);
258 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000259 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
260 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000261}
262
263status_t RpcSession::readId() {
264 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000265 RpcMutexLockGuard _l(mMutex);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000266 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
267 }
268
Steven Moreland195edb82021-06-08 02:44:39 +0000269 ExclusiveConnection connection;
270 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
271 ConnectionUse::CLIENT, &connection);
272 if (status != OK) return status;
273
Steven Moreland826367f2021-09-10 14:05:31 -0700274 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000275 if (status != OK) return status;
276
Steven Moreland826367f2021-09-10 14:05:31 -0700277 LOG_RPC_DETAIL("RpcSession %p has id %s", this,
278 base::HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000279 return OK;
280}
281
Steven Morelanddd67b942021-07-23 17:15:41 -0700282void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000283 const sp<RpcSession>& session) {
284 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000285}
286
Steven Moreland19fc9f72021-06-10 03:57:30 +0000287void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000288 mCv.notify_all();
289}
290
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000291void RpcSession::WaitForShutdownListener::waitForShutdown(RpcMutexUniqueLock& lock,
Steven Moreland791e4662021-09-13 15:22:58 -0700292 const sp<RpcSession>& session) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700293 while (session->mConnections.mIncoming.size() > 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000294 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700295 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
296 "still.",
Steven Morelanda59937e2021-10-04 17:42:30 -0700297 session->mConnections.mIncoming.size());
Steven Moreland659416d2021-05-11 00:47:50 +0000298 }
299 }
300}
301
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000302void RpcSession::preJoinThreadOwnership(RpcMaybeThread thread) {
303 LOG_ALWAYS_FATAL_IF(thread.get_id() != rpc_this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000304
Steven Morelanda63ff932021-05-12 00:03:15 +0000305 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000306 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700307 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000308 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000309}
Steven Morelanda63ff932021-05-12 00:03:15 +0000310
Yifan Hong702115c2021-06-24 15:39:18 -0700311RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
312 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000313 // must be registered to allow arbitrary client code executing commands to
314 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700315 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000316
Steven Morelanddd67b942021-07-23 17:15:41 -0700317 status_t status;
318
319 if (connection == nullptr) {
320 status = DEAD_OBJECT;
321 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700322 status =
323 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700324 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000325
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000326 return PreJoinSetupResult{
327 .connection = std::move(connection),
328 .status = status,
329 };
330}
331
Yifan Hong194acf22021-06-29 18:44:56 -0700332namespace {
Andrei Homescu47f8c4f2022-04-30 01:38:24 +0000333#if !defined(__ANDROID__) || defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -0700334class JavaThreadAttacher {};
335#else
Yifan Hong194acf22021-06-29 18:44:56 -0700336// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
337// Android Runtime doesn't exist, no-op.
338class JavaThreadAttacher {
339public:
340 JavaThreadAttacher() {
341 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
342 // libbinder.
343 auto vm = getJavaVM();
344 if (vm == nullptr) return;
345
346 char threadName[16];
347 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
348 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
349 memcpy(threadName, defaultThreadName,
350 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
351 }
352 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
353 JavaVMAttachArgs args;
354 args.version = JNI_VERSION_1_2;
355 args.name = threadName;
356 args.group = nullptr;
357 JNIEnv* env;
358
359 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
360 "Cannot attach thread %s to JVM", threadName);
361 mAttached = true;
362 }
363 ~JavaThreadAttacher() {
364 if (!mAttached) return;
365 auto vm = getJavaVM();
366 LOG_ALWAYS_FATAL_IF(vm == nullptr,
367 "Unable to detach thread. No JavaVM, but it was present before!");
368
369 LOG_RPC_DETAIL("Detaching current thread from JVM");
370 if (vm->DetachCurrentThread() != JNI_OK) {
371 mAttached = false;
372 } else {
373 ALOGW("Unable to detach current thread from JVM");
374 }
375 }
376
377private:
378 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
379 bool mAttached = false;
380
381 static JavaVM* getJavaVM() {
382 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
383 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
384 if (fn == nullptr) return nullptr;
385 return fn();
386 }
387};
Yifan Hongd258e682021-11-01 18:34:42 -0700388#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700389} // namespace
390
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000391void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
392 sp<RpcConnection>& connection = setupResult.connection;
393
394 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700395 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700396 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000397 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000398 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000399 RpcState::CommandType::ANY);
400 if (status != OK) {
401 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
402 statusToString(status).c_str());
403 break;
404 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000405 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000406 } else {
407 ALOGE("Connection failed to init, closing with status %s",
408 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409 }
410
Steven Moreland659416d2021-05-11 00:47:50 +0000411 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000412 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000413 RpcMutexLockGuard _l(session->mMutex);
414 auto it = session->mConnections.mThreads.find(rpc_this_thread::get_id());
Steven Morelanda59937e2021-10-04 17:42:30 -0700415 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000416 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700417 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000418
Steven Moreland659416d2021-05-11 00:47:50 +0000419 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000420 }
421
Steven Morelanddd67b942021-07-23 17:15:41 -0700422 // done after all cleanup, since session shutdown progresses via callbacks here
423 if (connection != nullptr) {
424 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
425 "bad state: connection object guaranteed to be in list");
426 }
427
Steven Moreland659416d2021-05-11 00:47:50 +0000428 session = nullptr;
429
430 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000431 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000432 }
433}
434
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000435sp<RpcServer> RpcSession::server() {
436 RpcServer* unsafeServer = mForServer.unsafe_get();
437 sp<RpcServer> server = mForServer.promote();
438
439 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
440 "wp<> is to avoid strong cycle only");
441 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000442}
443
Steven Moreland826367f2021-09-10 14:05:31 -0700444status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
445 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000446 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000447 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700448 LOG_ALWAYS_FATAL_IF(mConnections.mOutgoing.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000449 "Must only setup session once, but already has %zu clients",
Steven Morelanda59937e2021-10-04 17:42:30 -0700450 mConnections.mOutgoing.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000451 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700452
Yifan Hong832521e2021-08-05 14:55:40 -0700453 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000454
Steven Moreland27a8bc72021-09-29 16:07:41 -0700455 auto oldProtocolVersion = mProtocolVersion;
456 auto cleanup = base::ScopeGuard([&] {
457 // if any threads are started, shut them down
458 (void)shutdownAndWait(true);
459
460 mShutdownListener = nullptr;
461 mEventListener.clear();
462
463 mId.clear();
464
465 mShutdownTrigger = nullptr;
466 mRpcBinderState = std::make_unique<RpcState>();
467
468 // protocol version may have been downgraded - if we reuse this object
469 // to connect to another server, force that server to request a
470 // downgrade again
471 mProtocolVersion = oldProtocolVersion;
472
Steven Morelanda59937e2021-10-04 17:42:30 -0700473 mConnections = {};
Steven Moreland27a8bc72021-09-29 16:07:41 -0700474 });
475
Steven Moreland826367f2021-09-10 14:05:31 -0700476 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000477
Steven Morelandbf57bce2021-07-26 15:26:12 -0700478 {
479 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700480 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
481 ConnectionUse::CLIENT, &connection);
482 status != OK)
483 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700484
485 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700486 if (status_t status =
487 state()->readNewSessionResponse(connection.get(),
488 sp<RpcSession>::fromExisting(this), &version);
489 status != OK)
490 return status;
491 if (!setProtocolVersion(version)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700492 }
493
Steven Morelanda5036f02021-06-08 02:26:57 +0000494 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000495 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000496 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000497 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700498 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000499 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700500 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000501 }
502
503 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700504 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000505 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700506 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000507 }
508
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000509#ifdef BINDER_RPC_SINGLE_THREADED
510 constexpr size_t outgoingThreads = 1;
511#else // BINDER_RPC_SINGLE_THREADED
Yifan Hong1f44f982021-10-08 17:16:47 -0700512 size_t outgoingThreads = std::min(numThreadsAvailable, mMaxOutgoingThreads);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000513#endif // BINDER_RPC_SINGLE_THREADED
Yifan Hong1f44f982021-10-08 17:16:47 -0700514 ALOGI_IF(outgoingThreads != numThreadsAvailable,
515 "Server hints client to start %zu outgoing threads, but client will only start %zu "
516 "because it is preconfigured to start at most %zu outgoing threads.",
517 numThreadsAvailable, outgoingThreads, mMaxOutgoingThreads);
518
Steven Morelanda5036f02021-06-08 02:26:57 +0000519 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000520 // instead of all at once - the other side should be responsible for setting
521 // up additional connections. We need to create at least one (unless 0 are
522 // requested to be set) in order to allow the other side to reliably make
523 // any requests at all.
524
Steven Moreland4198a122021-08-03 17:37:58 -0700525 // we've already setup one client
Yifan Hong1f44f982021-10-08 17:16:47 -0700526 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing (server max: %zu) and %zu "
527 "incoming threads",
528 outgoingThreads, numThreadsAvailable, mMaxIncomingThreads);
529 for (size_t i = 0; i + 1 < outgoingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700530 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700531 }
532
Yifan Hong10423062021-10-08 16:26:32 -0700533 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700534 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000535 }
536
Steven Moreland27a8bc72021-09-29 16:07:41 -0700537 cleanup.Disable();
538
Steven Moreland2372f9d2021-08-05 15:42:01 -0700539 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000540}
541
Steven Moreland2372f9d2021-08-05 15:42:01 -0700542status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700543 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700544 return setupOneSocketConnection(addr, sessionId, incoming);
545 });
546}
547
Steven Moreland2372f9d2021-08-05 15:42:01 -0700548status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700549 const std::vector<uint8_t>& sessionId,
550 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000551 for (size_t tries = 0; tries < 5; tries++) {
552 if (tries > 0) usleep(10000);
553
Yifan Hongb675ffe2021-08-05 16:37:17 -0700554 unique_fd serverFd(TEMP_FAILURE_RETRY(
555 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000556 if (serverFd == -1) {
557 int savedErrno = errno;
558 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
559 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700560 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000561 }
562
563 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700564 int connErrno = errno;
565 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
566 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
567 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
568 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
569 if (pollStatus != OK) {
570 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
571 statusToString(pollStatus).c_str());
572 return pollStatus;
573 }
574 // Set connErrno to the errno that connect() would have set if the fd were blocking.
575 socklen_t connErrnoLen = sizeof(connErrno);
576 int ret =
577 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
578 if (ret == -1) {
579 int savedErrno = errno;
580 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
581 "(Original error from connect() is: %s)",
582 strerror(savedErrno), strerror(connErrno));
583 return -savedErrno;
584 }
585 // Retrieved the real connErrno as if connect() was called with a blocking socket
586 // fd. Continue checking connErrno.
587 }
588 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000589 ALOGW("Connection reset on %s", addr.toString().c_str());
590 continue;
591 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700592 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
593 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700594 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700595 strerror(connErrno));
596 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700597 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000598 }
Yifan Hong702115c2021-06-24 15:39:18 -0700599 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
600
Steven Moreland4198a122021-08-03 17:37:58 -0700601 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000602 }
603
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000604 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700605 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000606}
607
Steven Moreland826367f2021-09-10 14:05:31 -0700608status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700609 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700610 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700611 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700612 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700613 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700614 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700615 }
616
617 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
618
Steven Moreland826367f2021-09-10 14:05:31 -0700619 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
620 ALOGE("Session ID too big %zu", sessionId.size());
621 return BAD_VALUE;
622 }
623
Steven Moreland4198a122021-08-03 17:37:58 -0700624 RpcConnectionHeader header{
625 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
626 .options = 0,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000627 .fileDescriptorTransportMode = static_cast<uint8_t>(mFileDescriptorTransportMode),
Steven Moreland826367f2021-09-10 14:05:31 -0700628 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700629 };
Steven Moreland4198a122021-08-03 17:37:58 -0700630
Steven Moreland826367f2021-09-10 14:05:31 -0700631 if (incoming) {
632 header.options |= RPC_CONNECTION_OPTION_INCOMING;
633 }
Steven Moreland4198a122021-08-03 17:37:58 -0700634
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000635 iovec headerIov{&header, sizeof(header)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000636 auto sendHeaderStatus = server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1,
637 std::nullopt, nullptr);
Yifan Hong8c950422021-08-05 17:13:55 -0700638 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700639 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700640 statusToString(sendHeaderStatus).c_str());
641 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700642 }
643
Steven Moreland826367f2021-09-10 14:05:31 -0700644 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000645 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
646 sessionId.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000647 auto sendSessionIdStatus =
648 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1,
649 std::nullopt, nullptr);
Steven Moreland826367f2021-09-10 14:05:31 -0700650 if (sendSessionIdStatus != OK) {
651 ALOGE("Could not write session ID ('%s') to socket: %s",
652 base::HexString(sessionId.data(), sessionId.size()).c_str(),
653 statusToString(sendSessionIdStatus).c_str());
654 return sendSessionIdStatus;
655 }
656 }
657
Steven Moreland4198a122021-08-03 17:37:58 -0700658 LOG_RPC_DETAIL("Socket at client: header sent");
659
660 if (incoming) {
661 return addIncomingConnection(std::move(server));
662 } else {
663 return addOutgoingConnection(std::move(server), true /*init*/);
664 }
665}
666
Steven Moreland2372f9d2021-08-05 15:42:01 -0700667status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000668 RpcMutex mutex;
669 RpcConditionVariable joinCv;
670 RpcMutexUniqueLock lock(mutex);
671 RpcMaybeThread thread;
Steven Morelandfba6f772021-07-15 22:45:09 +0000672 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
673 bool ownershipTransferred = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000674 thread = RpcMaybeThread([&]() {
675 RpcMutexUniqueLock threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700676 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000677 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
678 sp<RpcSession> session = thiz;
679 session->preJoinThreadOwnership(std::move(thread));
680
681 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700682 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000683
684 ownershipTransferred = true;
685 threadLock.unlock();
686 joinCv.notify_one();
687 // do not use & vars below
688
689 RpcSession::join(std::move(session), std::move(setupResult));
690 });
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000691 rpcJoinIfSingleThreaded(thread);
Steven Morelandfba6f772021-07-15 22:45:09 +0000692 joinCv.wait(lock, [&] { return ownershipTransferred; });
693 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700694 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000695}
696
Yifan Hong832521e2021-08-05 14:55:40 -0700697status_t RpcSession::initShutdownTrigger() {
698 // first client connection added, but setForServer not called, so
699 // initializaing for a client.
700 if (mShutdownTrigger == nullptr) {
701 mShutdownTrigger = FdTrigger::make();
702 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
703 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
704 }
705 return OK;
706}
707
Steven Moreland2372f9d2021-08-05 15:42:01 -0700708status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000709 sp<RpcConnection> connection = sp<RpcConnection>::make();
710 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000711 RpcMutexLockGuard _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700712 connection->rpcTransport = std::move(rpcTransport);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000713 connection->exclusiveTid = rpcGetThreadId();
Steven Morelanda59937e2021-10-04 17:42:30 -0700714 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000715 }
716
Steven Morelandb86e26b2021-06-12 00:35:58 +0000717 status_t status = OK;
718 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700719 status =
720 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000721 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000722
Andrei Homescuc8490872022-06-23 05:18:51 +0000723 clearConnectionTid(connection);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000724
Steven Moreland2372f9d2021-08-05 15:42:01 -0700725 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000726}
727
Steven Morelanda8b44292021-06-08 01:27:53 +0000728bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700729 const std::vector<uint8_t>& sessionId,
730 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000731 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
732 LOG_ALWAYS_FATAL_IF(server == nullptr);
733 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
734 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000735 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Andrei Homescu5e301462022-05-12 00:52:34 +0000736 LOG_ALWAYS_FATAL_IF(mCtx != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000737
738 mShutdownTrigger = FdTrigger::make();
739 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000740
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000741 mId = sessionId;
742 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000743 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700744 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000745 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000746}
747
Yifan Hong702115c2021-06-24 15:39:18 -0700748sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
749 std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000750 RpcMutexLockGuard _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700751
Yifan Hong10423062021-10-08 16:26:32 -0700752 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700753 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700754 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700755 return nullptr;
756 }
757
Steven Morelanddd67b942021-07-23 17:15:41 -0700758 // Don't accept any more connections, some have shutdown. Usually this
759 // happens when new connections are still being established as part of a
760 // very short-lived session which shuts down after it already started
761 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700762 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700763 return nullptr;
764 }
765
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000766 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700767 session->rpcTransport = std::move(rpcTransport);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000768 session->exclusiveTid = rpcGetThreadId();
Steven Morelanddd67b942021-07-23 17:15:41 -0700769
Steven Morelanda59937e2021-10-04 17:42:30 -0700770 mConnections.mIncoming.push_back(session);
771 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000772
773 return session;
774}
775
Steven Moreland19fc9f72021-06-10 03:57:30 +0000776bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000777 RpcMutexUniqueLock _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700778 if (auto it =
779 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
780 it != mConnections.mIncoming.end()) {
781 mConnections.mIncoming.erase(it);
782 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000783 sp<EventListener> listener = mEventListener.promote();
784 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700785 _l.unlock();
786 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000787 }
Steven Morelandee78e762021-05-05 21:12:51 +0000788 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000789 return true;
790 }
791 return false;
792}
793
Andrei Homescuc8490872022-06-23 05:18:51 +0000794void RpcSession::clearConnectionTid(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000795 RpcMutexUniqueLock _l(mMutex);
Andrei Homescuc8490872022-06-23 05:18:51 +0000796 connection->exclusiveTid = std::nullopt;
797 if (mConnections.mWaitingThreads > 0) {
798 _l.unlock();
799 mAvailableConnectionCv.notify_one();
800 }
801}
802
Yifan Hong9734cfc2021-09-13 16:14:09 -0700803std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700804 return mCtx->getCertificate(format);
805}
806
Steven Moreland195edb82021-06-08 02:44:39 +0000807status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
808 ExclusiveConnection* connection) {
809 connection->mSession = session;
810 connection->mConnection = nullptr;
811 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000812
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000813 uint64_t tid = rpcGetThreadId();
814 RpcMutexUniqueLock _l(session->mMutex);
Steven Moreland195edb82021-06-08 02:44:39 +0000815
Steven Morelanda59937e2021-10-04 17:42:30 -0700816 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000817 while (true) {
818 sp<RpcConnection> exclusive;
819 sp<RpcConnection> available;
820
821 // CHECK FOR DEDICATED CLIENT SOCKET
822 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000823 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700824 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
825 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000826
827 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700828 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000829 //
830 // Imagine we have more than one thread in play, and a single thread
831 // sends a synchronous, then an asynchronous command. Imagine the
832 // asynchronous command is sent on the first client connection. Then, if
833 // we naively send a synchronous command to that same connection, the
834 // thread on the far side might be busy processing the asynchronous
835 // command. So, we move to considering the second available thread
836 // for subsequent calls.
837 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700838 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
839 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000840 }
841
Steven Morelandc7d40132021-06-10 03:42:11 +0000842 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000843 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000844 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000845 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000846 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700847 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000848
849 // asynchronous calls cannot be nested, we currently allow ref count
850 // calls to be nested (so that you can use this without having extra
851 // threads). Note 'drainCommands' is used so that these ref counts can't
852 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000853 if (exclusiveIncoming != nullptr) {
854 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000855 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000856 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000857 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
858 // prefer available socket, but if we don't have one, don't
859 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000860 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000861 }
862 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000863 }
864
Steven Moreland85e067b2021-05-26 17:43:53 +0000865 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000866 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000867 connection->mConnection = exclusive;
868 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000869 break;
870 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000871 connection->mConnection = available;
872 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000873 break;
874 }
875
Steven Morelanda59937e2021-10-04 17:42:30 -0700876 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000877 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
878 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
879 "reason: %d. Incoming connections: %zu. %s.",
880 static_cast<int>(use), session->mConnections.mIncoming.size(),
881 (session->server()
882 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
883 "for the corresponding client"
884 : "This is a client session, so see RpcSession::setMaxOutgoingThreads "
885 "for this client or RpcServer::setMaxThreads for the corresponding "
886 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000887 return WOULD_BLOCK;
888 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000889
Steven Moreland85e067b2021-05-26 17:43:53 +0000890 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700891 session->mConnections.mOutgoing.size(),
892 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000893 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000894 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700895 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000896
897 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000898}
899
Andrei Homescue922b232022-04-23 03:41:09 +0000900void RpcSession::ExclusiveConnection::findConnection(uint64_t tid, sp<RpcConnection>* exclusive,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000901 sp<RpcConnection>* available,
902 std::vector<sp<RpcConnection>>& sockets,
903 size_t socketsIndexHint) {
904 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
905 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
906
907 if (*exclusive != nullptr) return; // consistent with break below
908
909 for (size_t i = 0; i < sockets.size(); i++) {
910 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
911
Steven Moreland85e067b2021-05-26 17:43:53 +0000912 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000913 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
914 *available = socket;
915 continue;
916 }
917
Steven Moreland85e067b2021-05-26 17:43:53 +0000918 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000919 // (nested transactions)
920 if (exclusive && socket->exclusiveTid == tid) {
921 *exclusive = socket;
922 break; // consistent with return above
923 }
924 }
925}
926
927RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000928 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000929 // is using this fd, and it retains the right to it. So, we don't give up
930 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000931 if (!mReentrant && mConnection != nullptr) {
Andrei Homescuc8490872022-06-23 05:18:51 +0000932 mSession->clearConnectionTid(mConnection);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000933 }
934}
935
936} // namespace android