blob: bef2ed63c7a10695cc2fc09795c5b6964d976825 [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.
Andrei Homescu024727b2022-08-24 23:54:59 +000071 return make(makeDefaultRpcTransportCtxFactory());
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
Pawan49d74cb2022-08-03 21:19:11 +0000165status_t RpcSession::setupPreconnectedClient(base::unique_fd fd,
166 std::function<unique_fd()>&& request) {
Frederick Mayle297c2772022-05-05 01:21:04 +0000167 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
Steven Moreland4198a122021-08-03 17:37:58 -0700168 if (!fd.ok()) {
169 fd = request();
Steven Moreland2372f9d2021-08-05 15:42:01 -0700170 if (!fd.ok()) return BAD_VALUE;
Steven Moreland4198a122021-08-03 17:37:58 -0700171 }
Yifan Hongb675ffe2021-08-05 16:37:17 -0700172 if (auto res = setNonBlocking(fd); !res.ok()) {
173 ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
174 return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
175 }
Pawan49d74cb2022-08-03 21:19:11 +0000176
Pawan3e0061c2022-08-26 21:08:34 +0000177 RpcTransportFd transportFd(std::move(fd));
Pawan49d74cb2022-08-03 21:19:11 +0000178 status_t status = initAndAddConnection(std::move(transportFd), sessionId, incoming);
Frederick Mayle297c2772022-05-05 01:21:04 +0000179 fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
180 return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700181 });
182}
183
Steven Moreland2372f9d2021-08-05 15:42:01 -0700184status_t RpcSession::addNullDebuggingClient() {
Yifan Hong702115c2021-06-24 15:39:18 -0700185 // Note: only works on raw sockets.
Yifan Hong832521e2021-08-05 14:55:40 -0700186 if (auto status = initShutdownTrigger(); status != OK) return status;
187
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000188 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
189
190 if (serverFd == -1) {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700191 int savedErrno = errno;
192 ALOGE("Could not connect to /dev/null: %s", strerror(savedErrno));
193 return -savedErrno;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000194 }
195
Pawan3e0061c2022-08-26 21:08:34 +0000196 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000197 auto server = mCtx->newTransport(std::move(transportFd), mShutdownTrigger.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700198 if (server == nullptr) {
199 ALOGE("Unable to set up RpcTransport");
Steven Moreland2372f9d2021-08-05 15:42:01 -0700200 return UNKNOWN_ERROR;
Yifan Hong702115c2021-06-24 15:39:18 -0700201 }
202 return addOutgoingConnection(std::move(server), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000203}
204
205sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000206 ExclusiveConnection connection;
207 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
208 ConnectionUse::CLIENT, &connection);
209 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000210 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000211}
212
Steven Moreland1be91352021-05-11 22:12:15 +0000213status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000214 ExclusiveConnection connection;
215 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
216 ConnectionUse::CLIENT, &connection);
217 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000218 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000219}
220
Steven Morelandc9d7b532021-06-04 20:57:41 +0000221bool RpcSession::shutdownAndWait(bool wait) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000222 RpcMutexUniqueLock _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000223 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000224
225 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000226
Steven Morelandc9d7b532021-06-04 20:57:41 +0000227 if (wait) {
228 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
Steven Moreland791e4662021-09-13 15:22:58 -0700229 mShutdownListener->waitForShutdown(_l, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700230
Steven Morelanda59937e2021-10-04 17:42:30 -0700231 LOG_ALWAYS_FATAL_IF(!mConnections.mThreads.empty(), "Shutdown failed");
Steven Morelandc9d7b532021-06-04 20:57:41 +0000232 }
233
234 _l.unlock();
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000235
Devin Moore66d5b7a2022-07-07 21:42:10 +0000236 if (status_t res = state()->sendObituaries(sp<RpcSession>::fromExisting(this)); res != OK) {
237 ALOGE("Failed to send obituaries as the RpcSession is shutting down: %s",
238 statusToString(res).c_str());
239 }
240
Steven Moreland27a8bc72021-09-29 16:07:41 -0700241 mRpcBinderState->clear();
Steven Morelandc9d7b532021-06-04 20:57:41 +0000242
Steven Moreland659416d2021-05-11 00:47:50 +0000243 return true;
244}
245
Steven Morelandf5174272021-05-25 00:39:28 +0000246status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000247 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000248 ExclusiveConnection connection;
249 status_t status =
250 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
251 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
252 : ConnectionUse::CLIENT,
253 &connection);
254 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000255 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000256 sp<RpcSession>::fromExisting(this), reply, flags);
257}
258
Steven Moreland4f622fe2021-09-13 17:38:09 -0700259status_t RpcSession::sendDecStrong(const BpBinder* binder) {
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000260 // target is 0 because this is used to free BpBinder objects
261 return sendDecStrongToTarget(binder->getPrivateAccessor().rpcAddress(), 0 /*target*/);
Steven Moreland4f622fe2021-09-13 17:38:09 -0700262}
263
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000264status_t RpcSession::sendDecStrongToTarget(uint64_t address, size_t target) {
Steven Moreland195edb82021-06-08 02:44:39 +0000265 ExclusiveConnection connection;
266 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
267 ConnectionUse::CLIENT_REFCOUNT, &connection);
268 if (status != OK) return status;
Steven Morelandfd1e8a02021-07-21 23:30:29 +0000269 return state()->sendDecStrongToTarget(connection.get(), sp<RpcSession>::fromExisting(this),
270 address, target);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000271}
272
273status_t RpcSession::readId() {
274 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000275 RpcMutexLockGuard _l(mMutex);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000276 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
277 }
278
Steven Moreland195edb82021-06-08 02:44:39 +0000279 ExclusiveConnection connection;
280 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
281 ConnectionUse::CLIENT, &connection);
282 if (status != OK) return status;
283
Steven Moreland826367f2021-09-10 14:05:31 -0700284 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this), &mId);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000285 if (status != OK) return status;
286
Steven Moreland826367f2021-09-10 14:05:31 -0700287 LOG_RPC_DETAIL("RpcSession %p has id %s", this,
288 base::HexString(mId.data(), mId.size()).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000289 return OK;
290}
291
Steven Morelanddd67b942021-07-23 17:15:41 -0700292void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000293 const sp<RpcSession>& session) {
294 (void)session;
Steven Moreland659416d2021-05-11 00:47:50 +0000295}
296
Steven Moreland19fc9f72021-06-10 03:57:30 +0000297void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000298 mCv.notify_all();
299}
300
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000301void RpcSession::WaitForShutdownListener::waitForShutdown(RpcMutexUniqueLock& lock,
Steven Moreland791e4662021-09-13 15:22:58 -0700302 const sp<RpcSession>& session) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700303 while (session->mConnections.mIncoming.size() > 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000304 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
Steven Moreland791e4662021-09-13 15:22:58 -0700305 ALOGE("Waiting for RpcSession to shut down (1s w/o progress): %zu incoming connections "
306 "still.",
Steven Morelanda59937e2021-10-04 17:42:30 -0700307 session->mConnections.mIncoming.size());
Steven Moreland659416d2021-05-11 00:47:50 +0000308 }
309 }
310}
311
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000312void RpcSession::preJoinThreadOwnership(RpcMaybeThread thread) {
313 LOG_ALWAYS_FATAL_IF(thread.get_id() != rpc_this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000314
Steven Morelanda63ff932021-05-12 00:03:15 +0000315 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000316 RpcMutexLockGuard _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700317 mConnections.mThreads[thread.get_id()] = std::move(thread);
Steven Morelanda63ff932021-05-12 00:03:15 +0000318 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000319}
Steven Morelanda63ff932021-05-12 00:03:15 +0000320
Yifan Hong702115c2021-06-24 15:39:18 -0700321RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(
322 std::unique_ptr<RpcTransport> rpcTransport) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000323 // must be registered to allow arbitrary client code executing commands to
324 // be able to do nested calls (we can't only read from it)
Yifan Hong702115c2021-06-24 15:39:18 -0700325 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(rpcTransport));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000326
Steven Morelanddd67b942021-07-23 17:15:41 -0700327 status_t status;
328
329 if (connection == nullptr) {
330 status = DEAD_OBJECT;
331 } else {
Steven Moreland27a8bc72021-09-29 16:07:41 -0700332 status =
333 mRpcBinderState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelanddd67b942021-07-23 17:15:41 -0700334 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000335
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000336 return PreJoinSetupResult{
337 .connection = std::move(connection),
338 .status = status,
339 };
340}
341
Yifan Hong194acf22021-06-29 18:44:56 -0700342namespace {
Andrei Homescu47f8c4f2022-04-30 01:38:24 +0000343#if !defined(__ANDROID__) || defined(__ANDROID_RECOVERY__)
Yifan Hongd258e682021-11-01 18:34:42 -0700344class JavaThreadAttacher {};
345#else
Yifan Hong194acf22021-06-29 18:44:56 -0700346// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
347// Android Runtime doesn't exist, no-op.
348class JavaThreadAttacher {
349public:
350 JavaThreadAttacher() {
351 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
352 // libbinder.
353 auto vm = getJavaVM();
354 if (vm == nullptr) return;
355
356 char threadName[16];
357 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
358 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
359 memcpy(threadName, defaultThreadName,
360 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
361 }
362 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
363 JavaVMAttachArgs args;
364 args.version = JNI_VERSION_1_2;
365 args.name = threadName;
366 args.group = nullptr;
367 JNIEnv* env;
368
369 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
370 "Cannot attach thread %s to JVM", threadName);
371 mAttached = true;
372 }
373 ~JavaThreadAttacher() {
374 if (!mAttached) return;
375 auto vm = getJavaVM();
376 LOG_ALWAYS_FATAL_IF(vm == nullptr,
377 "Unable to detach thread. No JavaVM, but it was present before!");
378
379 LOG_RPC_DETAIL("Detaching current thread from JVM");
380 if (vm->DetachCurrentThread() != JNI_OK) {
381 mAttached = false;
382 } else {
383 ALOGW("Unable to detach current thread from JVM");
384 }
385 }
386
387private:
388 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
389 bool mAttached = false;
390
391 static JavaVM* getJavaVM() {
392 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
393 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
394 if (fn == nullptr) return nullptr;
395 return fn();
396 }
397};
Yifan Hongd258e682021-11-01 18:34:42 -0700398#endif
Yifan Hong194acf22021-06-29 18:44:56 -0700399} // namespace
400
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000401void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
402 sp<RpcConnection>& connection = setupResult.connection;
403
404 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700405 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hongd258e682021-11-01 18:34:42 -0700406 [[maybe_unused]] JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000407 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000408 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000409 RpcState::CommandType::ANY);
410 if (status != OK) {
411 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
412 statusToString(status).c_str());
413 break;
414 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000415 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000416 } else {
417 ALOGE("Connection failed to init, closing with status %s",
418 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000419 }
420
Steven Moreland659416d2021-05-11 00:47:50 +0000421 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000422 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000423 RpcMutexLockGuard _l(session->mMutex);
424 auto it = session->mConnections.mThreads.find(rpc_this_thread::get_id());
Steven Morelanda59937e2021-10-04 17:42:30 -0700425 LOG_ALWAYS_FATAL_IF(it == session->mConnections.mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000426 it->second.detach();
Steven Morelanda59937e2021-10-04 17:42:30 -0700427 session->mConnections.mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000428
Steven Moreland659416d2021-05-11 00:47:50 +0000429 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000430 }
431
Steven Morelanddd67b942021-07-23 17:15:41 -0700432 // done after all cleanup, since session shutdown progresses via callbacks here
433 if (connection != nullptr) {
434 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
435 "bad state: connection object guaranteed to be in list");
436 }
437
Steven Moreland659416d2021-05-11 00:47:50 +0000438 session = nullptr;
439
440 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000441 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000442 }
443}
444
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000445sp<RpcServer> RpcSession::server() {
446 RpcServer* unsafeServer = mForServer.unsafe_get();
447 sp<RpcServer> server = mForServer.promote();
448
449 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
450 "wp<> is to avoid strong cycle only");
451 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000452}
453
Steven Moreland826367f2021-09-10 14:05:31 -0700454status_t RpcSession::setupClient(const std::function<status_t(const std::vector<uint8_t>& sessionId,
455 bool incoming)>& connectAndInit) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000456 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000457 RpcMutexLockGuard _l(mMutex);
Andrei Homescu9b58a462022-07-28 02:26:46 +0000458 LOG_ALWAYS_FATAL_IF(mStartedSetup, "Must only setup session once");
459 mStartedSetup = true;
460
461 if constexpr (!kEnableRpcThreads) {
462 LOG_ALWAYS_FATAL_IF(mMaxIncomingThreads > 0,
463 "Incoming threads are not supported on single-threaded libbinder");
464 // mMaxIncomingThreads should not change from here to its use below,
465 // since we set mStartedSetup==true and setMaxIncomingThreads checks
466 // for that
467 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000468 }
Steven Moreland27a8bc72021-09-29 16:07:41 -0700469
Yifan Hong832521e2021-08-05 14:55:40 -0700470 if (auto status = initShutdownTrigger(); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000471
Steven Moreland27a8bc72021-09-29 16:07:41 -0700472 auto oldProtocolVersion = mProtocolVersion;
473 auto cleanup = base::ScopeGuard([&] {
474 // if any threads are started, shut them down
475 (void)shutdownAndWait(true);
476
477 mShutdownListener = nullptr;
478 mEventListener.clear();
479
480 mId.clear();
481
482 mShutdownTrigger = nullptr;
483 mRpcBinderState = std::make_unique<RpcState>();
484
485 // protocol version may have been downgraded - if we reuse this object
486 // to connect to another server, force that server to request a
487 // downgrade again
488 mProtocolVersion = oldProtocolVersion;
489
Steven Morelanda59937e2021-10-04 17:42:30 -0700490 mConnections = {};
Andrei Homescu77ddf622022-08-23 00:33:15 +0000491
492 // clear mStartedSetup so that we can reuse this RpcSession
493 mStartedSetup = false;
Steven Moreland27a8bc72021-09-29 16:07:41 -0700494 });
495
Steven Moreland826367f2021-09-10 14:05:31 -0700496 if (status_t status = connectAndInit({}, false /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000497
Steven Morelandbf57bce2021-07-26 15:26:12 -0700498 {
499 ExclusiveConnection connection;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700500 if (status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
501 ConnectionUse::CLIENT, &connection);
502 status != OK)
503 return status;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700504
505 uint32_t version;
Steven Moreland2372f9d2021-08-05 15:42:01 -0700506 if (status_t status =
507 state()->readNewSessionResponse(connection.get(),
508 sp<RpcSession>::fromExisting(this), &version);
509 status != OK)
510 return status;
Andrei Homescu9b58a462022-07-28 02:26:46 +0000511 if (!setProtocolVersionInternal(version, false)) return BAD_VALUE;
Steven Morelandbf57bce2021-07-26 15:26:12 -0700512 }
513
Steven Morelanda5036f02021-06-08 02:26:57 +0000514 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000515 // instead of all at once.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000516 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000517 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700518 ALOGE("Could not get max threads after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000519 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700520 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000521 }
522
523 if (status_t status = readId(); status != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700524 ALOGE("Could not get session id after initial session setup: %s",
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000525 statusToString(status).c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700526 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000527 }
528
Yifan Hong1f44f982021-10-08 17:16:47 -0700529 size_t outgoingThreads = std::min(numThreadsAvailable, mMaxOutgoingThreads);
530 ALOGI_IF(outgoingThreads != numThreadsAvailable,
531 "Server hints client to start %zu outgoing threads, but client will only start %zu "
532 "because it is preconfigured to start at most %zu outgoing threads.",
533 numThreadsAvailable, outgoingThreads, mMaxOutgoingThreads);
534
Steven Morelanda5036f02021-06-08 02:26:57 +0000535 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000536 // instead of all at once - the other side should be responsible for setting
537 // up additional connections. We need to create at least one (unless 0 are
538 // requested to be set) in order to allow the other side to reliably make
539 // any requests at all.
540
Steven Moreland4198a122021-08-03 17:37:58 -0700541 // we've already setup one client
Yifan Hong1f44f982021-10-08 17:16:47 -0700542 LOG_RPC_DETAIL("RpcSession::setupClient() instantiating %zu outgoing (server max: %zu) and %zu "
543 "incoming threads",
544 outgoingThreads, numThreadsAvailable, mMaxIncomingThreads);
545 for (size_t i = 0; i + 1 < outgoingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700546 if (status_t status = connectAndInit(mId, false /*incoming*/); status != OK) return status;
Steven Moreland4198a122021-08-03 17:37:58 -0700547 }
548
Yifan Hong10423062021-10-08 16:26:32 -0700549 for (size_t i = 0; i < mMaxIncomingThreads; i++) {
Steven Moreland826367f2021-09-10 14:05:31 -0700550 if (status_t status = connectAndInit(mId, true /*incoming*/); status != OK) return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000551 }
552
Steven Moreland27a8bc72021-09-29 16:07:41 -0700553 cleanup.Disable();
554
Steven Moreland2372f9d2021-08-05 15:42:01 -0700555 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000556}
557
Steven Moreland2372f9d2021-08-05 15:42:01 -0700558status_t RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
Steven Moreland826367f2021-09-10 14:05:31 -0700559 return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) {
Steven Moreland4198a122021-08-03 17:37:58 -0700560 return setupOneSocketConnection(addr, sessionId, incoming);
561 });
562}
563
Steven Moreland2372f9d2021-08-05 15:42:01 -0700564status_t RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr,
Steven Moreland826367f2021-09-10 14:05:31 -0700565 const std::vector<uint8_t>& sessionId,
566 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000567 for (size_t tries = 0; tries < 5; tries++) {
568 if (tries > 0) usleep(10000);
569
Yifan Hongb675ffe2021-08-05 16:37:17 -0700570 unique_fd serverFd(TEMP_FAILURE_RETRY(
571 socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000572 if (serverFd == -1) {
573 int savedErrno = errno;
574 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
575 strerror(savedErrno));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700576 return -savedErrno;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000577 }
578
Pawan3e0061c2022-08-26 21:08:34 +0000579 RpcTransportFd transportFd(std::move(serverFd));
Pawan49d74cb2022-08-03 21:19:11 +0000580
581 if (0 != TEMP_FAILURE_RETRY(connect(transportFd.fd.get(), addr.addr(), addr.addrSize()))) {
Yifan Hong95d15e52021-08-25 17:15:15 -0700582 int connErrno = errno;
583 if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
584 // For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
585 // EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
Pawan49d74cb2022-08-03 21:19:11 +0000586 status_t pollStatus = mShutdownTrigger->triggerablePoll(transportFd, POLLOUT);
Yifan Hong95d15e52021-08-25 17:15:15 -0700587 if (pollStatus != OK) {
588 ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
589 statusToString(pollStatus).c_str());
590 return pollStatus;
591 }
592 // Set connErrno to the errno that connect() would have set if the fd were blocking.
593 socklen_t connErrnoLen = sizeof(connErrno);
Pawan49d74cb2022-08-03 21:19:11 +0000594 int ret = getsockopt(transportFd.fd.get(), SOL_SOCKET, SO_ERROR, &connErrno,
595 &connErrnoLen);
Yifan Hong95d15e52021-08-25 17:15:15 -0700596 if (ret == -1) {
597 int savedErrno = errno;
598 ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
599 "(Original error from connect() is: %s)",
600 strerror(savedErrno), strerror(connErrno));
601 return -savedErrno;
602 }
603 // Retrieved the real connErrno as if connect() was called with a blocking socket
604 // fd. Continue checking connErrno.
605 }
606 if (connErrno == ECONNRESET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000607 ALOGW("Connection reset on %s", addr.toString().c_str());
608 continue;
609 }
Yifan Hong95d15e52021-08-25 17:15:15 -0700610 // connErrno could be zero if getsockopt determines so. Hence zero-check again.
611 if (connErrno != 0) {
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700612 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
Yifan Hong95d15e52021-08-25 17:15:15 -0700613 strerror(connErrno));
614 return -connErrno;
Yifan Hongd9f8cef2021-08-05 15:17:31 -0700615 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000616 }
Pawan49d74cb2022-08-03 21:19:11 +0000617 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(),
618 transportFd.fd.get());
Yifan Hong702115c2021-06-24 15:39:18 -0700619
Pawan49d74cb2022-08-03 21:19:11 +0000620 return initAndAddConnection(std::move(transportFd), sessionId, incoming);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000621 }
622
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000623 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700624 return UNKNOWN_ERROR;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000625}
626
Pawan3e0061c2022-08-26 21:08:34 +0000627status_t RpcSession::initAndAddConnection(RpcTransportFd fd, const std::vector<uint8_t>& sessionId,
Steven Moreland2372f9d2021-08-05 15:42:01 -0700628 bool incoming) {
Yifan Hong8c950422021-08-05 17:13:55 -0700629 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
Yifan Hongecf937d2021-08-11 17:29:28 -0700630 auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
Steven Moreland4198a122021-08-03 17:37:58 -0700631 if (server == nullptr) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700632 ALOGE("%s: Unable to set up RpcTransport", __PRETTY_FUNCTION__);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700633 return UNKNOWN_ERROR;
Steven Moreland4198a122021-08-03 17:37:58 -0700634 }
635
636 LOG_RPC_DETAIL("Socket at client with RpcTransport %p", server.get());
637
Steven Moreland826367f2021-09-10 14:05:31 -0700638 if (sessionId.size() > std::numeric_limits<uint16_t>::max()) {
639 ALOGE("Session ID too big %zu", sessionId.size());
640 return BAD_VALUE;
641 }
642
Steven Moreland4198a122021-08-03 17:37:58 -0700643 RpcConnectionHeader header{
644 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
645 .options = 0,
Frederick Mayle69a0c992022-05-26 20:38:39 +0000646 .fileDescriptorTransportMode = static_cast<uint8_t>(mFileDescriptorTransportMode),
Steven Moreland826367f2021-09-10 14:05:31 -0700647 .sessionIdSize = static_cast<uint16_t>(sessionId.size()),
Steven Moreland4198a122021-08-03 17:37:58 -0700648 };
Steven Moreland4198a122021-08-03 17:37:58 -0700649
Steven Moreland826367f2021-09-10 14:05:31 -0700650 if (incoming) {
651 header.options |= RPC_CONNECTION_OPTION_INCOMING;
652 }
Steven Moreland4198a122021-08-03 17:37:58 -0700653
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000654 iovec headerIov{&header, sizeof(header)};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000655 auto sendHeaderStatus = server->interruptableWriteFully(mShutdownTrigger.get(), &headerIov, 1,
656 std::nullopt, nullptr);
Yifan Hong8c950422021-08-05 17:13:55 -0700657 if (sendHeaderStatus != OK) {
Steven Moreland4198a122021-08-03 17:37:58 -0700658 ALOGE("Could not write connection header to socket: %s",
Yifan Hong8c950422021-08-05 17:13:55 -0700659 statusToString(sendHeaderStatus).c_str());
660 return sendHeaderStatus;
Steven Moreland4198a122021-08-03 17:37:58 -0700661 }
662
Steven Moreland826367f2021-09-10 14:05:31 -0700663 if (sessionId.size() > 0) {
Andrei Homescua39e4ed2021-12-10 08:41:54 +0000664 iovec sessionIov{const_cast<void*>(static_cast<const void*>(sessionId.data())),
665 sessionId.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +0000666 auto sendSessionIdStatus =
667 server->interruptableWriteFully(mShutdownTrigger.get(), &sessionIov, 1,
668 std::nullopt, nullptr);
Steven Moreland826367f2021-09-10 14:05:31 -0700669 if (sendSessionIdStatus != OK) {
670 ALOGE("Could not write session ID ('%s') to socket: %s",
671 base::HexString(sessionId.data(), sessionId.size()).c_str(),
672 statusToString(sendSessionIdStatus).c_str());
673 return sendSessionIdStatus;
674 }
675 }
676
Steven Moreland4198a122021-08-03 17:37:58 -0700677 LOG_RPC_DETAIL("Socket at client: header sent");
678
679 if (incoming) {
680 return addIncomingConnection(std::move(server));
681 } else {
682 return addOutgoingConnection(std::move(server), true /*init*/);
683 }
684}
685
Steven Moreland2372f9d2021-08-05 15:42:01 -0700686status_t RpcSession::addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000687 RpcMutex mutex;
688 RpcConditionVariable joinCv;
689 RpcMutexUniqueLock lock(mutex);
690 RpcMaybeThread thread;
Steven Morelandfba6f772021-07-15 22:45:09 +0000691 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
692 bool ownershipTransferred = false;
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000693 thread = RpcMaybeThread([&]() {
694 RpcMutexUniqueLock threadLock(mutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700695 std::unique_ptr<RpcTransport> movedRpcTransport = std::move(rpcTransport);
Steven Morelandfba6f772021-07-15 22:45:09 +0000696 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
697 sp<RpcSession> session = thiz;
698 session->preJoinThreadOwnership(std::move(thread));
699
700 // only continue once we have a response or the connection fails
Yifan Hong702115c2021-06-24 15:39:18 -0700701 auto setupResult = session->preJoinSetup(std::move(movedRpcTransport));
Steven Morelandfba6f772021-07-15 22:45:09 +0000702
703 ownershipTransferred = true;
704 threadLock.unlock();
705 joinCv.notify_one();
706 // do not use & vars below
707
708 RpcSession::join(std::move(session), std::move(setupResult));
709 });
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000710 rpcJoinIfSingleThreaded(thread);
Steven Morelandfba6f772021-07-15 22:45:09 +0000711 joinCv.wait(lock, [&] { return ownershipTransferred; });
712 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700713 return OK;
Steven Morelandfba6f772021-07-15 22:45:09 +0000714}
715
Yifan Hong832521e2021-08-05 14:55:40 -0700716status_t RpcSession::initShutdownTrigger() {
717 // first client connection added, but setForServer not called, so
718 // initializaing for a client.
719 if (mShutdownTrigger == nullptr) {
720 mShutdownTrigger = FdTrigger::make();
721 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
722 if (mShutdownTrigger == nullptr) return INVALID_OPERATION;
723 }
724 return OK;
725}
726
Steven Moreland2372f9d2021-08-05 15:42:01 -0700727status_t RpcSession::addOutgoingConnection(std::unique_ptr<RpcTransport> rpcTransport, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000728 sp<RpcConnection> connection = sp<RpcConnection>::make();
729 {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000730 RpcMutexLockGuard _l(mMutex);
Yifan Hong702115c2021-06-24 15:39:18 -0700731 connection->rpcTransport = std::move(rpcTransport);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000732 connection->exclusiveTid = rpcGetThreadId();
Steven Morelanda59937e2021-10-04 17:42:30 -0700733 mConnections.mOutgoing.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000734 }
735
Steven Morelandb86e26b2021-06-12 00:35:58 +0000736 status_t status = OK;
737 if (init) {
Steven Morelandfc027e02021-10-25 15:31:31 -0700738 status =
739 mRpcBinderState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandb86e26b2021-06-12 00:35:58 +0000740 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000741
Andrei Homescuc8490872022-06-23 05:18:51 +0000742 clearConnectionTid(connection);
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000743
Steven Moreland2372f9d2021-08-05 15:42:01 -0700744 return status;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000745}
746
Steven Morelanda8b44292021-06-08 01:27:53 +0000747bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland51c44a92021-10-14 16:50:35 -0700748 const std::vector<uint8_t>& sessionId,
749 const sp<IBinder>& sessionSpecificRoot) {
Steven Moreland659416d2021-05-11 00:47:50 +0000750 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
751 LOG_ALWAYS_FATAL_IF(server == nullptr);
752 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
753 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000754 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Andrei Homescu5e301462022-05-12 00:52:34 +0000755 LOG_ALWAYS_FATAL_IF(mCtx != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000756
757 mShutdownTrigger = FdTrigger::make();
758 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000759
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000760 mId = sessionId;
761 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000762 mEventListener = eventListener;
Steven Moreland51c44a92021-10-14 16:50:35 -0700763 mSessionSpecificRootObject = sessionSpecificRoot;
Steven Morelanda8b44292021-06-08 01:27:53 +0000764 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000765}
766
Yifan Hong702115c2021-06-24 15:39:18 -0700767sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(
768 std::unique_ptr<RpcTransport> rpcTransport) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000769 RpcMutexLockGuard _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700770
Yifan Hong10423062021-10-08 16:26:32 -0700771 if (mConnections.mIncoming.size() >= mMaxIncomingThreads) {
Steven Moreland132d5bf2021-08-03 16:13:24 -0700772 ALOGE("Cannot add thread to session with %zu threads (max is set to %zu)",
Yifan Hong10423062021-10-08 16:26:32 -0700773 mConnections.mIncoming.size(), mMaxIncomingThreads);
Steven Moreland132d5bf2021-08-03 16:13:24 -0700774 return nullptr;
775 }
776
Steven Morelanddd67b942021-07-23 17:15:41 -0700777 // Don't accept any more connections, some have shutdown. Usually this
778 // happens when new connections are still being established as part of a
779 // very short-lived session which shuts down after it already started
780 // accepting new connections.
Steven Morelanda59937e2021-10-04 17:42:30 -0700781 if (mConnections.mIncoming.size() < mConnections.mMaxIncoming) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700782 return nullptr;
783 }
784
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000785 sp<RpcConnection> session = sp<RpcConnection>::make();
Yifan Hong702115c2021-06-24 15:39:18 -0700786 session->rpcTransport = std::move(rpcTransport);
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000787 session->exclusiveTid = rpcGetThreadId();
Steven Morelanddd67b942021-07-23 17:15:41 -0700788
Steven Morelanda59937e2021-10-04 17:42:30 -0700789 mConnections.mIncoming.push_back(session);
790 mConnections.mMaxIncoming = mConnections.mIncoming.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000791
792 return session;
793}
794
Steven Moreland19fc9f72021-06-10 03:57:30 +0000795bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000796 RpcMutexUniqueLock _l(mMutex);
Steven Morelanda59937e2021-10-04 17:42:30 -0700797 if (auto it =
798 std::find(mConnections.mIncoming.begin(), mConnections.mIncoming.end(), connection);
799 it != mConnections.mIncoming.end()) {
800 mConnections.mIncoming.erase(it);
801 if (mConnections.mIncoming.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000802 sp<EventListener> listener = mEventListener.promote();
803 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700804 _l.unlock();
805 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000806 }
Steven Morelandee78e762021-05-05 21:12:51 +0000807 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000808 return true;
809 }
810 return false;
811}
812
Andrei Homescuc8490872022-06-23 05:18:51 +0000813void RpcSession::clearConnectionTid(const sp<RpcConnection>& connection) {
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000814 RpcMutexUniqueLock _l(mMutex);
Andrei Homescuc8490872022-06-23 05:18:51 +0000815 connection->exclusiveTid = std::nullopt;
816 if (mConnections.mWaitingThreads > 0) {
817 _l.unlock();
818 mAvailableConnectionCv.notify_one();
819 }
820}
821
Yifan Hong9734cfc2021-09-13 16:14:09 -0700822std::vector<uint8_t> RpcSession::getCertificate(RpcCertificateFormat format) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700823 return mCtx->getCertificate(format);
824}
825
Steven Moreland195edb82021-06-08 02:44:39 +0000826status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
827 ExclusiveConnection* connection) {
828 connection->mSession = session;
829 connection->mConnection = nullptr;
830 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000831
Andrei Homescuffa3aaa2022-04-07 05:06:33 +0000832 uint64_t tid = rpcGetThreadId();
833 RpcMutexUniqueLock _l(session->mMutex);
Steven Moreland195edb82021-06-08 02:44:39 +0000834
Steven Morelanda59937e2021-10-04 17:42:30 -0700835 session->mConnections.mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000836 while (true) {
837 sp<RpcConnection> exclusive;
838 sp<RpcConnection> available;
839
840 // CHECK FOR DEDICATED CLIENT SOCKET
841 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000842 // A server/looper should always use a dedicated connection if available
Steven Morelanda59937e2021-10-04 17:42:30 -0700843 findConnection(tid, &exclusive, &available, session->mConnections.mOutgoing,
844 session->mConnections.mOutgoingOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000845
846 // WARNING: this assumes a server cannot request its client to send
Steven Morelanda59937e2021-10-04 17:42:30 -0700847 // a transaction, as mIncoming is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000848 //
849 // Imagine we have more than one thread in play, and a single thread
850 // sends a synchronous, then an asynchronous command. Imagine the
851 // asynchronous command is sent on the first client connection. Then, if
852 // we naively send a synchronous command to that same connection, the
853 // thread on the far side might be busy processing the asynchronous
854 // command. So, we move to considering the second available thread
855 // for subsequent calls.
856 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Morelanda59937e2021-10-04 17:42:30 -0700857 session->mConnections.mOutgoingOffset = (session->mConnections.mOutgoingOffset + 1) %
858 session->mConnections.mOutgoing.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000859 }
860
Steven Morelandc7d40132021-06-10 03:42:11 +0000861 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000862 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000863 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000864 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000865 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
Steven Morelanda59937e2021-10-04 17:42:30 -0700866 session->mConnections.mIncoming, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000867
868 // asynchronous calls cannot be nested, we currently allow ref count
869 // calls to be nested (so that you can use this without having extra
870 // threads). Note 'drainCommands' is used so that these ref counts can't
871 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000872 if (exclusiveIncoming != nullptr) {
873 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000874 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000875 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000876 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
877 // prefer available socket, but if we don't have one, don't
878 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000879 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000880 }
881 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000882 }
883
Steven Moreland85e067b2021-05-26 17:43:53 +0000884 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000885 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000886 connection->mConnection = exclusive;
887 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000888 break;
889 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000890 connection->mConnection = available;
891 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000892 break;
893 }
894
Steven Morelanda59937e2021-10-04 17:42:30 -0700895 if (session->mConnections.mOutgoing.size() == 0) {
Steven Moreland25d9cc52022-03-10 23:11:56 +0000896 ALOGE("Session has no outgoing connections. This is required for an RPC server to make "
897 "any non-nested (e.g. oneway or on another thread) calls. Use code request "
898 "reason: %d. Incoming connections: %zu. %s.",
899 static_cast<int>(use), session->mConnections.mIncoming.size(),
900 (session->server()
901 ? "This is a server session, so see RpcSession::setMaxIncomingThreads "
902 "for the corresponding client"
903 : "This is a client session, so see RpcSession::setMaxOutgoingThreads "
904 "for this client or RpcServer::setMaxThreads for the corresponding "
905 "server"));
Steven Moreland195edb82021-06-08 02:44:39 +0000906 return WOULD_BLOCK;
907 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000908
Steven Moreland85e067b2021-05-26 17:43:53 +0000909 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Morelanda59937e2021-10-04 17:42:30 -0700910 session->mConnections.mOutgoing.size(),
911 session->mConnections.mIncoming.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000912 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000913 }
Steven Morelanda59937e2021-10-04 17:42:30 -0700914 session->mConnections.mWaitingThreads--;
Steven Moreland195edb82021-06-08 02:44:39 +0000915
916 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000917}
918
Andrei Homescue922b232022-04-23 03:41:09 +0000919void RpcSession::ExclusiveConnection::findConnection(uint64_t tid, sp<RpcConnection>* exclusive,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000920 sp<RpcConnection>* available,
921 std::vector<sp<RpcConnection>>& sockets,
922 size_t socketsIndexHint) {
923 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
924 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
925
926 if (*exclusive != nullptr) return; // consistent with break below
927
928 for (size_t i = 0; i < sockets.size(); i++) {
929 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
930
Steven Moreland85e067b2021-05-26 17:43:53 +0000931 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000932 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
933 *available = socket;
934 continue;
935 }
936
Steven Moreland85e067b2021-05-26 17:43:53 +0000937 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000938 // (nested transactions)
939 if (exclusive && socket->exclusiveTid == tid) {
940 *exclusive = socket;
941 break; // consistent with return above
942 }
943 }
944}
945
946RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000947 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000948 // is using this fd, and it retains the right to it. So, we don't give up
949 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000950 if (!mReentrant && mConnection != nullptr) {
Andrei Homescuc8490872022-06-23 05:18:51 +0000951 mSession->clearConnectionTid(mConnection);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000952 }
953}
954
955} // namespace android