blob: 5fe0b0025f7bb178557f57aa089086a5f1de1b7c [file] [log] [blame]
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "RpcSession"
18
19#include <binder/RpcSession.h>
20
Yifan Hong194acf22021-06-29 18:44:56 -070021#include <dlfcn.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000022#include <inttypes.h>
Steven Moreland4ec3c432021-05-20 00:32:47 +000023#include <poll.h>
Yifan Hong194acf22021-06-29 18:44:56 -070024#include <pthread.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000025#include <unistd.h>
26
27#include <string_view>
28
Steven Moreland4ec3c432021-05-20 00:32:47 +000029#include <android-base/macros.h>
Yifan Hong194acf22021-06-29 18:44:56 -070030#include <android_runtime/vm.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000031#include <binder/Parcel.h>
Steven Morelandee78e762021-05-05 21:12:51 +000032#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000033#include <binder/Stability.h>
Yifan Hong194acf22021-06-29 18:44:56 -070034#include <jni.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000035#include <utils/String8.h>
36
37#include "RpcSocketAddress.h"
38#include "RpcState.h"
39#include "RpcWireFormat.h"
40
41#ifdef __GLIBC__
42extern "C" pid_t gettid();
43#endif
44
45namespace android {
46
47using base::unique_fd;
48
49RpcSession::RpcSession() {
50 LOG_RPC_DETAIL("RpcSession created %p", this);
51
52 mState = std::make_unique<RpcState>();
53}
54RpcSession::~RpcSession() {
55 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
56
57 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000058 LOG_ALWAYS_FATAL_IF(mIncomingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000059 "Should not be able to destroy a session with servers in use.");
60}
61
62sp<RpcSession> RpcSession::make() {
63 return sp<RpcSession>::make();
64}
65
Steven Moreland103424e2021-06-02 18:16:19 +000066void RpcSession::setMaxThreads(size_t threads) {
67 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000068 LOG_ALWAYS_FATAL_IF(!mOutgoingConnections.empty() || !mIncomingConnections.empty(),
Steven Moreland103424e2021-06-02 18:16:19 +000069 "Must set max threads before setting up connections, but has %zu client(s) "
70 "and %zu server(s)",
Steven Moreland19fc9f72021-06-10 03:57:30 +000071 mOutgoingConnections.size(), mIncomingConnections.size());
Steven Moreland103424e2021-06-02 18:16:19 +000072 mMaxThreads = threads;
73}
74
75size_t RpcSession::getMaxThreads() {
76 std::lock_guard<std::mutex> _l(mMutex);
77 return mMaxThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000078}
79
Steven Morelandbdb53ab2021-05-05 17:57:41 +000080bool RpcSession::setupUnixDomainClient(const char* path) {
81 return setupSocketClient(UnixSocketAddress(path));
82}
83
Steven Morelandbdb53ab2021-05-05 17:57:41 +000084bool RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
85 return setupSocketClient(VsockSocketAddress(cid, port));
86}
87
Steven Morelandbdb53ab2021-05-05 17:57:41 +000088bool RpcSession::setupInetClient(const char* addr, unsigned int port) {
89 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
90 if (aiStart == nullptr) return false;
91 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
92 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
93 if (setupSocketClient(socketAddress)) return true;
94 }
95 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
96 return false;
97}
98
99bool RpcSession::addNullDebuggingClient() {
100 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
101
102 if (serverFd == -1) {
103 ALOGE("Could not connect to /dev/null: %s", strerror(errno));
104 return false;
105 }
106
Steven Morelandb86e26b2021-06-12 00:35:58 +0000107 return addOutgoingConnection(std::move(serverFd), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000108}
109
110sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000111 ExclusiveConnection connection;
112 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
113 ConnectionUse::CLIENT, &connection);
114 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000115 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000116}
117
Steven Moreland1be91352021-05-11 22:12:15 +0000118status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000119 ExclusiveConnection connection;
120 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
121 ConnectionUse::CLIENT, &connection);
122 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000123 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000124}
125
Steven Morelandc9d7b532021-06-04 20:57:41 +0000126bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000127 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000128 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000129
130 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000131
Steven Morelandc9d7b532021-06-04 20:57:41 +0000132 if (wait) {
133 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
134 mShutdownListener->waitForShutdown(_l);
135 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
136 }
137
138 _l.unlock();
139 mState->clear();
140
Steven Moreland659416d2021-05-11 00:47:50 +0000141 return true;
142}
143
Steven Morelandf5174272021-05-25 00:39:28 +0000144status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000145 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000146 ExclusiveConnection connection;
147 status_t status =
148 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
149 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
150 : ConnectionUse::CLIENT,
151 &connection);
152 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000153 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000154 sp<RpcSession>::fromExisting(this), reply, flags);
155}
156
157status_t RpcSession::sendDecStrong(const RpcAddress& address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000158 ExclusiveConnection connection;
159 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
160 ConnectionUse::CLIENT_REFCOUNT, &connection);
161 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000162 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000163}
164
Steven Morelande47511f2021-05-20 00:07:41 +0000165std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
166 auto ret = std::make_unique<RpcSession::FdTrigger>();
Steven Morelanda8b44292021-06-08 01:27:53 +0000167 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) {
168 ALOGE("Could not create pipe %s", strerror(errno));
169 return nullptr;
170 }
Steven Morelande47511f2021-05-20 00:07:41 +0000171 return ret;
172}
173
174void RpcSession::FdTrigger::trigger() {
175 mWrite.reset();
176}
177
Steven Morelanda8b44292021-06-08 01:27:53 +0000178bool RpcSession::FdTrigger::isTriggered() {
179 return mWrite == -1;
180}
181
Steven Moreland798e0d12021-07-14 23:19:25 +0000182status_t RpcSession::FdTrigger::triggerablePoll(base::borrowed_fd fd, int16_t event) {
Steven Moreland4ec3c432021-05-20 00:32:47 +0000183 while (true) {
Steven Moreland441bb0e2021-07-21 22:36:32 +0000184 pollfd pfd[]{{.fd = fd.get(), .events = static_cast<int16_t>(event), .revents = 0},
Steven Moreland4ec3c432021-05-20 00:32:47 +0000185 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
186 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
187 if (ret < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000188 return -errno;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000189 }
190 if (ret == 0) {
191 continue;
192 }
193 if (pfd[1].revents & POLLHUP) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000194 return -ECANCELED;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000195 }
Steven Moreland798e0d12021-07-14 23:19:25 +0000196 return pfd[0].revents & event ? OK : DEAD_OBJECT;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000197 }
198}
199
Steven Moreland798e0d12021-07-14 23:19:25 +0000200status_t RpcSession::FdTrigger::interruptableWriteFully(base::borrowed_fd fd, const void* data,
201 size_t size) {
202 const uint8_t* buffer = reinterpret_cast<const uint8_t*>(data);
203 const uint8_t* end = buffer + size;
204
205 MAYBE_WAIT_IN_FLAKE_MODE;
206
207 status_t status;
208 while ((status = triggerablePoll(fd, POLLOUT)) == OK) {
209 ssize_t writeSize = TEMP_FAILURE_RETRY(send(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
210 if (writeSize == 0) return DEAD_OBJECT;
211
212 if (writeSize < 0) {
213 return -errno;
214 }
215 buffer += writeSize;
216 if (buffer == end) return OK;
217 }
218 return status;
219}
220
Steven Moreland2b4f3802021-05-22 01:46:27 +0000221status_t RpcSession::FdTrigger::interruptableReadFully(base::borrowed_fd fd, void* data,
222 size_t size) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000223 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
224 uint8_t* end = buffer + size;
225
Steven Morelandb8176792021-06-22 20:29:21 +0000226 MAYBE_WAIT_IN_FLAKE_MODE;
227
Steven Moreland2b4f3802021-05-22 01:46:27 +0000228 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000229 while ((status = triggerablePoll(fd, POLLIN)) == OK) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000230 ssize_t readSize = TEMP_FAILURE_RETRY(recv(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
Steven Moreland2b4f3802021-05-22 01:46:27 +0000231 if (readSize == 0) return DEAD_OBJECT; // EOF
Steven Morelanddfe3be92021-05-22 00:24:29 +0000232
Steven Moreland9d11b922021-05-20 01:22:58 +0000233 if (readSize < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000234 return -errno;
Steven Moreland9d11b922021-05-20 01:22:58 +0000235 }
236 buffer += readSize;
Steven Moreland2b4f3802021-05-22 01:46:27 +0000237 if (buffer == end) return OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000238 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000239 return status;
Steven Moreland9d11b922021-05-20 01:22:58 +0000240}
241
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000242status_t RpcSession::readId() {
243 {
244 std::lock_guard<std::mutex> _l(mMutex);
245 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
246 }
247
Steven Moreland195edb82021-06-08 02:44:39 +0000248 ExclusiveConnection connection;
249 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
250 ConnectionUse::CLIENT, &connection);
251 if (status != OK) return status;
252
Steven Moreland01a6bad2021-06-11 00:59:20 +0000253 mId = RpcAddress::zero();
254 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this),
255 &mId.value());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000256 if (status != OK) return status;
257
Steven Moreland01a6bad2021-06-11 00:59:20 +0000258 LOG_RPC_DETAIL("RpcSession %p has id %s", this, mId->toString().c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000259 return OK;
260}
261
Steven Moreland19fc9f72021-06-10 03:57:30 +0000262void RpcSession::WaitForShutdownListener::onSessionLockedAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000263 const sp<RpcSession>& session) {
264 (void)session;
265 mShutdown = true;
266}
267
Steven Moreland19fc9f72021-06-10 03:57:30 +0000268void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000269 mCv.notify_all();
270}
271
272void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
273 while (!mShutdown) {
274 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
275 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
276 }
277 }
278}
279
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000280void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000281 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000282
Steven Morelanda63ff932021-05-12 00:03:15 +0000283 {
284 std::lock_guard<std::mutex> _l(mMutex);
285 mThreads[thread.get_id()] = std::move(thread);
286 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000287}
Steven Morelanda63ff932021-05-12 00:03:15 +0000288
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000289RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(base::unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000290 // must be registered to allow arbitrary client code executing commands to
291 // be able to do nested calls (we can't only read from it)
Steven Moreland19fc9f72021-06-10 03:57:30 +0000292 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(fd));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000293
Steven Moreland5ae62562021-06-10 03:21:42 +0000294 status_t status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000295
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000296 return PreJoinSetupResult{
297 .connection = std::move(connection),
298 .status = status,
299 };
300}
301
Yifan Hong194acf22021-06-29 18:44:56 -0700302namespace {
303// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
304// Android Runtime doesn't exist, no-op.
305class JavaThreadAttacher {
306public:
307 JavaThreadAttacher() {
308 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
309 // libbinder.
310 auto vm = getJavaVM();
311 if (vm == nullptr) return;
312
313 char threadName[16];
314 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
315 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
316 memcpy(threadName, defaultThreadName,
317 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
318 }
319 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
320 JavaVMAttachArgs args;
321 args.version = JNI_VERSION_1_2;
322 args.name = threadName;
323 args.group = nullptr;
324 JNIEnv* env;
325
326 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
327 "Cannot attach thread %s to JVM", threadName);
328 mAttached = true;
329 }
330 ~JavaThreadAttacher() {
331 if (!mAttached) return;
332 auto vm = getJavaVM();
333 LOG_ALWAYS_FATAL_IF(vm == nullptr,
334 "Unable to detach thread. No JavaVM, but it was present before!");
335
336 LOG_RPC_DETAIL("Detaching current thread from JVM");
337 if (vm->DetachCurrentThread() != JNI_OK) {
338 mAttached = false;
339 } else {
340 ALOGW("Unable to detach current thread from JVM");
341 }
342 }
343
344private:
345 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
346 bool mAttached = false;
347
348 static JavaVM* getJavaVM() {
349 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
350 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
351 if (fn == nullptr) return nullptr;
352 return fn();
353 }
354};
355} // namespace
356
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000357void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
358 sp<RpcConnection>& connection = setupResult.connection;
359
360 if (setupResult.status == OK) {
Yifan Hong194acf22021-06-29 18:44:56 -0700361 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000362 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000363 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000364 RpcState::CommandType::ANY);
365 if (status != OK) {
366 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
367 statusToString(status).c_str());
368 break;
369 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000370 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000371 } else {
372 ALOGE("Connection failed to init, closing with status %s",
373 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000374 }
375
Steven Moreland19fc9f72021-06-10 03:57:30 +0000376 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000377 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000378
Steven Moreland659416d2021-05-11 00:47:50 +0000379 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000380 {
Steven Moreland659416d2021-05-11 00:47:50 +0000381 std::lock_guard<std::mutex> _l(session->mMutex);
382 auto it = session->mThreads.find(std::this_thread::get_id());
383 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000384 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000385 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000386
Steven Moreland659416d2021-05-11 00:47:50 +0000387 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000388 }
389
Steven Moreland659416d2021-05-11 00:47:50 +0000390 session = nullptr;
391
392 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000393 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000394 }
395}
396
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000397sp<RpcServer> RpcSession::server() {
398 RpcServer* unsafeServer = mForServer.unsafe_get();
399 sp<RpcServer> server = mForServer.promote();
400
401 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
402 "wp<> is to avoid strong cycle only");
403 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000404}
405
406bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
407 {
408 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000409 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000410 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000411 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000412 }
413
Steven Moreland1b304292021-07-15 22:59:34 +0000414 if (!setupOneSocketConnection(addr, RpcAddress::zero(), false /*incoming*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000415
Steven Morelanda5036f02021-06-08 02:26:57 +0000416 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000417 // instead of all at once.
418 // TODO(b/186470974): first risk of blocking
419 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000420 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000421 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
422 statusToString(status).c_str());
423 return false;
424 }
425
426 if (status_t status = readId(); status != OK) {
427 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
428 statusToString(status).c_str());
429 return false;
430 }
431
432 // we've already setup one client
433 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000434 // TODO(b/189955605): shutdown existing connections?
Steven Moreland1b304292021-07-15 22:59:34 +0000435 if (!setupOneSocketConnection(addr, mId.value(), false /*incoming*/)) return false;
Steven Moreland659416d2021-05-11 00:47:50 +0000436 }
437
Steven Morelanda5036f02021-06-08 02:26:57 +0000438 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000439 // instead of all at once - the other side should be responsible for setting
440 // up additional connections. We need to create at least one (unless 0 are
441 // requested to be set) in order to allow the other side to reliably make
442 // any requests at all.
443
Steven Moreland103424e2021-06-02 18:16:19 +0000444 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland1b304292021-07-15 22:59:34 +0000445 if (!setupOneSocketConnection(addr, mId.value(), true /*incoming*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000446 }
447
448 return true;
449}
450
Steven Moreland01a6bad2021-06-11 00:59:20 +0000451bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, const RpcAddress& id,
Steven Moreland1b304292021-07-15 22:59:34 +0000452 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000453 for (size_t tries = 0; tries < 5; tries++) {
454 if (tries > 0) usleep(10000);
455
456 unique_fd serverFd(
457 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
458 if (serverFd == -1) {
459 int savedErrno = errno;
460 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
461 strerror(savedErrno));
462 return false;
463 }
464
465 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
466 if (errno == ECONNRESET) {
467 ALOGW("Connection reset on %s", addr.toString().c_str());
468 continue;
469 }
470 int savedErrno = errno;
471 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
472 strerror(savedErrno));
473 return false;
474 }
475
Steven Moreland01a6bad2021-06-11 00:59:20 +0000476 RpcConnectionHeader header{.options = 0};
477 memcpy(&header.sessionId, &id.viewRawEmbedded(), sizeof(RpcWireAddress));
478
Steven Moreland1b304292021-07-15 22:59:34 +0000479 if (incoming) header.options |= RPC_CONNECTION_OPTION_INCOMING;
Steven Moreland659416d2021-05-11 00:47:50 +0000480
481 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000482 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000483 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000484 strerror(savedErrno));
485 return false;
486 }
487
488 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
489
Steven Moreland1b304292021-07-15 22:59:34 +0000490 if (incoming) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000491 return addIncomingConnection(std::move(serverFd));
Steven Moreland659416d2021-05-11 00:47:50 +0000492 } else {
Steven Morelandb86e26b2021-06-12 00:35:58 +0000493 return addOutgoingConnection(std::move(serverFd), true);
Steven Moreland659416d2021-05-11 00:47:50 +0000494 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000495 }
496
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000497 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
498 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000499}
500
Steven Morelandfba6f772021-07-15 22:45:09 +0000501bool RpcSession::addIncomingConnection(unique_fd fd) {
502 std::mutex mutex;
503 std::condition_variable joinCv;
504 std::unique_lock<std::mutex> lock(mutex);
505 std::thread thread;
506 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
507 bool ownershipTransferred = false;
508 thread = std::thread([&]() {
509 std::unique_lock<std::mutex> threadLock(mutex);
510 unique_fd movedFd = std::move(fd);
511 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
512 sp<RpcSession> session = thiz;
513 session->preJoinThreadOwnership(std::move(thread));
514
515 // only continue once we have a response or the connection fails
516 auto setupResult = session->preJoinSetup(std::move(movedFd));
517
518 ownershipTransferred = true;
519 threadLock.unlock();
520 joinCv.notify_one();
521 // do not use & vars below
522
523 RpcSession::join(std::move(session), std::move(setupResult));
524 });
525 joinCv.wait(lock, [&] { return ownershipTransferred; });
526 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
527 return true;
528}
529
Steven Morelandb86e26b2021-06-12 00:35:58 +0000530bool RpcSession::addOutgoingConnection(unique_fd fd, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000531 sp<RpcConnection> connection = sp<RpcConnection>::make();
532 {
533 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000534
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000535 // first client connection added, but setForServer not called, so
536 // initializaing for a client.
537 if (mShutdownTrigger == nullptr) {
538 mShutdownTrigger = FdTrigger::make();
539 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
540 if (mShutdownTrigger == nullptr) return false;
541 }
542
543 connection->fd = std::move(fd);
544 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000545 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000546 }
547
Steven Morelandb86e26b2021-06-12 00:35:58 +0000548 status_t status = OK;
549 if (init) {
550 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
551 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000552
553 {
554 std::lock_guard<std::mutex> _l(mMutex);
555 connection->exclusiveTid = std::nullopt;
556 }
557
558 return status == OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000559}
560
Steven Morelanda8b44292021-06-08 01:27:53 +0000561bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000562 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000563 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
564 LOG_ALWAYS_FATAL_IF(server == nullptr);
565 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
566 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000567 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000568
569 mShutdownTrigger = FdTrigger::make();
570 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000571
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000572 mId = sessionId;
573 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000574 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000575 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000576}
577
Steven Moreland19fc9f72021-06-10 03:57:30 +0000578sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000579 std::lock_guard<std::mutex> _l(mMutex);
580 sp<RpcConnection> session = sp<RpcConnection>::make();
581 session->fd = std::move(fd);
582 session->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000583 mIncomingConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000584
585 return session;
586}
587
Steven Moreland19fc9f72021-06-10 03:57:30 +0000588bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000589 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000590 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
591 it != mIncomingConnections.end()) {
592 mIncomingConnections.erase(it);
593 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000594 sp<EventListener> listener = mEventListener.promote();
595 if (listener) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000596 listener->onSessionLockedAllIncomingThreadsEnded(
597 sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000598 }
Steven Morelandee78e762021-05-05 21:12:51 +0000599 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000600 return true;
601 }
602 return false;
603}
604
Steven Moreland195edb82021-06-08 02:44:39 +0000605status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
606 ExclusiveConnection* connection) {
607 connection->mSession = session;
608 connection->mConnection = nullptr;
609 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000610
Steven Moreland195edb82021-06-08 02:44:39 +0000611 pid_t tid = gettid();
612 std::unique_lock<std::mutex> _l(session->mMutex);
613
614 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000615 while (true) {
616 sp<RpcConnection> exclusive;
617 sp<RpcConnection> available;
618
619 // CHECK FOR DEDICATED CLIENT SOCKET
620 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000621 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000622 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
623 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000624
625 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000626 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000627 //
628 // Imagine we have more than one thread in play, and a single thread
629 // sends a synchronous, then an asynchronous command. Imagine the
630 // asynchronous command is sent on the first client connection. Then, if
631 // we naively send a synchronous command to that same connection, the
632 // thread on the far side might be busy processing the asynchronous
633 // command. So, we move to considering the second available thread
634 // for subsequent calls.
635 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000636 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
637 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000638 }
639
Steven Morelandc7d40132021-06-10 03:42:11 +0000640 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000641 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000642 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000643 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000644 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
645 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000646
647 // asynchronous calls cannot be nested, we currently allow ref count
648 // calls to be nested (so that you can use this without having extra
649 // threads). Note 'drainCommands' is used so that these ref counts can't
650 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000651 if (exclusiveIncoming != nullptr) {
652 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000653 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000654 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000655 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
656 // prefer available socket, but if we don't have one, don't
657 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000658 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000659 }
660 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000661 }
662
Steven Moreland85e067b2021-05-26 17:43:53 +0000663 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000664 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000665 connection->mConnection = exclusive;
666 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000667 break;
668 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000669 connection->mConnection = available;
670 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000671 break;
672 }
673
Steven Moreland19fc9f72021-06-10 03:57:30 +0000674 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000675 ALOGE("Session has no client connections. This is required for an RPC server to make "
676 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
677 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000678 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000679 return WOULD_BLOCK;
680 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000681
Steven Moreland85e067b2021-05-26 17:43:53 +0000682 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000683 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000684 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000685 }
Steven Moreland195edb82021-06-08 02:44:39 +0000686 session->mWaitingThreads--;
687
688 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000689}
690
691void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
692 sp<RpcConnection>* available,
693 std::vector<sp<RpcConnection>>& sockets,
694 size_t socketsIndexHint) {
695 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
696 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
697
698 if (*exclusive != nullptr) return; // consistent with break below
699
700 for (size_t i = 0; i < sockets.size(); i++) {
701 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
702
Steven Moreland85e067b2021-05-26 17:43:53 +0000703 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000704 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
705 *available = socket;
706 continue;
707 }
708
Steven Moreland85e067b2021-05-26 17:43:53 +0000709 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000710 // (nested transactions)
711 if (exclusive && socket->exclusiveTid == tid) {
712 *exclusive = socket;
713 break; // consistent with return above
714 }
715 }
716}
717
718RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000719 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000720 // is using this fd, and it retains the right to it. So, we don't give up
721 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000722 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000723 std::unique_lock<std::mutex> _l(mSession->mMutex);
724 mConnection->exclusiveTid = std::nullopt;
725 if (mSession->mWaitingThreads > 0) {
726 _l.unlock();
727 mSession->mAvailableConnectionCv.notify_one();
728 }
729 }
730}
731
732} // namespace android