blob: 1c376518f01dc383de63ccaea4f086dbde112b0b [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);
Steven Morelanddd67b942021-07-23 17:15:41 -0700135
Steven Morelandc9d7b532021-06-04 20:57:41 +0000136 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
137 }
138
139 _l.unlock();
140 mState->clear();
141
Steven Moreland659416d2021-05-11 00:47:50 +0000142 return true;
143}
144
Steven Morelandf5174272021-05-25 00:39:28 +0000145status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000146 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000147 ExclusiveConnection connection;
148 status_t status =
149 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
150 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
151 : ConnectionUse::CLIENT,
152 &connection);
153 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000154 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000155 sp<RpcSession>::fromExisting(this), reply, flags);
156}
157
158status_t RpcSession::sendDecStrong(const RpcAddress& address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000159 ExclusiveConnection connection;
160 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
161 ConnectionUse::CLIENT_REFCOUNT, &connection);
162 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000163 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000164}
165
Steven Morelande47511f2021-05-20 00:07:41 +0000166std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
167 auto ret = std::make_unique<RpcSession::FdTrigger>();
Steven Morelanda8b44292021-06-08 01:27:53 +0000168 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) {
169 ALOGE("Could not create pipe %s", strerror(errno));
170 return nullptr;
171 }
Steven Morelande47511f2021-05-20 00:07:41 +0000172 return ret;
173}
174
175void RpcSession::FdTrigger::trigger() {
176 mWrite.reset();
177}
178
Steven Morelanda8b44292021-06-08 01:27:53 +0000179bool RpcSession::FdTrigger::isTriggered() {
180 return mWrite == -1;
181}
182
Steven Moreland798e0d12021-07-14 23:19:25 +0000183status_t RpcSession::FdTrigger::triggerablePoll(base::borrowed_fd fd, int16_t event) {
Steven Moreland4ec3c432021-05-20 00:32:47 +0000184 while (true) {
Steven Moreland441bb0e2021-07-21 22:36:32 +0000185 pollfd pfd[]{{.fd = fd.get(), .events = static_cast<int16_t>(event), .revents = 0},
Steven Moreland4ec3c432021-05-20 00:32:47 +0000186 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
187 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
188 if (ret < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000189 return -errno;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000190 }
191 if (ret == 0) {
192 continue;
193 }
194 if (pfd[1].revents & POLLHUP) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000195 return -ECANCELED;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000196 }
Steven Moreland798e0d12021-07-14 23:19:25 +0000197 return pfd[0].revents & event ? OK : DEAD_OBJECT;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000198 }
199}
200
Steven Moreland798e0d12021-07-14 23:19:25 +0000201status_t RpcSession::FdTrigger::interruptableWriteFully(base::borrowed_fd fd, const void* data,
202 size_t size) {
203 const uint8_t* buffer = reinterpret_cast<const uint8_t*>(data);
204 const uint8_t* end = buffer + size;
205
206 MAYBE_WAIT_IN_FLAKE_MODE;
207
208 status_t status;
209 while ((status = triggerablePoll(fd, POLLOUT)) == OK) {
210 ssize_t writeSize = TEMP_FAILURE_RETRY(send(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
211 if (writeSize == 0) return DEAD_OBJECT;
212
213 if (writeSize < 0) {
214 return -errno;
215 }
216 buffer += writeSize;
217 if (buffer == end) return OK;
218 }
219 return status;
220}
221
Steven Moreland2b4f3802021-05-22 01:46:27 +0000222status_t RpcSession::FdTrigger::interruptableReadFully(base::borrowed_fd fd, void* data,
223 size_t size) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000224 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
225 uint8_t* end = buffer + size;
226
Steven Morelandb8176792021-06-22 20:29:21 +0000227 MAYBE_WAIT_IN_FLAKE_MODE;
228
Steven Moreland2b4f3802021-05-22 01:46:27 +0000229 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000230 while ((status = triggerablePoll(fd, POLLIN)) == OK) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000231 ssize_t readSize = TEMP_FAILURE_RETRY(recv(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
Steven Moreland2b4f3802021-05-22 01:46:27 +0000232 if (readSize == 0) return DEAD_OBJECT; // EOF
Steven Morelanddfe3be92021-05-22 00:24:29 +0000233
Steven Moreland9d11b922021-05-20 01:22:58 +0000234 if (readSize < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000235 return -errno;
Steven Moreland9d11b922021-05-20 01:22:58 +0000236 }
237 buffer += readSize;
Steven Moreland2b4f3802021-05-22 01:46:27 +0000238 if (buffer == end) return OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000239 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000240 return status;
Steven Moreland9d11b922021-05-20 01:22:58 +0000241}
242
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000243status_t RpcSession::readId() {
244 {
245 std::lock_guard<std::mutex> _l(mMutex);
246 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
247 }
248
Steven Moreland195edb82021-06-08 02:44:39 +0000249 ExclusiveConnection connection;
250 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
251 ConnectionUse::CLIENT, &connection);
252 if (status != OK) return status;
253
Steven Moreland01a6bad2021-06-11 00:59:20 +0000254 mId = RpcAddress::zero();
255 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this),
256 &mId.value());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000257 if (status != OK) return status;
258
Steven Moreland01a6bad2021-06-11 00:59:20 +0000259 LOG_RPC_DETAIL("RpcSession %p has id %s", this, mId->toString().c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000260 return OK;
261}
262
Steven Morelanddd67b942021-07-23 17:15:41 -0700263void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000264 const sp<RpcSession>& session) {
265 (void)session;
266 mShutdown = true;
267}
268
Steven Moreland19fc9f72021-06-10 03:57:30 +0000269void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000270 mCv.notify_all();
271}
272
273void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
274 while (!mShutdown) {
275 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
276 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
277 }
278 }
279}
280
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000281void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000282 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000283
Steven Morelanda63ff932021-05-12 00:03:15 +0000284 {
285 std::lock_guard<std::mutex> _l(mMutex);
286 mThreads[thread.get_id()] = std::move(thread);
287 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000288}
Steven Morelanda63ff932021-05-12 00:03:15 +0000289
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000290RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(base::unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000291 // must be registered to allow arbitrary client code executing commands to
292 // be able to do nested calls (we can't only read from it)
Steven Moreland19fc9f72021-06-10 03:57:30 +0000293 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(fd));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000294
Steven Morelanddd67b942021-07-23 17:15:41 -0700295 status_t status;
296
297 if (connection == nullptr) {
298 status = DEAD_OBJECT;
299 } else {
300 status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
301 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000302
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000303 return PreJoinSetupResult{
304 .connection = std::move(connection),
305 .status = status,
306 };
307}
308
Yifan Hong194acf22021-06-29 18:44:56 -0700309namespace {
310// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
311// Android Runtime doesn't exist, no-op.
312class JavaThreadAttacher {
313public:
314 JavaThreadAttacher() {
315 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
316 // libbinder.
317 auto vm = getJavaVM();
318 if (vm == nullptr) return;
319
320 char threadName[16];
321 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
322 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
323 memcpy(threadName, defaultThreadName,
324 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
325 }
326 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
327 JavaVMAttachArgs args;
328 args.version = JNI_VERSION_1_2;
329 args.name = threadName;
330 args.group = nullptr;
331 JNIEnv* env;
332
333 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
334 "Cannot attach thread %s to JVM", threadName);
335 mAttached = true;
336 }
337 ~JavaThreadAttacher() {
338 if (!mAttached) return;
339 auto vm = getJavaVM();
340 LOG_ALWAYS_FATAL_IF(vm == nullptr,
341 "Unable to detach thread. No JavaVM, but it was present before!");
342
343 LOG_RPC_DETAIL("Detaching current thread from JVM");
344 if (vm->DetachCurrentThread() != JNI_OK) {
345 mAttached = false;
346 } else {
347 ALOGW("Unable to detach current thread from JVM");
348 }
349 }
350
351private:
352 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
353 bool mAttached = false;
354
355 static JavaVM* getJavaVM() {
356 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
357 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
358 if (fn == nullptr) return nullptr;
359 return fn();
360 }
361};
362} // namespace
363
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000364void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
365 sp<RpcConnection>& connection = setupResult.connection;
366
367 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700368 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hong194acf22021-06-29 18:44:56 -0700369 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000370 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000371 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000372 RpcState::CommandType::ANY);
373 if (status != OK) {
374 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
375 statusToString(status).c_str());
376 break;
377 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000378 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000379 } else {
380 ALOGE("Connection failed to init, closing with status %s",
381 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000382 }
383
Steven Moreland659416d2021-05-11 00:47:50 +0000384 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000385 {
Steven Moreland659416d2021-05-11 00:47:50 +0000386 std::lock_guard<std::mutex> _l(session->mMutex);
387 auto it = session->mThreads.find(std::this_thread::get_id());
388 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000389 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000390 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000391
Steven Moreland659416d2021-05-11 00:47:50 +0000392 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000393 }
394
Steven Morelanddd67b942021-07-23 17:15:41 -0700395 // done after all cleanup, since session shutdown progresses via callbacks here
396 if (connection != nullptr) {
397 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
398 "bad state: connection object guaranteed to be in list");
399 }
400
Steven Moreland659416d2021-05-11 00:47:50 +0000401 session = nullptr;
402
403 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000404 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000405 }
406}
407
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000408sp<RpcServer> RpcSession::server() {
409 RpcServer* unsafeServer = mForServer.unsafe_get();
410 sp<RpcServer> server = mForServer.promote();
411
412 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
413 "wp<> is to avoid strong cycle only");
414 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000415}
416
417bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
418 {
419 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000420 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000421 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000422 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000423 }
424
Steven Moreland1b304292021-07-15 22:59:34 +0000425 if (!setupOneSocketConnection(addr, RpcAddress::zero(), false /*incoming*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000426
Steven Morelanda5036f02021-06-08 02:26:57 +0000427 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000428 // instead of all at once.
429 // TODO(b/186470974): first risk of blocking
430 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000431 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000432 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
433 statusToString(status).c_str());
434 return false;
435 }
436
437 if (status_t status = readId(); status != OK) {
438 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
439 statusToString(status).c_str());
440 return false;
441 }
442
443 // we've already setup one client
444 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000445 // TODO(b/189955605): shutdown existing connections?
Steven Moreland1b304292021-07-15 22:59:34 +0000446 if (!setupOneSocketConnection(addr, mId.value(), false /*incoming*/)) return false;
Steven Moreland659416d2021-05-11 00:47:50 +0000447 }
448
Steven Morelanda5036f02021-06-08 02:26:57 +0000449 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000450 // instead of all at once - the other side should be responsible for setting
451 // up additional connections. We need to create at least one (unless 0 are
452 // requested to be set) in order to allow the other side to reliably make
453 // any requests at all.
454
Steven Moreland103424e2021-06-02 18:16:19 +0000455 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland1b304292021-07-15 22:59:34 +0000456 if (!setupOneSocketConnection(addr, mId.value(), true /*incoming*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000457 }
458
459 return true;
460}
461
Steven Moreland01a6bad2021-06-11 00:59:20 +0000462bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, const RpcAddress& id,
Steven Moreland1b304292021-07-15 22:59:34 +0000463 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000464 for (size_t tries = 0; tries < 5; tries++) {
465 if (tries > 0) usleep(10000);
466
467 unique_fd serverFd(
468 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
469 if (serverFd == -1) {
470 int savedErrno = errno;
471 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
472 strerror(savedErrno));
473 return false;
474 }
475
476 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
477 if (errno == ECONNRESET) {
478 ALOGW("Connection reset on %s", addr.toString().c_str());
479 continue;
480 }
481 int savedErrno = errno;
482 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
483 strerror(savedErrno));
484 return false;
485 }
486
Steven Moreland01a6bad2021-06-11 00:59:20 +0000487 RpcConnectionHeader header{.options = 0};
488 memcpy(&header.sessionId, &id.viewRawEmbedded(), sizeof(RpcWireAddress));
489
Steven Moreland1b304292021-07-15 22:59:34 +0000490 if (incoming) header.options |= RPC_CONNECTION_OPTION_INCOMING;
Steven Moreland659416d2021-05-11 00:47:50 +0000491
492 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000493 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000494 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000495 strerror(savedErrno));
496 return false;
497 }
498
499 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
500
Steven Moreland1b304292021-07-15 22:59:34 +0000501 if (incoming) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000502 return addIncomingConnection(std::move(serverFd));
Steven Moreland659416d2021-05-11 00:47:50 +0000503 } else {
Steven Morelandb86e26b2021-06-12 00:35:58 +0000504 return addOutgoingConnection(std::move(serverFd), true);
Steven Moreland659416d2021-05-11 00:47:50 +0000505 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000506 }
507
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000508 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
509 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000510}
511
Steven Morelandfba6f772021-07-15 22:45:09 +0000512bool RpcSession::addIncomingConnection(unique_fd fd) {
513 std::mutex mutex;
514 std::condition_variable joinCv;
515 std::unique_lock<std::mutex> lock(mutex);
516 std::thread thread;
517 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
518 bool ownershipTransferred = false;
519 thread = std::thread([&]() {
520 std::unique_lock<std::mutex> threadLock(mutex);
521 unique_fd movedFd = std::move(fd);
522 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
523 sp<RpcSession> session = thiz;
524 session->preJoinThreadOwnership(std::move(thread));
525
526 // only continue once we have a response or the connection fails
527 auto setupResult = session->preJoinSetup(std::move(movedFd));
528
529 ownershipTransferred = true;
530 threadLock.unlock();
531 joinCv.notify_one();
532 // do not use & vars below
533
534 RpcSession::join(std::move(session), std::move(setupResult));
535 });
536 joinCv.wait(lock, [&] { return ownershipTransferred; });
537 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
538 return true;
539}
540
Steven Morelandb86e26b2021-06-12 00:35:58 +0000541bool RpcSession::addOutgoingConnection(unique_fd fd, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000542 sp<RpcConnection> connection = sp<RpcConnection>::make();
543 {
544 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000545
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000546 // first client connection added, but setForServer not called, so
547 // initializaing for a client.
548 if (mShutdownTrigger == nullptr) {
549 mShutdownTrigger = FdTrigger::make();
550 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
551 if (mShutdownTrigger == nullptr) return false;
552 }
553
554 connection->fd = std::move(fd);
555 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000556 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000557 }
558
Steven Morelandb86e26b2021-06-12 00:35:58 +0000559 status_t status = OK;
560 if (init) {
561 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
562 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000563
564 {
565 std::lock_guard<std::mutex> _l(mMutex);
566 connection->exclusiveTid = std::nullopt;
567 }
568
569 return status == OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000570}
571
Steven Morelanda8b44292021-06-08 01:27:53 +0000572bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000573 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000574 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
575 LOG_ALWAYS_FATAL_IF(server == nullptr);
576 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
577 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000578 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000579
580 mShutdownTrigger = FdTrigger::make();
581 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000582
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000583 mId = sessionId;
584 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000585 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000586 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000587}
588
Steven Moreland19fc9f72021-06-10 03:57:30 +0000589sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000590 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700591
592 // Don't accept any more connections, some have shutdown. Usually this
593 // happens when new connections are still being established as part of a
594 // very short-lived session which shuts down after it already started
595 // accepting new connections.
596 if (mIncomingConnections.size() < mMaxIncomingConnections) {
597 return nullptr;
598 }
599
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000600 sp<RpcConnection> session = sp<RpcConnection>::make();
601 session->fd = std::move(fd);
602 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700603
Steven Moreland19fc9f72021-06-10 03:57:30 +0000604 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700605 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000606
607 return session;
608}
609
Steven Moreland19fc9f72021-06-10 03:57:30 +0000610bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700611 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000612 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
613 it != mIncomingConnections.end()) {
614 mIncomingConnections.erase(it);
615 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000616 sp<EventListener> listener = mEventListener.promote();
617 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700618 _l.unlock();
619 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000620 }
Steven Morelandee78e762021-05-05 21:12:51 +0000621 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000622 return true;
623 }
624 return false;
625}
626
Steven Moreland195edb82021-06-08 02:44:39 +0000627status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
628 ExclusiveConnection* connection) {
629 connection->mSession = session;
630 connection->mConnection = nullptr;
631 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000632
Steven Moreland195edb82021-06-08 02:44:39 +0000633 pid_t tid = gettid();
634 std::unique_lock<std::mutex> _l(session->mMutex);
635
636 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000637 while (true) {
638 sp<RpcConnection> exclusive;
639 sp<RpcConnection> available;
640
641 // CHECK FOR DEDICATED CLIENT SOCKET
642 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000643 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000644 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
645 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000646
647 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000648 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000649 //
650 // Imagine we have more than one thread in play, and a single thread
651 // sends a synchronous, then an asynchronous command. Imagine the
652 // asynchronous command is sent on the first client connection. Then, if
653 // we naively send a synchronous command to that same connection, the
654 // thread on the far side might be busy processing the asynchronous
655 // command. So, we move to considering the second available thread
656 // for subsequent calls.
657 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000658 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
659 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000660 }
661
Steven Morelandc7d40132021-06-10 03:42:11 +0000662 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000663 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000664 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000665 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000666 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
667 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000668
669 // asynchronous calls cannot be nested, we currently allow ref count
670 // calls to be nested (so that you can use this without having extra
671 // threads). Note 'drainCommands' is used so that these ref counts can't
672 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000673 if (exclusiveIncoming != nullptr) {
674 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000675 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000676 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000677 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
678 // prefer available socket, but if we don't have one, don't
679 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000680 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000681 }
682 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000683 }
684
Steven Moreland85e067b2021-05-26 17:43:53 +0000685 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000686 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000687 connection->mConnection = exclusive;
688 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000689 break;
690 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000691 connection->mConnection = available;
692 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000693 break;
694 }
695
Steven Moreland19fc9f72021-06-10 03:57:30 +0000696 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000697 ALOGE("Session has no client connections. This is required for an RPC server to make "
698 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
699 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000700 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000701 return WOULD_BLOCK;
702 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000703
Steven Moreland85e067b2021-05-26 17:43:53 +0000704 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000705 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000706 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000707 }
Steven Moreland195edb82021-06-08 02:44:39 +0000708 session->mWaitingThreads--;
709
710 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000711}
712
713void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
714 sp<RpcConnection>* available,
715 std::vector<sp<RpcConnection>>& sockets,
716 size_t socketsIndexHint) {
717 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
718 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
719
720 if (*exclusive != nullptr) return; // consistent with break below
721
722 for (size_t i = 0; i < sockets.size(); i++) {
723 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
724
Steven Moreland85e067b2021-05-26 17:43:53 +0000725 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000726 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
727 *available = socket;
728 continue;
729 }
730
Steven Moreland85e067b2021-05-26 17:43:53 +0000731 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000732 // (nested transactions)
733 if (exclusive && socket->exclusiveTid == tid) {
734 *exclusive = socket;
735 break; // consistent with return above
736 }
737 }
738}
739
740RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000741 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000742 // is using this fd, and it retains the right to it. So, we don't give up
743 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000744 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000745 std::unique_lock<std::mutex> _l(mSession->mMutex);
746 mConnection->exclusiveTid = std::nullopt;
747 if (mSession->mWaitingThreads > 0) {
748 _l.unlock();
749 mSession->mAvailableConnectionCv.notify_one();
750 }
751 }
752}
753
754} // namespace android