blob: d347262040ad043d9d5c22dfa12aec52406c6cb6 [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
Andrei Homescu9b58a462022-07-28 02:26:46 +000039#include "BuildFlags.h"
Yifan Hong8c950422021-08-05 17:13:55 -070040#include "FdTrigger.h"
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000041#include "OS.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000042#include "RpcSocketAddress.h"
43#include "RpcState.h"
44#include "RpcWireFormat.h"
Yifan Hongb675ffe2021-08-05 16:37:17 -070045#include "Utils.h"
Steven Morelandbdb53ab2021-05-05 17:57:41 +000046
Andrei Homescu47f8c4f2022-04-30 01:38:24 +000047#if defined(__ANDROID__) && !defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -070048#include <android_runtime/vm.h>
49#include <jni.h>
50#endif
51
Steven Morelandbdb53ab2021-05-05 17:57:41 +000052namespace android {
53
54using base::unique_fd;
55
Yifan Hongecf937d2021-08-11 17:29:28 -070056RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +000057 LOG_RPC_DETAIL("RpcSession created %p", this);
58
Steven Moreland27a8bc72021-09-29 16:07:41 -070059 mRpcBinderState = std::make_unique<RpcState>();
Steven Morelandbdb53ab2021-05-05 17:57:41 +000060}
61RpcSession::~RpcSession() {
62 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
63
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000064 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -070065 LOG_ALWAYS_FATAL_IF(mConnections.mIncoming.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000066 "Should not be able to destroy a session with servers in use.");
67}
68
Yifan Hongecf937d2021-08-11 17:29:28 -070069sp<RpcSession> RpcSession::make() {
Yifan Hong702115c2021-06-24 15:39:18 -070070 // Default is without TLS.
Yifan Hongfdd9f692021-09-09 15:12:52 -070071 return make(RpcTransportCtxFactoryRaw::make());
Yifan Hongecf937d2021-08-11 17:29:28 -070072}
73
Yifan Hongfdd9f692021-09-09 15:12:52 -070074sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
Yifan Hongecf937d2021-08-11 17:29:28 -070075 auto ctx = rpcTransportCtxFactory->newClientCtx();
76 if (ctx == nullptr) return nullptr;
Yifan Hongecf937d2021-08-11 17:29:28 -070077 return sp<RpcSession>::make(std::move(ctx));
Steven Morelandbdb53ab2021-05-05 17:57:41 +000078}
79
Yifan Hong10423062021-10-08 16:26:32 -070080void RpcSession::setMaxIncomingThreads(size_t threads) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000081 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +000082 LOG_ALWAYS_FATAL_IF(mStartedSetup,
83 "Must set max incoming threads before setting up connections");
Yifan Hong10423062021-10-08 16:26:32 -070084 mMaxIncomingThreads = threads;
Steven Moreland103424e2021-06-02 18:16:19 +000085}
86
Yifan Hong10423062021-10-08 16:26:32 -070087size_t RpcSession::getMaxIncomingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000088 RpcMutexLockGuard _l(mMutex);
Yifan Hong10423062021-10-08 16:26:32 -070089 return mMaxIncomingThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000090}
91
Yifan Hong1f44f982021-10-08 17:16:47 -070092void RpcSession::setMaxOutgoingThreads(size_t threads) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +000093 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +000094 LOG_ALWAYS_FATAL_IF(mStartedSetup,
95 "Must set max outgoing threads before setting up connections");
Yifan Hong1f44f982021-10-08 17:16:47 -070096 mMaxOutgoingThreads = threads;
97}
98
99size_t RpcSession::getMaxOutgoingThreads() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000100 RpcMutexLockGuard _l(mMutex);
Yifan Hong1f44f982021-10-08 17:16:47 -0700101 return mMaxOutgoingThreads;
102}
103
Andrei Homescu9b58a462022-07-28 02:26:46 +0000104bool RpcSession::setProtocolVersionInternal(uint32_t version, bool checkStarted) {
Steven Morelandbf57bce2021-07-26 15:26:12 -0700105 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
106 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
107 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
108 "is %u).",
109 version, RPC_WIRE_PROTOCOL_VERSION);
110 return false;
111 }
112
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000113 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000114 LOG_ALWAYS_FATAL_IF(checkStarted && mStartedSetup,
115 "Must set protocol version before setting up connections");
Steven Moreland40b736e2021-07-30 14:37:10 -0700116 if (mProtocolVersion && version > *mProtocolVersion) {
117 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
118 *mProtocolVersion, version);
119 return false;
120 }
121
Steven Morelandbf57bce2021-07-26 15:26:12 -0700122 mProtocolVersion = version;
123 return true;
124}
125
Andrei Homescu9b58a462022-07-28 02:26:46 +0000126bool RpcSession::setProtocolVersion(uint32_t version) {
127 return setProtocolVersionInternal(version, true);
128}
129
Steven Morelandbf57bce2021-07-26 15:26:12 -0700130std::optional<uint32_t> RpcSession::getProtocolVersion() {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000131 RpcMutexLockGuard _l(mMutex);
Steven Morelandbf57bce2021-07-26 15:26:12 -0700132 return mProtocolVersion;
133}
134
Frederick Mayle69a0c992022-05-26 20:38:39 +0000135void RpcSession::setFileDescriptorTransportMode(FileDescriptorTransportMode mode) {
Andrei Homescu9b58a462022-07-28 02:26:46 +0000136 RpcMutexLockGuard _l(mMutex);
137 LOG_ALWAYS_FATAL_IF(mStartedSetup,
138 "Must set file descriptor transport mode before setting up connections");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000139 mFileDescriptorTransportMode = mode;
140}
141
142RpcSession::FileDescriptorTransportMode RpcSession::getFileDescriptorTransportMode() {
143 return mFileDescriptorTransportMode;
144}
145
Steven Moreland2372f9d2021-08-05 15:42:01 -0700146status_t RpcSession::setupUnixDomainClient(const char* path) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000147 return setupSocketClient(UnixSocketAddress(path));
148}
149
Steven Moreland2372f9d2021-08-05 15:42:01 -0700150status_t RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000151 return setupSocketClient(VsockSocketAddress(cid, port));
152}
153
Steven Moreland2372f9d2021-08-05 15:42:01 -0700154status_t RpcSession::setupInetClient(const char* addr, unsigned int port) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000155 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700156 if (aiStart == nullptr) return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000157 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
158 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700159 if (status_t status = setupSocketClient(socketAddress); status == OK) return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000160 }
161 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 -0700162 return NAME_NOT_FOUND;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000163}
164
Steven Moreland2372f9d2021-08-05 15:42:01 -0700165status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
Frederick Mayle297c2772022-05-05 01:21:04 +0000166 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700167 if (!fd.ok()) {
168 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700169 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700170 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700171 if (auto res = setNonBlocking(fd); !res.ok()) {
172 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
173 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
174 }
Frederick Mayle297c2772022-05-05 01:21:04 +0000175 status_t status = initAndAddConnection(std::move(fd), sessionId, incoming);
176 fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
177 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700178 });
179}
180
Steven Moreland2372f9d2021-08-05 15:42:01 -0700181status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700182 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700183 if (auto status = initShutdownTrigger(); status != OK) return status;
184
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000185 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
186
187 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700188 int savedErrno = errno;
189 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
190 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000191 }
192
Yifan Hongecf937d2021-08-11 17:29:28 -0700193 auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700194 if (server == nullptr) {
195 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700196 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700197 }
198 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000199}
200
201sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000202 ExclusiveConnection connection;
203 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
204 ConnectionUse::CLIENT, &connection);
205 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000206 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000207}
208
Steven Moreland1be91352021-05-11 22:12:15 +0000209status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000210 ExclusiveConnection connection;
211 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
212 ConnectionUse::CLIENT, &connection);
213 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000214 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000215}
216
Steven Morelandc9d7b532021-06-04 20:57:41 +0000217bool RpcSession::shutdownAndWait(bool wait) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000218 RpcMutexUniqueLock _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000219 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000220
221 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000222
Steven Morelandc9d7b532021-06-04 20:57:41 +0000223 if (wait) {
224 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700225 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700226
Steven Morelanda59937e2021-10-04 17:42:30 -0700227 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000228 }
229
230 _l.unlock();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000231
Devin Moore66d5b7a2022-07-07 21:42:10 +0000232 if (status_t res = state()->sendObituaries(sp<RpcSession>::fromExisting(this)); res != OK) {
233 ALOGE("Failed to send obituaries as the RpcSession is shutting down: %s",
234 statusToString(res).c_str());
235 }
236
Steven Moreland27a8bc72021-09-29 16:07:41 -0700237 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000238
Steven Moreland659416d2021-05-11 00:47:50 +0000239 return true;
240}
241
Steven Morelandf5174272021-05-25 00:39:28 +0000242status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000243 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000244 ExclusiveConnection connection;
245 status_t status =
246 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
247 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
248 : ConnectionUse::CLIENT,
249 &connection);
250 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000251 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000252 sp<RpcSession>::fromExisting(this), reply, flags);
253}
254
Steven Moreland4f622fe2021-09-13 17:38:09 -0700255status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000256 // target is 0 because this is used to free BpBinder objects
257 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700258}
259
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000260status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000261 ExclusiveConnection connection;
262 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
263 ConnectionUse::CLIENT_REFCOUNT, &connection);
264 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000265 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
266 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000267}
268
269status_t RpcSession::readId() {
270 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000271 RpcMutexLockGuard _l(mMutex);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000272 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
273 }
274
Steven Moreland195edb82021-06-08 02:44:39 +0000275 ExclusiveConnection connection;
276 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
277 ConnectionUse::CLIENT, &connection);
278 if (status != OK) return status;
279
Steven Moreland826367f2021-09-10 14:05:31 -0700280 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000281 if (status != OK) return status;
282
Steven Moreland826367f2021-09-10 14:05:31 -0700283 LOG_RPC_DETAIL("RpcSession %p has id %s", this,
284 base::HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000285 return OK;
286}
287
Steven Morelanddd67b942021-07-23 17:15:41 -0700288void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000289 const sp<RpcSession>& session) {
290 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000291}
292
Steven Moreland19fc9f72021-06-10 03:57:30 +0000293void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000294 mCv.notify_all();
295}
296
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000297void RpcSession::WaitForShutdownListener::waitForShutdown(RpcMutexUniqueLock& lock,
Steven Moreland791e4662021-09-13 15:22:58 -0700298 const sp<RpcSession>& session) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700299 while (session->mConnections.mIncoming.size() > 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000300 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700301 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
302 "still.",
Steven Morelanda59937e2021-10-04 17:42:30 -0700303 session->mConnections.mIncoming.size());
Steven Moreland659416d2021-05-11 00:47:50 +0000304 }
305 }
306}
307
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000308void RpcSession::preJoinThreadOwnership(RpcMaybeThread thread) {
309 LOG_ALWAYS_FATAL_IF(thread.get_id() != rpc_this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000310
Steven Morelanda63ff932021-05-12 00:03:15 +0000311 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000312 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700313 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000314 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000315}
Steven Morelanda63ff932021-05-12 00:03:15 +0000316
Yifan Hong702115c2021-06-24 15:39:18 -0700317RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
318 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000319 // must be registered to allow arbitrary client code executing commands to
320 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700321 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000322
Steven Morelanddd67b942021-07-23 17:15:41 -0700323 status_t status;
324
325 if (connection == nullptr) {
326 status = DEAD_OBJECT;
327 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700328 status =
329 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700330 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000331
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000332 return PreJoinSetupResult{
333 .connection = std::move(connection),
334 .status = status,
335 };
336}
337
Yifan Hong194acf22021-06-29 18:44:56 -0700338namespace {
Andrei Homescu47f8c4f2022-04-30 01:38:24 +0000339#if !defined(__ANDROID__) || defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -0700340class JavaThreadAttacher {};
341#else
Yifan Hong194acf22021-06-29 18:44:56 -0700342// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
343// Android Runtime doesn't exist, no-op.
344class JavaThreadAttacher {
345public:
346 JavaThreadAttacher() {
347 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
348 // libbinder.
349 auto vm = getJavaVM();
350 if (vm == nullptr) return;
351
352 char threadName[16];
353 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
354 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
355 memcpy(threadName, defaultThreadName,
356 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
357 }
358 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
359 JavaVMAttachArgs args;
360 args.version = JNI_VERSION_1_2;
361 args.name = threadName;
362 args.group = nullptr;
363 JNIEnv* env;
364
365 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
366 "Cannot attach thread %s to JVM", threadName);
367 mAttached = true;
368 }
369 ~JavaThreadAttacher() {
370 if (!mAttached) return;
371 auto vm = getJavaVM();
372 LOG_ALWAYS_FATAL_IF(vm == nullptr,
373 "Unable to detach thread. No JavaVM, but it was present before!");
374
375 LOG_RPC_DETAIL("Detaching current thread from JVM");
376 if (vm->DetachCurrentThread() != JNI_OK) {
377 mAttached = false;
378 } else {
379 ALOGW("Unable to detach current thread from JVM");
380 }
381 }
382
383private:
384 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
385 bool mAttached = false;
386
387 static JavaVM* getJavaVM() {
388 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
389 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
390 if (fn == nullptr) return nullptr;
391 return fn();
392 }
393};
Yifan Hongd258e682021-11-01 18:34:42 -0700394#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700395} // namespace
396
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000397void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
398 sp<RpcConnection>& connection = setupResult.connection;
399
400 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700401 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700402 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000403 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000404 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000405 RpcState::CommandType::ANY);
406 if (status != OK) {
407 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
408 statusToString(status).c_str());
409 break;
410 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000411 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000412 } else {
413 ALOGE("Connection failed to init, closing with status %s",
414 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000415 }
416
Steven Moreland659416d2021-05-11 00:47:50 +0000417 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000418 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000419 RpcMutexLockGuard _l(session->mMutex);
420 auto it = session->mConnections.mThreads.find(rpc_this_thread::get_id());
Steven Morelanda59937e2021-10-04 17:42:30 -0700421 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000422 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700423 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000424
Steven Moreland659416d2021-05-11 00:47:50 +0000425 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000426 }
427
Steven Morelanddd67b942021-07-23 17:15:41 -0700428 // done after all cleanup, since session shutdown progresses via callbacks here
429 if (connection != nullptr) {
430 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
431 "bad state: connection object guaranteed to be in list");
432 }
433
Steven Moreland659416d2021-05-11 00:47:50 +0000434 session = nullptr;
435
436 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000437 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000438 }
439}
440
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000441sp<RpcServer> RpcSession::server() {
442 RpcServer* unsafeServer = mForServer.unsafe_get();
443 sp<RpcServer> server = mForServer.promote();
444
445 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
446 "wp<> is to avoid strong cycle only");
447 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000448}
449
Steven Moreland826367f2021-09-10 14:05:31 -0700450status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
451 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000452 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000453 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000454 LOG_ALWAYS_FATAL_IF(mStartedSetup, "Must only setup session once");
455 mStartedSetup = true;
456
457 if constexpr (!kEnableRpcThreads) {
458 LOG_ALWAYS_FATAL_IF(mMaxIncomingThreads > 0,
459 "Incoming threads are not supported on single-threaded libbinder");
460 // mMaxIncomingThreads should not change from here to its use below,
461 // since we set mStartedSetup==true and setMaxIncomingThreads checks
462 // for that
463 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000464 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700465
Yifan Hong832521e2021-08-05 14:55:40 -0700466 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000467
Steven Moreland27a8bc72021-09-29 16:07:41 -0700468 auto oldProtocolVersion = mProtocolVersion;
469 auto cleanup = base::ScopeGuard([&] {
470 // if any threads are started, shut them down
471 (void)shutdownAndWait(true);
472
473 mShutdownListener = nullptr;
474 mEventListener.clear();
475
476 mId.clear();
477
478 mShutdownTrigger = nullptr;
479 mRpcBinderState = std::make_unique<RpcState>();
480
481 // protocol version may have been downgraded - if we reuse this object
482 // to connect to another server, force that server to request a
483 // downgrade again
484 mProtocolVersion = oldProtocolVersion;
485
Steven Morelanda59937e2021-10-04 17:42:30 -0700486 mConnections = {};
Steven Moreland27a8bc72021-09-29 16:07:41 -0700487 });
488
Steven Moreland826367f2021-09-10 14:05:31 -0700489 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000490
Steven Morelandbf57bce2021-07-26 15:26:12 -0700491 {
492 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700493 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
494 ConnectionUse::CLIENT, &connection);
495 status != OK)
496 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700497
498 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700499 if (status_t status =
500 state()->readNewSessionResponse(connection.get(),
501 sp<RpcSession>::fromExisting(this), &version);
502 status != OK)
503 return status;
Andrei Homescu9b58a462022-07-28 02:26:46 +0000504 if (!setProtocolVersionInternal(version, false)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700505 }
506
Steven Morelanda5036f02021-06-08 02:26:57 +0000507 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000508 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000509 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000510 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700511 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000512 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700513 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000514 }
515
516 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700517 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000518 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700519 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000520 }
521
Yifan Hong1f44f982021-10-08 17:16:47 -0700522 size_t outgoingThreads = std::min(numThreadsAvailable, mMaxOutgoingThreads);
523 ALOGI_IF(outgoingThreads != numThreadsAvailable,
524 "Server hints client to start %zu outgoing threads, but client will only start %zu "
525 "because it is preconfigured to start at most %zu outgoing threads.",
526 numThreadsAvailable, outgoingThreads, mMaxOutgoingThreads);
527
Steven Morelanda5036f02021-06-08 02:26:57 +0000528 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000529 // instead of all at once - the other side should be responsible for setting
530 // up additional connections. We need to create at least one (unless 0 are
531 // requested to be set) in order to allow the other side to reliably make
532 // any requests at all.
533
Steven Moreland4198a122021-08-03 17:37:58 -0700534 // we've already setup one client
Yifan Hong1f44f982021-10-08 17:16:47 -0700535 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing (server max: %zu) and %zu "
536 "incoming threads",
537 outgoingThreads, numThreadsAvailable, mMaxIncomingThreads);
538 for (size_t i = 0; i + 1 < outgoingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700539 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700540 }
541
Yifan Hong10423062021-10-08 16:26:32 -0700542 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700543 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000544 }
545
Steven Moreland27a8bc72021-09-29 16:07:41 -0700546 cleanup.Disable();
547
Steven Moreland2372f9d2021-08-05 15:42:01 -0700548 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000549}
550
Steven Moreland2372f9d2021-08-05 15:42:01 -0700551status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700552 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700553 return setupOneSocketConnection(addr, sessionId, incoming);
554 });
555}
556
Steven Moreland2372f9d2021-08-05 15:42:01 -0700557status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700558 const std::vector<uint8_t>& sessionId,
559 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000560 for (size_t tries = 0; tries < 5; tries++) {
561 if (tries > 0) usleep(10000);
562
Yifan Hongb675ffe2021-08-05 16:37:17 -0700563 unique_fd serverFd(TEMP_FAILURE_RETRY(
564 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000565 if (serverFd == -1) {
566 int savedErrno = errno;
567 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
568 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700569 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000570 }
571
572 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700573 int connErrno = errno;
574 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
575 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
576 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
577 status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
578 if (pollStatus != OK) {
579 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
580 statusToString(pollStatus).c_str());
581 return pollStatus;
582 }
583 // Set connErrno to the errno that connect() would have set if the fd were blocking.
584 socklen_t connErrnoLen = sizeof(connErrno);
585 int ret =
586 getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
587 if (ret == -1) {
588 int savedErrno = errno;
589 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
590 "(Original error from connect() is: %s)",
591 strerror(savedErrno), strerror(connErrno));
592 return -savedErrno;
593 }
594 // Retrieved the real connErrno as if connect() was called with a blocking socket
595 // fd. Continue checking connErrno.
596 }
597 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000598 ALOGW("Connection reset on %s", addr.toString().c_str());
599 continue;
600 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700601 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
602 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700603 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700604 strerror(connErrno));
605 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700606 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000607 }
Yifan Hong702115c2021-06-24 15:39:18 -0700608 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
609
Steven Moreland4198a122021-08-03 17:37:58 -0700610 return initAndAddConnection(std::move(serverFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000611 }
612
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000613 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700614 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000615}
616
Steven Moreland826367f2021-09-10 14:05:31 -0700617status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700618 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700619 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700620 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700621 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700622 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700623 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700624 }
625
626 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
627
Steven Moreland826367f2021-09-10 14:05:31 -0700628 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
629 ALOGE("Session ID too big %zu", sessionId.size());
630 return BAD_VALUE;
631 }
632
Steven Moreland4198a122021-08-03 17:37:58 -0700633 RpcConnectionHeader header{
634 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
635 .options = 0,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000636 .fileDescriptorTransportMode = static_cast<uint8_t>(mFileDescriptorTransportMode),
Steven Moreland826367f2021-09-10 14:05:31 -0700637 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700638 };
Steven Moreland4198a122021-08-03 17:37:58 -0700639
Steven Moreland826367f2021-09-10 14:05:31 -0700640 if (incoming) {
641 header.options |= RPC_CONNECTION_OPTION_INCOMING;
642 }
Steven Moreland4198a122021-08-03 17:37:58 -0700643
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000644 iovec headerIov{&header, sizeof(header)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000645 auto sendHeaderStatus = server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1,
646 std::nullopt, nullptr);
Yifan Hong8c950422021-08-05 17:13:55 -0700647 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700648 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700649 statusToString(sendHeaderStatus).c_str());
650 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700651 }
652
Steven Moreland826367f2021-09-10 14:05:31 -0700653 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000654 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
655 sessionId.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000656 auto sendSessionIdStatus =
657 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1,
658 std::nullopt, nullptr);
Steven Moreland826367f2021-09-10 14:05:31 -0700659 if (sendSessionIdStatus != OK) {
660 ALOGE("Could not write session ID ('%s') to socket: %s",
661 base::HexString(sessionId.data(), sessionId.size()).c_str(),
662 statusToString(sendSessionIdStatus).c_str());
663 return sendSessionIdStatus;
664 }
665 }
666
Steven Moreland4198a122021-08-03 17:37:58 -0700667 LOG_RPC_DETAIL("Socket at client: header sent");
668
669 if (incoming) {
670 return addIncomingConnection(std::move(server));
671 } else {
672 return addOutgoingConnection(std::move(server), true /*init*/);
673 }
674}
675
Steven Moreland2372f9d2021-08-05 15:42:01 -0700676status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000677 RpcMutex mutex;
678 RpcConditionVariable joinCv;
679 RpcMutexUniqueLock lock(mutex);
680 RpcMaybeThread thread;
Steven Morelandfba6f772021-07-15 22:45:09 +0000681 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
682 bool ownershipTransferred = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000683 thread = RpcMaybeThread([&]() {
684 RpcMutexUniqueLock threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700685 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000686 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
687 sp<RpcSession> session = thiz;
688 session->preJoinThreadOwnership(std::move(thread));
689
690 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700691 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000692
693 ownershipTransferred = true;
694 threadLock.unlock();
695 joinCv.notify_one();
696 // do not use & vars below
697
698 RpcSession::join(std::move(session), std::move(setupResult));
699 });
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000700 rpcJoinIfSingleThreaded(thread);
Steven Morelandfba6f772021-07-15 22:45:09 +0000701 joinCv.wait(lock, [&] { return ownershipTransferred; });
702 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700703 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000704}
705
Yifan Hong832521e2021-08-05 14:55:40 -0700706status_t RpcSession::initShutdownTrigger() {
707 // first client connection added, but setForServer not called, so
708 // initializaing for a client.
709 if (mShutdownTrigger == nullptr) {
710 mShutdownTrigger = FdTrigger::make();
711 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
712 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
713 }
714 return OK;
715}
716
Steven Moreland2372f9d2021-08-05 15:42:01 -0700717status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000718 sp<RpcConnection> connection = sp<RpcConnection>::make();
719 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000720 RpcMutexLockGuard _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700721 connection->rpcTransport = std::move(rpcTransport);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000722 connection->exclusiveTid = rpcGetThreadId();
Steven Morelanda59937e2021-10-04 17:42:30 -0700723 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000724 }
725
Steven Morelandb86e26b2021-06-12 00:35:58 +0000726 status_t status = OK;
727 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700728 status =
729 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000730 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000731
Andrei Homescuc8490872022-06-23 05:18:51 +0000732 clearConnectionTid(connection);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000733
Steven Moreland2372f9d2021-08-05 15:42:01 -0700734 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000735}
736
Steven Morelanda8b44292021-06-08 01:27:53 +0000737bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700738 const std::vector<uint8_t>& sessionId,
739 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000740 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
741 LOG_ALWAYS_FATAL_IF(server == nullptr);
742 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
743 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000744 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Andrei Homescu5e301462022-05-12 00:52:34 +0000745 LOG_ALWAYS_FATAL_IF(mCtx != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000746
747 mShutdownTrigger = FdTrigger::make();
748 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000749
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000750 mId = sessionId;
751 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000752 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700753 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000754 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000755}
756
Yifan Hong702115c2021-06-24 15:39:18 -0700757sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
758 std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000759 RpcMutexLockGuard _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700760
Yifan Hong10423062021-10-08 16:26:32 -0700761 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700762 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700763 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700764 return nullptr;
765 }
766
Steven Morelanddd67b942021-07-23 17:15:41 -0700767 // Don't accept any more connections, some have shutdown. Usually this
768 // happens when new connections are still being established as part of a
769 // very short-lived session which shuts down after it already started
770 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700771 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700772 return nullptr;
773 }
774
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000775 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700776 session->rpcTransport = std::move(rpcTransport);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000777 session->exclusiveTid = rpcGetThreadId();
Steven Morelanddd67b942021-07-23 17:15:41 -0700778
Steven Morelanda59937e2021-10-04 17:42:30 -0700779 mConnections.mIncoming.push_back(session);
780 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000781
782 return session;
783}
784
Steven Moreland19fc9f72021-06-10 03:57:30 +0000785bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000786 RpcMutexUniqueLock _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700787 if (auto it =
788 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
789 it != mConnections.mIncoming.end()) {
790 mConnections.mIncoming.erase(it);
791 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000792 sp<EventListener> listener = mEventListener.promote();
793 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700794 _l.unlock();
795 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000796 }
Steven Morelandee78e762021-05-05 21:12:51 +0000797 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000798 return true;
799 }
800 return false;
801}
802
Andrei Homescuc8490872022-06-23 05:18:51 +0000803void RpcSession::clearConnectionTid(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000804 RpcMutexUniqueLock _l(mMutex);
Andrei Homescuc8490872022-06-23 05:18:51 +0000805 connection->exclusiveTid = std::nullopt;
806 if (mConnections.mWaitingThreads > 0) {
807 _l.unlock();
808 mAvailableConnectionCv.notify_one();
809 }
810}
811
Yifan Hong9734cfc2021-09-13 16:14:09 -0700812std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700813 return mCtx->getCertificate(format);
814}
815
Steven Moreland195edb82021-06-08 02:44:39 +0000816status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
817 ExclusiveConnection* connection) {
818 connection->mSession = session;
819 connection->mConnection = nullptr;
820 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000821
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000822 uint64_t tid = rpcGetThreadId();
823 RpcMutexUniqueLock _l(session->mMutex);
Steven Moreland195edb82021-06-08 02:44:39 +0000824
Steven Morelanda59937e2021-10-04 17:42:30 -0700825 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000826 while (true) {
827 sp<RpcConnection> exclusive;
828 sp<RpcConnection> available;
829
830 // CHECK FOR DEDICATED CLIENT SOCKET
831 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000832 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700833 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
834 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000835
836 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700837 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000838 //
839 // Imagine we have more than one thread in play, and a single thread
840 // sends a synchronous, then an asynchronous command. Imagine the
841 // asynchronous command is sent on the first client connection. Then, if
842 // we naively send a synchronous command to that same connection, the
843 // thread on the far side might be busy processing the asynchronous
844 // command. So, we move to considering the second available thread
845 // for subsequent calls.
846 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700847 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
848 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000849 }
850
Steven Morelandc7d40132021-06-10 03:42:11 +0000851 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000852 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000853 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000854 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000855 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700856 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000857
858 // asynchronous calls cannot be nested, we currently allow ref count
859 // calls to be nested (so that you can use this without having extra
860 // threads). Note 'drainCommands' is used so that these ref counts can't
861 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000862 if (exclusiveIncoming != nullptr) {
863 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000864 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000865 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000866 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
867 // prefer available socket, but if we don't have one, don't
868 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000869 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000870 }
871 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000872 }
873
Steven Moreland85e067b2021-05-26 17:43:53 +0000874 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000875 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000876 connection->mConnection = exclusive;
877 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000878 break;
879 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000880 connection->mConnection = available;
881 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000882 break;
883 }
884
Steven Morelanda59937e2021-10-04 17:42:30 -0700885 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000886 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
887 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
888 "reason: %d. Incoming connections: %zu. %s.",
889 static_cast<int>(use), session->mConnections.mIncoming.size(),
890 (session->server()
891 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
892 "for the corresponding client"
893 : "This is a client session, so see RpcSession::setMaxOutgoingThreads "
894 "for this client or RpcServer::setMaxThreads for the corresponding "
895 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000896 return WOULD_BLOCK;
897 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000898
Steven Moreland85e067b2021-05-26 17:43:53 +0000899 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700900 session->mConnections.mOutgoing.size(),
901 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000902 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000903 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700904 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000905
906 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000907}
908
Andrei Homescue922b232022-04-23 03:41:09 +0000909void RpcSession::ExclusiveConnection::findConnection(uint64_t tid, sp<RpcConnection>* exclusive,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000910 sp<RpcConnection>* available,
911 std::vector<sp<RpcConnection>>& sockets,
912 size_t socketsIndexHint) {
913 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
914 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
915
916 if (*exclusive != nullptr) return; // consistent with break below
917
918 for (size_t i = 0; i < sockets.size(); i++) {
919 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
920
Steven Moreland85e067b2021-05-26 17:43:53 +0000921 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000922 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
923 *available = socket;
924 continue;
925 }
926
Steven Moreland85e067b2021-05-26 17:43:53 +0000927 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000928 // (nested transactions)
929 if (exclusive && socket->exclusiveTid == tid) {
930 *exclusive = socket;
931 break; // consistent with return above
932 }
933 }
934}
935
936RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000937 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000938 // is using this fd, and it retains the right to it. So, we don't give up
939 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000940 if (!mReentrant && mConnection != nullptr) {
Andrei Homescuc8490872022-06-23 05:18:51 +0000941 mSession->clearConnectionTid(mConnection);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000942 }
943}
944
945} // namespace android