blob: 90ce4d6d3f24611b22cf1c92d87392c7d88d8b04 [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 Morelandbf57bce2021-07-26 15:26:12 -070080bool RpcSession::setProtocolVersion(uint32_t version) {
81 if (version >= RPC_WIRE_PROTOCOL_VERSION_NEXT &&
82 version != RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) {
83 ALOGE("Cannot start RPC session with version %u which is unknown (current protocol version "
84 "is %u).",
85 version, RPC_WIRE_PROTOCOL_VERSION);
86 return false;
87 }
88
89 std::lock_guard<std::mutex> _l(mMutex);
90 mProtocolVersion = version;
91 return true;
92}
93
94std::optional<uint32_t> RpcSession::getProtocolVersion() {
95 std::lock_guard<std::mutex> _l(mMutex);
96 return mProtocolVersion;
97}
98
Steven Morelandbdb53ab2021-05-05 17:57:41 +000099bool RpcSession::setupUnixDomainClient(const char* path) {
100 return setupSocketClient(UnixSocketAddress(path));
101}
102
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000103bool RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
104 return setupSocketClient(VsockSocketAddress(cid, port));
105}
106
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000107bool RpcSession::setupInetClient(const char* addr, unsigned int port) {
108 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
109 if (aiStart == nullptr) return false;
110 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
111 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
112 if (setupSocketClient(socketAddress)) return true;
113 }
114 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
115 return false;
116}
117
118bool RpcSession::addNullDebuggingClient() {
119 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
120
121 if (serverFd == -1) {
122 ALOGE("Could not connect to /dev/null: %s", strerror(errno));
123 return false;
124 }
125
Steven Morelandb86e26b2021-06-12 00:35:58 +0000126 return addOutgoingConnection(std::move(serverFd), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000127}
128
129sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000130 ExclusiveConnection connection;
131 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
132 ConnectionUse::CLIENT, &connection);
133 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000134 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000135}
136
Steven Moreland1be91352021-05-11 22:12:15 +0000137status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000138 ExclusiveConnection connection;
139 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
140 ConnectionUse::CLIENT, &connection);
141 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000142 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000143}
144
Steven Morelandc9d7b532021-06-04 20:57:41 +0000145bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000146 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000147 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000148
149 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000150
Steven Morelandc9d7b532021-06-04 20:57:41 +0000151 if (wait) {
152 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
153 mShutdownListener->waitForShutdown(_l);
Steven Morelanddd67b942021-07-23 17:15:41 -0700154
Steven Morelandc9d7b532021-06-04 20:57:41 +0000155 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
156 }
157
158 _l.unlock();
159 mState->clear();
160
Steven Moreland659416d2021-05-11 00:47:50 +0000161 return true;
162}
163
Steven Morelandf5174272021-05-25 00:39:28 +0000164status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000165 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000166 ExclusiveConnection connection;
167 status_t status =
168 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
169 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
170 : ConnectionUse::CLIENT,
171 &connection);
172 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000173 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000174 sp<RpcSession>::fromExisting(this), reply, flags);
175}
176
177status_t RpcSession::sendDecStrong(const RpcAddress& address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000178 ExclusiveConnection connection;
179 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
180 ConnectionUse::CLIENT_REFCOUNT, &connection);
181 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000182 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000183}
184
Steven Morelande47511f2021-05-20 00:07:41 +0000185std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
186 auto ret = std::make_unique<RpcSession::FdTrigger>();
Steven Morelanda8b44292021-06-08 01:27:53 +0000187 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) {
188 ALOGE("Could not create pipe %s", strerror(errno));
189 return nullptr;
190 }
Steven Morelande47511f2021-05-20 00:07:41 +0000191 return ret;
192}
193
194void RpcSession::FdTrigger::trigger() {
195 mWrite.reset();
196}
197
Steven Morelanda8b44292021-06-08 01:27:53 +0000198bool RpcSession::FdTrigger::isTriggered() {
199 return mWrite == -1;
200}
201
Steven Moreland798e0d12021-07-14 23:19:25 +0000202status_t RpcSession::FdTrigger::triggerablePoll(base::borrowed_fd fd, int16_t event) {
Steven Moreland4ec3c432021-05-20 00:32:47 +0000203 while (true) {
Steven Moreland441bb0e2021-07-21 22:36:32 +0000204 pollfd pfd[]{{.fd = fd.get(), .events = static_cast<int16_t>(event), .revents = 0},
Steven Moreland4ec3c432021-05-20 00:32:47 +0000205 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
206 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
207 if (ret < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000208 return -errno;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000209 }
210 if (ret == 0) {
211 continue;
212 }
213 if (pfd[1].revents & POLLHUP) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000214 return -ECANCELED;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000215 }
Steven Moreland798e0d12021-07-14 23:19:25 +0000216 return pfd[0].revents & event ? OK : DEAD_OBJECT;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000217 }
218}
219
Steven Moreland798e0d12021-07-14 23:19:25 +0000220status_t RpcSession::FdTrigger::interruptableWriteFully(base::borrowed_fd fd, const void* data,
221 size_t size) {
222 const uint8_t* buffer = reinterpret_cast<const uint8_t*>(data);
223 const uint8_t* end = buffer + size;
224
225 MAYBE_WAIT_IN_FLAKE_MODE;
226
227 status_t status;
228 while ((status = triggerablePoll(fd, POLLOUT)) == OK) {
229 ssize_t writeSize = TEMP_FAILURE_RETRY(send(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
230 if (writeSize == 0) return DEAD_OBJECT;
231
232 if (writeSize < 0) {
233 return -errno;
234 }
235 buffer += writeSize;
236 if (buffer == end) return OK;
237 }
238 return status;
239}
240
Steven Moreland2b4f3802021-05-22 01:46:27 +0000241status_t RpcSession::FdTrigger::interruptableReadFully(base::borrowed_fd fd, void* data,
242 size_t size) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000243 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
244 uint8_t* end = buffer + size;
245
Steven Morelandb8176792021-06-22 20:29:21 +0000246 MAYBE_WAIT_IN_FLAKE_MODE;
247
Steven Moreland2b4f3802021-05-22 01:46:27 +0000248 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000249 while ((status = triggerablePoll(fd, POLLIN)) == OK) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000250 ssize_t readSize = TEMP_FAILURE_RETRY(recv(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
Steven Moreland2b4f3802021-05-22 01:46:27 +0000251 if (readSize == 0) return DEAD_OBJECT; // EOF
Steven Morelanddfe3be92021-05-22 00:24:29 +0000252
Steven Moreland9d11b922021-05-20 01:22:58 +0000253 if (readSize < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000254 return -errno;
Steven Moreland9d11b922021-05-20 01:22:58 +0000255 }
256 buffer += readSize;
Steven Moreland2b4f3802021-05-22 01:46:27 +0000257 if (buffer == end) return OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000258 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000259 return status;
Steven Moreland9d11b922021-05-20 01:22:58 +0000260}
261
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000262status_t RpcSession::readId() {
263 {
264 std::lock_guard<std::mutex> _l(mMutex);
265 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
266 }
267
Steven Moreland195edb82021-06-08 02:44:39 +0000268 ExclusiveConnection connection;
269 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
270 ConnectionUse::CLIENT, &connection);
271 if (status != OK) return status;
272
Steven Moreland01a6bad2021-06-11 00:59:20 +0000273 mId = RpcAddress::zero();
274 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this),
275 &mId.value());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000276 if (status != OK) return status;
277
Steven Moreland01a6bad2021-06-11 00:59:20 +0000278 LOG_RPC_DETAIL("RpcSession %p has id %s", this, mId->toString().c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000279 return OK;
280}
281
Steven Morelanddd67b942021-07-23 17:15:41 -0700282void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000283 const sp<RpcSession>& session) {
284 (void)session;
285 mShutdown = true;
286}
287
Steven Moreland19fc9f72021-06-10 03:57:30 +0000288void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000289 mCv.notify_all();
290}
291
292void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
293 while (!mShutdown) {
294 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
295 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
296 }
297 }
298}
299
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000300void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000301 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000302
Steven Morelanda63ff932021-05-12 00:03:15 +0000303 {
304 std::lock_guard<std::mutex> _l(mMutex);
305 mThreads[thread.get_id()] = std::move(thread);
306 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000307}
Steven Morelanda63ff932021-05-12 00:03:15 +0000308
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000309RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(base::unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000310 // must be registered to allow arbitrary client code executing commands to
311 // be able to do nested calls (we can't only read from it)
Steven Moreland19fc9f72021-06-10 03:57:30 +0000312 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(fd));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000313
Steven Morelanddd67b942021-07-23 17:15:41 -0700314 status_t status;
315
316 if (connection == nullptr) {
317 status = DEAD_OBJECT;
318 } else {
319 status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
320 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000321
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000322 return PreJoinSetupResult{
323 .connection = std::move(connection),
324 .status = status,
325 };
326}
327
Yifan Hong194acf22021-06-29 18:44:56 -0700328namespace {
329// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
330// Android Runtime doesn't exist, no-op.
331class JavaThreadAttacher {
332public:
333 JavaThreadAttacher() {
334 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
335 // libbinder.
336 auto vm = getJavaVM();
337 if (vm == nullptr) return;
338
339 char threadName[16];
340 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
341 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
342 memcpy(threadName, defaultThreadName,
343 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
344 }
345 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
346 JavaVMAttachArgs args;
347 args.version = JNI_VERSION_1_2;
348 args.name = threadName;
349 args.group = nullptr;
350 JNIEnv* env;
351
352 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
353 "Cannot attach thread %s to JVM", threadName);
354 mAttached = true;
355 }
356 ~JavaThreadAttacher() {
357 if (!mAttached) return;
358 auto vm = getJavaVM();
359 LOG_ALWAYS_FATAL_IF(vm == nullptr,
360 "Unable to detach thread. No JavaVM, but it was present before!");
361
362 LOG_RPC_DETAIL("Detaching current thread from JVM");
363 if (vm->DetachCurrentThread() != JNI_OK) {
364 mAttached = false;
365 } else {
366 ALOGW("Unable to detach current thread from JVM");
367 }
368 }
369
370private:
371 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
372 bool mAttached = false;
373
374 static JavaVM* getJavaVM() {
375 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
376 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
377 if (fn == nullptr) return nullptr;
378 return fn();
379 }
380};
381} // namespace
382
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000383void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
384 sp<RpcConnection>& connection = setupResult.connection;
385
386 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700387 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hong194acf22021-06-29 18:44:56 -0700388 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000389 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000390 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000391 RpcState::CommandType::ANY);
392 if (status != OK) {
393 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
394 statusToString(status).c_str());
395 break;
396 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000397 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000398 } else {
399 ALOGE("Connection failed to init, closing with status %s",
400 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000401 }
402
Steven Moreland659416d2021-05-11 00:47:50 +0000403 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000404 {
Steven Moreland659416d2021-05-11 00:47:50 +0000405 std::lock_guard<std::mutex> _l(session->mMutex);
406 auto it = session->mThreads.find(std::this_thread::get_id());
407 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000408 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000409 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000410
Steven Moreland659416d2021-05-11 00:47:50 +0000411 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000412 }
413
Steven Morelanddd67b942021-07-23 17:15:41 -0700414 // done after all cleanup, since session shutdown progresses via callbacks here
415 if (connection != nullptr) {
416 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
417 "bad state: connection object guaranteed to be in list");
418 }
419
Steven Moreland659416d2021-05-11 00:47:50 +0000420 session = nullptr;
421
422 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000423 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000424 }
425}
426
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000427sp<RpcServer> RpcSession::server() {
428 RpcServer* unsafeServer = mForServer.unsafe_get();
429 sp<RpcServer> server = mForServer.promote();
430
431 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
432 "wp<> is to avoid strong cycle only");
433 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000434}
435
436bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
437 {
438 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000439 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000441 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000442 }
443
Steven Moreland1b304292021-07-15 22:59:34 +0000444 if (!setupOneSocketConnection(addr, RpcAddress::zero(), false /*incoming*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000445
Steven Morelandbf57bce2021-07-26 15:26:12 -0700446 {
447 ExclusiveConnection connection;
448 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
449 ConnectionUse::CLIENT, &connection);
450 if (status != OK) return false;
451
452 uint32_t version;
453 status = state()->readNewSessionResponse(connection.get(),
454 sp<RpcSession>::fromExisting(this), &version);
455 if (!setProtocolVersion(version)) return false;
456 }
457
Steven Morelanda5036f02021-06-08 02:26:57 +0000458 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000459 // instead of all at once.
460 // TODO(b/186470974): first risk of blocking
461 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000462 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000463 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
464 statusToString(status).c_str());
465 return false;
466 }
467
468 if (status_t status = readId(); status != OK) {
469 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
470 statusToString(status).c_str());
471 return false;
472 }
473
474 // we've already setup one client
475 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000476 // TODO(b/189955605): shutdown existing connections?
Steven Moreland1b304292021-07-15 22:59:34 +0000477 if (!setupOneSocketConnection(addr, mId.value(), false /*incoming*/)) return false;
Steven Moreland659416d2021-05-11 00:47:50 +0000478 }
479
Steven Morelanda5036f02021-06-08 02:26:57 +0000480 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000481 // instead of all at once - the other side should be responsible for setting
482 // up additional connections. We need to create at least one (unless 0 are
483 // requested to be set) in order to allow the other side to reliably make
484 // any requests at all.
485
Steven Moreland103424e2021-06-02 18:16:19 +0000486 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland1b304292021-07-15 22:59:34 +0000487 if (!setupOneSocketConnection(addr, mId.value(), true /*incoming*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000488 }
489
490 return true;
491}
492
Steven Moreland01a6bad2021-06-11 00:59:20 +0000493bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, const RpcAddress& id,
Steven Moreland1b304292021-07-15 22:59:34 +0000494 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000495 for (size_t tries = 0; tries < 5; tries++) {
496 if (tries > 0) usleep(10000);
497
498 unique_fd serverFd(
499 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
500 if (serverFd == -1) {
501 int savedErrno = errno;
502 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
503 strerror(savedErrno));
504 return false;
505 }
506
507 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
508 if (errno == ECONNRESET) {
509 ALOGW("Connection reset on %s", addr.toString().c_str());
510 continue;
511 }
512 int savedErrno = errno;
513 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
514 strerror(savedErrno));
515 return false;
516 }
517
Steven Morelandbf57bce2021-07-26 15:26:12 -0700518 RpcConnectionHeader header{
519 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
520 .options = 0,
521 };
Steven Moreland01a6bad2021-06-11 00:59:20 +0000522 memcpy(&header.sessionId, &id.viewRawEmbedded(), sizeof(RpcWireAddress));
523
Steven Moreland1b304292021-07-15 22:59:34 +0000524 if (incoming) header.options |= RPC_CONNECTION_OPTION_INCOMING;
Steven Moreland659416d2021-05-11 00:47:50 +0000525
526 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000527 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000528 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000529 strerror(savedErrno));
530 return false;
531 }
532
533 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
534
Steven Moreland1b304292021-07-15 22:59:34 +0000535 if (incoming) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000536 return addIncomingConnection(std::move(serverFd));
Steven Moreland659416d2021-05-11 00:47:50 +0000537 } else {
Steven Morelandb86e26b2021-06-12 00:35:58 +0000538 return addOutgoingConnection(std::move(serverFd), true);
Steven Moreland659416d2021-05-11 00:47:50 +0000539 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000540 }
541
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000542 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
543 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000544}
545
Steven Morelandfba6f772021-07-15 22:45:09 +0000546bool RpcSession::addIncomingConnection(unique_fd fd) {
547 std::mutex mutex;
548 std::condition_variable joinCv;
549 std::unique_lock<std::mutex> lock(mutex);
550 std::thread thread;
551 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
552 bool ownershipTransferred = false;
553 thread = std::thread([&]() {
554 std::unique_lock<std::mutex> threadLock(mutex);
555 unique_fd movedFd = std::move(fd);
556 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
557 sp<RpcSession> session = thiz;
558 session->preJoinThreadOwnership(std::move(thread));
559
560 // only continue once we have a response or the connection fails
561 auto setupResult = session->preJoinSetup(std::move(movedFd));
562
563 ownershipTransferred = true;
564 threadLock.unlock();
565 joinCv.notify_one();
566 // do not use & vars below
567
568 RpcSession::join(std::move(session), std::move(setupResult));
569 });
570 joinCv.wait(lock, [&] { return ownershipTransferred; });
571 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
572 return true;
573}
574
Steven Morelandb86e26b2021-06-12 00:35:58 +0000575bool RpcSession::addOutgoingConnection(unique_fd fd, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000576 sp<RpcConnection> connection = sp<RpcConnection>::make();
577 {
578 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000579
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000580 // first client connection added, but setForServer not called, so
581 // initializaing for a client.
582 if (mShutdownTrigger == nullptr) {
583 mShutdownTrigger = FdTrigger::make();
584 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
585 if (mShutdownTrigger == nullptr) return false;
586 }
587
588 connection->fd = std::move(fd);
589 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000590 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000591 }
592
Steven Morelandb86e26b2021-06-12 00:35:58 +0000593 status_t status = OK;
594 if (init) {
595 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
596 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000597
598 {
599 std::lock_guard<std::mutex> _l(mMutex);
600 connection->exclusiveTid = std::nullopt;
601 }
602
603 return status == OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000604}
605
Steven Morelanda8b44292021-06-08 01:27:53 +0000606bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000607 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000608 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
609 LOG_ALWAYS_FATAL_IF(server == nullptr);
610 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
611 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000612 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000613
614 mShutdownTrigger = FdTrigger::make();
615 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000616
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000617 mId = sessionId;
618 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000619 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000620 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000621}
622
Steven Moreland19fc9f72021-06-10 03:57:30 +0000623sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000624 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700625
626 // Don't accept any more connections, some have shutdown. Usually this
627 // happens when new connections are still being established as part of a
628 // very short-lived session which shuts down after it already started
629 // accepting new connections.
630 if (mIncomingConnections.size() < mMaxIncomingConnections) {
631 return nullptr;
632 }
633
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000634 sp<RpcConnection> session = sp<RpcConnection>::make();
635 session->fd = std::move(fd);
636 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700637
Steven Moreland19fc9f72021-06-10 03:57:30 +0000638 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700639 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000640
641 return session;
642}
643
Steven Moreland19fc9f72021-06-10 03:57:30 +0000644bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700645 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000646 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
647 it != mIncomingConnections.end()) {
648 mIncomingConnections.erase(it);
649 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000650 sp<EventListener> listener = mEventListener.promote();
651 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700652 _l.unlock();
653 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000654 }
Steven Morelandee78e762021-05-05 21:12:51 +0000655 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000656 return true;
657 }
658 return false;
659}
660
Steven Moreland195edb82021-06-08 02:44:39 +0000661status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
662 ExclusiveConnection* connection) {
663 connection->mSession = session;
664 connection->mConnection = nullptr;
665 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000666
Steven Moreland195edb82021-06-08 02:44:39 +0000667 pid_t tid = gettid();
668 std::unique_lock<std::mutex> _l(session->mMutex);
669
670 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000671 while (true) {
672 sp<RpcConnection> exclusive;
673 sp<RpcConnection> available;
674
675 // CHECK FOR DEDICATED CLIENT SOCKET
676 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000677 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000678 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
679 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000680
681 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000682 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000683 //
684 // Imagine we have more than one thread in play, and a single thread
685 // sends a synchronous, then an asynchronous command. Imagine the
686 // asynchronous command is sent on the first client connection. Then, if
687 // we naively send a synchronous command to that same connection, the
688 // thread on the far side might be busy processing the asynchronous
689 // command. So, we move to considering the second available thread
690 // for subsequent calls.
691 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000692 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
693 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000694 }
695
Steven Morelandc7d40132021-06-10 03:42:11 +0000696 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000697 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000698 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000699 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000700 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
701 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000702
703 // asynchronous calls cannot be nested, we currently allow ref count
704 // calls to be nested (so that you can use this without having extra
705 // threads). Note 'drainCommands' is used so that these ref counts can't
706 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000707 if (exclusiveIncoming != nullptr) {
708 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000709 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000710 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000711 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
712 // prefer available socket, but if we don't have one, don't
713 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000714 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000715 }
716 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000717 }
718
Steven Moreland85e067b2021-05-26 17:43:53 +0000719 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000720 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000721 connection->mConnection = exclusive;
722 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000723 break;
724 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000725 connection->mConnection = available;
726 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000727 break;
728 }
729
Steven Moreland19fc9f72021-06-10 03:57:30 +0000730 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000731 ALOGE("Session has no client connections. This is required for an RPC server to make "
732 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
733 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000734 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000735 return WOULD_BLOCK;
736 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000737
Steven Moreland85e067b2021-05-26 17:43:53 +0000738 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000739 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000740 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000741 }
Steven Moreland195edb82021-06-08 02:44:39 +0000742 session->mWaitingThreads--;
743
744 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000745}
746
747void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
748 sp<RpcConnection>* available,
749 std::vector<sp<RpcConnection>>& sockets,
750 size_t socketsIndexHint) {
751 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
752 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
753
754 if (*exclusive != nullptr) return; // consistent with break below
755
756 for (size_t i = 0; i < sockets.size(); i++) {
757 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
758
Steven Moreland85e067b2021-05-26 17:43:53 +0000759 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000760 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
761 *available = socket;
762 continue;
763 }
764
Steven Moreland85e067b2021-05-26 17:43:53 +0000765 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000766 // (nested transactions)
767 if (exclusive && socket->exclusiveTid == tid) {
768 *exclusive = socket;
769 break; // consistent with return above
770 }
771 }
772}
773
774RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000775 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000776 // is using this fd, and it retains the right to it. So, we don't give up
777 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000778 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000779 std::unique_lock<std::mutex> _l(mSession->mMutex);
780 mConnection->exclusiveTid = std::nullopt;
781 if (mSession->mWaitingThreads > 0) {
782 _l.unlock();
783 mSession->mAvailableConnectionCv.notify_one();
784 }
785 }
786}
787
788} // namespace android