blob: c01a03d4c67e4fc0d4d159a05747cdba76e8f73a [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 Moreland798e0d12021-07-14 23:19:25 +0000184 pollfd pfd[]{{.fd = fd.get(),
185 .events = static_cast<int16_t>(event | POLLHUP),
186 .revents = 0},
Steven Moreland4ec3c432021-05-20 00:32:47 +0000187 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
188 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
189 if (ret < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000190 return -errno;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000191 }
192 if (ret == 0) {
193 continue;
194 }
195 if (pfd[1].revents & POLLHUP) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000196 return -ECANCELED;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000197 }
Steven Moreland798e0d12021-07-14 23:19:25 +0000198 return pfd[0].revents & event ? OK : DEAD_OBJECT;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000199 }
200}
201
Steven Moreland798e0d12021-07-14 23:19:25 +0000202status_t RpcSession::FdTrigger::interruptableWriteFully(base::borrowed_fd fd, const void* data,
203 size_t size) {
204 const uint8_t* buffer = reinterpret_cast<const uint8_t*>(data);
205 const uint8_t* end = buffer + size;
206
207 MAYBE_WAIT_IN_FLAKE_MODE;
208
209 status_t status;
210 while ((status = triggerablePoll(fd, POLLOUT)) == OK) {
211 ssize_t writeSize = TEMP_FAILURE_RETRY(send(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
212 if (writeSize == 0) return DEAD_OBJECT;
213
214 if (writeSize < 0) {
215 return -errno;
216 }
217 buffer += writeSize;
218 if (buffer == end) return OK;
219 }
220 return status;
221}
222
Steven Moreland2b4f3802021-05-22 01:46:27 +0000223status_t RpcSession::FdTrigger::interruptableReadFully(base::borrowed_fd fd, void* data,
224 size_t size) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000225 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
226 uint8_t* end = buffer + size;
227
Steven Morelandb8176792021-06-22 20:29:21 +0000228 MAYBE_WAIT_IN_FLAKE_MODE;
229
Steven Moreland2b4f3802021-05-22 01:46:27 +0000230 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000231 while ((status = triggerablePoll(fd, POLLIN)) == OK) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000232 ssize_t readSize = TEMP_FAILURE_RETRY(recv(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
Steven Moreland2b4f3802021-05-22 01:46:27 +0000233 if (readSize == 0) return DEAD_OBJECT; // EOF
Steven Morelanddfe3be92021-05-22 00:24:29 +0000234
Steven Moreland9d11b922021-05-20 01:22:58 +0000235 if (readSize < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000236 return -errno;
Steven Moreland9d11b922021-05-20 01:22:58 +0000237 }
238 buffer += readSize;
Steven Moreland2b4f3802021-05-22 01:46:27 +0000239 if (buffer == end) return OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000240 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000241 return status;
Steven Moreland9d11b922021-05-20 01:22:58 +0000242}
243
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000244status_t RpcSession::readId() {
245 {
246 std::lock_guard<std::mutex> _l(mMutex);
247 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
248 }
249
Steven Moreland195edb82021-06-08 02:44:39 +0000250 ExclusiveConnection connection;
251 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
252 ConnectionUse::CLIENT, &connection);
253 if (status != OK) return status;
254
Steven Moreland01a6bad2021-06-11 00:59:20 +0000255 mId = RpcAddress::zero();
256 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this),
257 &mId.value());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000258 if (status != OK) return status;
259
Steven Moreland01a6bad2021-06-11 00:59:20 +0000260 LOG_RPC_DETAIL("RpcSession %p has id %s", this, mId->toString().c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000261 return OK;
262}
263
Steven Moreland19fc9f72021-06-10 03:57:30 +0000264void RpcSession::WaitForShutdownListener::onSessionLockedAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000265 const sp<RpcSession>& session) {
266 (void)session;
267 mShutdown = true;
268}
269
Steven Moreland19fc9f72021-06-10 03:57:30 +0000270void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000271 mCv.notify_all();
272}
273
274void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
275 while (!mShutdown) {
276 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
277 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
278 }
279 }
280}
281
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000282void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000283 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000284
Steven Morelanda63ff932021-05-12 00:03:15 +0000285 {
286 std::lock_guard<std::mutex> _l(mMutex);
287 mThreads[thread.get_id()] = std::move(thread);
288 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000289}
Steven Morelanda63ff932021-05-12 00:03:15 +0000290
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000291RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(base::unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000292 // must be registered to allow arbitrary client code executing commands to
293 // be able to do nested calls (we can't only read from it)
Steven Moreland19fc9f72021-06-10 03:57:30 +0000294 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(fd));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000295
Steven Moreland5ae62562021-06-10 03:21:42 +0000296 status_t status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000297
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000298 return PreJoinSetupResult{
299 .connection = std::move(connection),
300 .status = status,
301 };
302}
303
Yifan Hong194acf22021-06-29 18:44:56 -0700304namespace {
305// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
306// Android Runtime doesn't exist, no-op.
307class JavaThreadAttacher {
308public:
309 JavaThreadAttacher() {
310 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
311 // libbinder.
312 auto vm = getJavaVM();
313 if (vm == nullptr) return;
314
315 char threadName[16];
316 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
317 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
318 memcpy(threadName, defaultThreadName,
319 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
320 }
321 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
322 JavaVMAttachArgs args;
323 args.version = JNI_VERSION_1_2;
324 args.name = threadName;
325 args.group = nullptr;
326 JNIEnv* env;
327
328 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
329 "Cannot attach thread %s to JVM", threadName);
330 mAttached = true;
331 }
332 ~JavaThreadAttacher() {
333 if (!mAttached) return;
334 auto vm = getJavaVM();
335 LOG_ALWAYS_FATAL_IF(vm == nullptr,
336 "Unable to detach thread. No JavaVM, but it was present before!");
337
338 LOG_RPC_DETAIL("Detaching current thread from JVM");
339 if (vm->DetachCurrentThread() != JNI_OK) {
340 mAttached = false;
341 } else {
342 ALOGW("Unable to detach current thread from JVM");
343 }
344 }
345
346private:
347 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
348 bool mAttached = false;
349
350 static JavaVM* getJavaVM() {
351 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
352 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
353 if (fn == nullptr) return nullptr;
354 return fn();
355 }
356};
357} // namespace
358
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000359void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
360 sp<RpcConnection>& connection = setupResult.connection;
361
362 if (setupResult.status == OK) {
Yifan Hong194acf22021-06-29 18:44:56 -0700363 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000364 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000365 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000366 RpcState::CommandType::ANY);
367 if (status != OK) {
368 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
369 statusToString(status).c_str());
370 break;
371 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000372 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000373 } else {
374 ALOGE("Connection failed to init, closing with status %s",
375 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000376 }
377
Steven Moreland19fc9f72021-06-10 03:57:30 +0000378 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000379 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000380
Steven Moreland659416d2021-05-11 00:47:50 +0000381 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000382 {
Steven Moreland659416d2021-05-11 00:47:50 +0000383 std::lock_guard<std::mutex> _l(session->mMutex);
384 auto it = session->mThreads.find(std::this_thread::get_id());
385 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000386 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000387 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000388
Steven Moreland659416d2021-05-11 00:47:50 +0000389 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000390 }
391
Steven Moreland659416d2021-05-11 00:47:50 +0000392 session = nullptr;
393
394 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000395 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000396 }
397}
398
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000399sp<RpcServer> RpcSession::server() {
400 RpcServer* unsafeServer = mForServer.unsafe_get();
401 sp<RpcServer> server = mForServer.promote();
402
403 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
404 "wp<> is to avoid strong cycle only");
405 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000406}
407
408bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
409 {
410 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000411 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000412 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000413 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000414 }
415
Steven Moreland1b304292021-07-15 22:59:34 +0000416 if (!setupOneSocketConnection(addr, RpcAddress::zero(), false /*incoming*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000417
Steven Morelanda5036f02021-06-08 02:26:57 +0000418 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000419 // instead of all at once.
420 // TODO(b/186470974): first risk of blocking
421 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000422 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000423 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
424 statusToString(status).c_str());
425 return false;
426 }
427
428 if (status_t status = readId(); status != OK) {
429 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
430 statusToString(status).c_str());
431 return false;
432 }
433
434 // we've already setup one client
435 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000436 // TODO(b/189955605): shutdown existing connections?
Steven Moreland1b304292021-07-15 22:59:34 +0000437 if (!setupOneSocketConnection(addr, mId.value(), false /*incoming*/)) return false;
Steven Moreland659416d2021-05-11 00:47:50 +0000438 }
439
Steven Morelanda5036f02021-06-08 02:26:57 +0000440 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000441 // instead of all at once - the other side should be responsible for setting
442 // up additional connections. We need to create at least one (unless 0 are
443 // requested to be set) in order to allow the other side to reliably make
444 // any requests at all.
445
Steven Moreland103424e2021-06-02 18:16:19 +0000446 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland1b304292021-07-15 22:59:34 +0000447 if (!setupOneSocketConnection(addr, mId.value(), true /*incoming*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000448 }
449
450 return true;
451}
452
Steven Moreland01a6bad2021-06-11 00:59:20 +0000453bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, const RpcAddress& id,
Steven Moreland1b304292021-07-15 22:59:34 +0000454 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000455 for (size_t tries = 0; tries < 5; tries++) {
456 if (tries > 0) usleep(10000);
457
458 unique_fd serverFd(
459 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
460 if (serverFd == -1) {
461 int savedErrno = errno;
462 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
463 strerror(savedErrno));
464 return false;
465 }
466
467 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
468 if (errno == ECONNRESET) {
469 ALOGW("Connection reset on %s", addr.toString().c_str());
470 continue;
471 }
472 int savedErrno = errno;
473 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
474 strerror(savedErrno));
475 return false;
476 }
477
Steven Moreland01a6bad2021-06-11 00:59:20 +0000478 RpcConnectionHeader header{.options = 0};
479 memcpy(&header.sessionId, &id.viewRawEmbedded(), sizeof(RpcWireAddress));
480
Steven Moreland1b304292021-07-15 22:59:34 +0000481 if (incoming) header.options |= RPC_CONNECTION_OPTION_INCOMING;
Steven Moreland659416d2021-05-11 00:47:50 +0000482
483 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000484 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000485 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000486 strerror(savedErrno));
487 return false;
488 }
489
490 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
491
Steven Moreland1b304292021-07-15 22:59:34 +0000492 if (incoming) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000493 return addIncomingConnection(std::move(serverFd));
Steven Moreland659416d2021-05-11 00:47:50 +0000494 } else {
Steven Morelandb86e26b2021-06-12 00:35:58 +0000495 return addOutgoingConnection(std::move(serverFd), true);
Steven Moreland659416d2021-05-11 00:47:50 +0000496 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000497 }
498
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000499 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
500 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000501}
502
Steven Morelandfba6f772021-07-15 22:45:09 +0000503bool RpcSession::addIncomingConnection(unique_fd fd) {
504 std::mutex mutex;
505 std::condition_variable joinCv;
506 std::unique_lock<std::mutex> lock(mutex);
507 std::thread thread;
508 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
509 bool ownershipTransferred = false;
510 thread = std::thread([&]() {
511 std::unique_lock<std::mutex> threadLock(mutex);
512 unique_fd movedFd = std::move(fd);
513 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
514 sp<RpcSession> session = thiz;
515 session->preJoinThreadOwnership(std::move(thread));
516
517 // only continue once we have a response or the connection fails
518 auto setupResult = session->preJoinSetup(std::move(movedFd));
519
520 ownershipTransferred = true;
521 threadLock.unlock();
522 joinCv.notify_one();
523 // do not use & vars below
524
525 RpcSession::join(std::move(session), std::move(setupResult));
526 });
527 joinCv.wait(lock, [&] { return ownershipTransferred; });
528 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
529 return true;
530}
531
Steven Morelandb86e26b2021-06-12 00:35:58 +0000532bool RpcSession::addOutgoingConnection(unique_fd fd, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000533 sp<RpcConnection> connection = sp<RpcConnection>::make();
534 {
535 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000536
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000537 // first client connection added, but setForServer not called, so
538 // initializaing for a client.
539 if (mShutdownTrigger == nullptr) {
540 mShutdownTrigger = FdTrigger::make();
541 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
542 if (mShutdownTrigger == nullptr) return false;
543 }
544
545 connection->fd = std::move(fd);
546 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000547 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000548 }
549
Steven Morelandb86e26b2021-06-12 00:35:58 +0000550 status_t status = OK;
551 if (init) {
552 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
553 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000554
555 {
556 std::lock_guard<std::mutex> _l(mMutex);
557 connection->exclusiveTid = std::nullopt;
558 }
559
560 return status == OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000561}
562
Steven Morelanda8b44292021-06-08 01:27:53 +0000563bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000564 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000565 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
566 LOG_ALWAYS_FATAL_IF(server == nullptr);
567 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
568 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000569 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000570
571 mShutdownTrigger = FdTrigger::make();
572 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000573
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000574 mId = sessionId;
575 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000576 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000577 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000578}
579
Steven Moreland19fc9f72021-06-10 03:57:30 +0000580sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000581 std::lock_guard<std::mutex> _l(mMutex);
582 sp<RpcConnection> session = sp<RpcConnection>::make();
583 session->fd = std::move(fd);
584 session->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000585 mIncomingConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000586
587 return session;
588}
589
Steven Moreland19fc9f72021-06-10 03:57:30 +0000590bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000591 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000592 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
593 it != mIncomingConnections.end()) {
594 mIncomingConnections.erase(it);
595 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000596 sp<EventListener> listener = mEventListener.promote();
597 if (listener) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000598 listener->onSessionLockedAllIncomingThreadsEnded(
599 sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000600 }
Steven Morelandee78e762021-05-05 21:12:51 +0000601 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000602 return true;
603 }
604 return false;
605}
606
Steven Moreland195edb82021-06-08 02:44:39 +0000607status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
608 ExclusiveConnection* connection) {
609 connection->mSession = session;
610 connection->mConnection = nullptr;
611 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000612
Steven Moreland195edb82021-06-08 02:44:39 +0000613 pid_t tid = gettid();
614 std::unique_lock<std::mutex> _l(session->mMutex);
615
616 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000617 while (true) {
618 sp<RpcConnection> exclusive;
619 sp<RpcConnection> available;
620
621 // CHECK FOR DEDICATED CLIENT SOCKET
622 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000623 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000624 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
625 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000626
627 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000628 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000629 //
630 // Imagine we have more than one thread in play, and a single thread
631 // sends a synchronous, then an asynchronous command. Imagine the
632 // asynchronous command is sent on the first client connection. Then, if
633 // we naively send a synchronous command to that same connection, the
634 // thread on the far side might be busy processing the asynchronous
635 // command. So, we move to considering the second available thread
636 // for subsequent calls.
637 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000638 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
639 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000640 }
641
Steven Morelandc7d40132021-06-10 03:42:11 +0000642 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000643 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000644 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000645 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000646 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
647 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000648
649 // asynchronous calls cannot be nested, we currently allow ref count
650 // calls to be nested (so that you can use this without having extra
651 // threads). Note 'drainCommands' is used so that these ref counts can't
652 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000653 if (exclusiveIncoming != nullptr) {
654 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000655 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000656 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000657 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
658 // prefer available socket, but if we don't have one, don't
659 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000660 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000661 }
662 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000663 }
664
Steven Moreland85e067b2021-05-26 17:43:53 +0000665 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000666 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000667 connection->mConnection = exclusive;
668 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000669 break;
670 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000671 connection->mConnection = available;
672 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000673 break;
674 }
675
Steven Moreland19fc9f72021-06-10 03:57:30 +0000676 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000677 ALOGE("Session has no client connections. This is required for an RPC server to make "
678 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
679 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000680 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000681 return WOULD_BLOCK;
682 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000683
Steven Moreland85e067b2021-05-26 17:43:53 +0000684 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000685 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000686 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000687 }
Steven Moreland195edb82021-06-08 02:44:39 +0000688 session->mWaitingThreads--;
689
690 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000691}
692
693void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
694 sp<RpcConnection>* available,
695 std::vector<sp<RpcConnection>>& sockets,
696 size_t socketsIndexHint) {
697 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
698 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
699
700 if (*exclusive != nullptr) return; // consistent with break below
701
702 for (size_t i = 0; i < sockets.size(); i++) {
703 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
704
Steven Moreland85e067b2021-05-26 17:43:53 +0000705 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000706 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
707 *available = socket;
708 continue;
709 }
710
Steven Moreland85e067b2021-05-26 17:43:53 +0000711 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000712 // (nested transactions)
713 if (exclusive && socket->exclusiveTid == tid) {
714 *exclusive = socket;
715 break; // consistent with return above
716 }
717 }
718}
719
720RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000721 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000722 // is using this fd, and it retains the right to it. So, we don't give up
723 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000724 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000725 std::unique_lock<std::mutex> _l(mSession->mMutex);
726 mConnection->exclusiveTid = std::nullopt;
727 if (mSession->mWaitingThreads > 0) {
728 _l.unlock();
729 mSession->mAvailableConnectionCv.notify_one();
730 }
731 }
732}
733
734} // namespace android