blob: 8ab2875e92667759de783e8fa87a7d22fe36b71c [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 Hong0f9c5c72021-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 Hong0f9c5c72021-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 Hong0f9c5c72021-06-29 18:44:56 -070030#include <android_runtime/threads.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>
34#include <utils/String8.h>
35
36#include "RpcSocketAddress.h"
37#include "RpcState.h"
38#include "RpcWireFormat.h"
39
40#ifdef __GLIBC__
41extern "C" pid_t gettid();
42#endif
43
44namespace android {
45
46using base::unique_fd;
47
48RpcSession::RpcSession() {
49 LOG_RPC_DETAIL("RpcSession created %p", this);
50
51 mState = std::make_unique<RpcState>();
52}
53RpcSession::~RpcSession() {
54 LOG_RPC_DETAIL("RpcSession destroyed %p", this);
55
56 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000057 LOG_ALWAYS_FATAL_IF(mIncomingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +000058 "Should not be able to destroy a session with servers in use.");
59}
60
61sp<RpcSession> RpcSession::make() {
62 return sp<RpcSession>::make();
63}
64
Steven Moreland103424e2021-06-02 18:16:19 +000065void RpcSession::setMaxThreads(size_t threads) {
66 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +000067 LOG_ALWAYS_FATAL_IF(!mOutgoingConnections.empty() || !mIncomingConnections.empty(),
Steven Moreland103424e2021-06-02 18:16:19 +000068 "Must set max threads before setting up connections, but has %zu client(s) "
69 "and %zu server(s)",
Steven Moreland19fc9f72021-06-10 03:57:30 +000070 mOutgoingConnections.size(), mIncomingConnections.size());
Steven Moreland103424e2021-06-02 18:16:19 +000071 mMaxThreads = threads;
72}
73
74size_t RpcSession::getMaxThreads() {
75 std::lock_guard<std::mutex> _l(mMutex);
76 return mMaxThreads;
Steven Moreland659416d2021-05-11 00:47:50 +000077}
78
Steven Morelandbdb53ab2021-05-05 17:57:41 +000079bool RpcSession::setupUnixDomainClient(const char* path) {
80 return setupSocketClient(UnixSocketAddress(path));
81}
82
Steven Morelandbdb53ab2021-05-05 17:57:41 +000083bool RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
84 return setupSocketClient(VsockSocketAddress(cid, port));
85}
86
Steven Morelandbdb53ab2021-05-05 17:57:41 +000087bool RpcSession::setupInetClient(const char* addr, unsigned int port) {
88 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
89 if (aiStart == nullptr) return false;
90 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
91 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
92 if (setupSocketClient(socketAddress)) return true;
93 }
94 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
95 return false;
96}
97
98bool RpcSession::addNullDebuggingClient() {
99 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
100
101 if (serverFd == -1) {
102 ALOGE("Could not connect to /dev/null: %s", strerror(errno));
103 return false;
104 }
105
Steven Morelandb86e26b2021-06-12 00:35:58 +0000106 return addOutgoingConnection(std::move(serverFd), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000107}
108
109sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000110 ExclusiveConnection connection;
111 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
112 ConnectionUse::CLIENT, &connection);
113 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000114 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000115}
116
Steven Moreland1be91352021-05-11 22:12:15 +0000117status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000118 ExclusiveConnection connection;
119 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
120 ConnectionUse::CLIENT, &connection);
121 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000122 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000123}
124
Steven Morelandc9d7b532021-06-04 20:57:41 +0000125bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000126 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000127 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000128
129 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000130
Steven Morelandc9d7b532021-06-04 20:57:41 +0000131 if (wait) {
132 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
133 mShutdownListener->waitForShutdown(_l);
134 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
135 }
136
137 _l.unlock();
138 mState->clear();
139
Steven Moreland659416d2021-05-11 00:47:50 +0000140 return true;
141}
142
Steven Morelandf5174272021-05-25 00:39:28 +0000143status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000144 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000145 ExclusiveConnection connection;
146 status_t status =
147 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
148 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
149 : ConnectionUse::CLIENT,
150 &connection);
151 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000152 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000153 sp<RpcSession>::fromExisting(this), reply, flags);
154}
155
156status_t RpcSession::sendDecStrong(const RpcAddress& address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000157 ExclusiveConnection connection;
158 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
159 ConnectionUse::CLIENT_REFCOUNT, &connection);
160 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000161 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000162}
163
Steven Morelande47511f2021-05-20 00:07:41 +0000164std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
165 auto ret = std::make_unique<RpcSession::FdTrigger>();
Steven Morelanda8b44292021-06-08 01:27:53 +0000166 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) {
167 ALOGE("Could not create pipe %s", strerror(errno));
168 return nullptr;
169 }
Steven Morelande47511f2021-05-20 00:07:41 +0000170 return ret;
171}
172
173void RpcSession::FdTrigger::trigger() {
174 mWrite.reset();
175}
176
Steven Morelanda8b44292021-06-08 01:27:53 +0000177bool RpcSession::FdTrigger::isTriggered() {
178 return mWrite == -1;
179}
180
Steven Moreland798e0d12021-07-14 23:19:25 +0000181status_t RpcSession::FdTrigger::triggerablePoll(base::borrowed_fd fd, int16_t event) {
Steven Moreland4ec3c432021-05-20 00:32:47 +0000182 while (true) {
Steven Moreland798e0d12021-07-14 23:19:25 +0000183 pollfd pfd[]{{.fd = fd.get(),
184 .events = static_cast<int16_t>(event | POLLHUP),
185 .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 Moreland19fc9f72021-06-10 03:57:30 +0000263void RpcSession::WaitForShutdownListener::onSessionLockedAllIncomingThreadsEnded(
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 Moreland5ae62562021-06-10 03:21:42 +0000295 status_t status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000296
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000297 return PreJoinSetupResult{
298 .connection = std::move(connection),
299 .status = status,
300 };
301}
302
Yifan Hong0f9c5c72021-06-29 18:44:56 -0700303namespace {
304// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
305// Android Runtime doesn't exist, no-op.
306class JavaThreadAttacher {
307public:
308 JavaThreadAttacher() {
309 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
310 // libbinder.
311 static auto attachFn = reinterpret_cast<decltype(&androidJavaAttachThread)>(
312 dlsym(RTLD_DEFAULT, "androidJavaAttachThread"));
313 if (attachFn == nullptr) return;
314
315 char buf[16];
316 const char* threadName = "UnknownRpcSessionThread"; // default thread name
317 if (0 == pthread_getname_np(pthread_self(), buf, sizeof(buf))) {
318 threadName = buf;
319 }
320 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
321 LOG_ALWAYS_FATAL_IF(!attachFn(threadName), "Cannot attach thread %s to JVM", threadName);
322 mAttached = true;
323 }
324 ~JavaThreadAttacher() {
325 if (!mAttached) return;
326 static auto detachFn = reinterpret_cast<decltype(&androidJavaDetachThread)>(
327 dlsym(RTLD_DEFAULT, "androidJavaDetachThread"));
328 LOG_ALWAYS_FATAL_IF(detachFn == nullptr,
329 "androidJavaAttachThread exists but androidJavaDetachThread doesn't");
330
331 LOG_RPC_DETAIL("Detaching current thread from JVM");
332 if (detachFn()) {
333 mAttached = false;
334 } else {
335 ALOGW("Unable to detach current thread from JVM");
336 }
337 }
338
339private:
340 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
341 bool mAttached = false;
342};
343} // namespace
344
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000345void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
346 sp<RpcConnection>& connection = setupResult.connection;
347
348 if (setupResult.status == OK) {
Yifan Hong0f9c5c72021-06-29 18:44:56 -0700349 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000350 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000351 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000352 RpcState::CommandType::ANY);
353 if (status != OK) {
354 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
355 statusToString(status).c_str());
356 break;
357 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000358 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000359 } else {
360 ALOGE("Connection failed to init, closing with status %s",
361 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000362 }
363
Steven Moreland19fc9f72021-06-10 03:57:30 +0000364 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000365 "bad state: connection object guaranteed to be in list");
Steven Morelanda63ff932021-05-12 00:03:15 +0000366
Steven Moreland659416d2021-05-11 00:47:50 +0000367 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000368 {
Steven Moreland659416d2021-05-11 00:47:50 +0000369 std::lock_guard<std::mutex> _l(session->mMutex);
370 auto it = session->mThreads.find(std::this_thread::get_id());
371 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000372 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000373 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000374
Steven Moreland659416d2021-05-11 00:47:50 +0000375 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000376 }
377
Steven Moreland659416d2021-05-11 00:47:50 +0000378 session = nullptr;
379
380 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000381 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000382 }
383}
384
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000385sp<RpcServer> RpcSession::server() {
386 RpcServer* unsafeServer = mForServer.unsafe_get();
387 sp<RpcServer> server = mForServer.promote();
388
389 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
390 "wp<> is to avoid strong cycle only");
391 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000392}
393
394bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
395 {
396 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000397 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000398 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000399 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000400 }
401
Steven Moreland01a6bad2021-06-11 00:59:20 +0000402 if (!setupOneSocketConnection(addr, RpcAddress::zero(), false /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000403
Steven Morelanda5036f02021-06-08 02:26:57 +0000404 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000405 // instead of all at once.
406 // TODO(b/186470974): first risk of blocking
407 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000408 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
410 statusToString(status).c_str());
411 return false;
412 }
413
414 if (status_t status = readId(); status != OK) {
415 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
416 statusToString(status).c_str());
417 return false;
418 }
419
420 // we've already setup one client
421 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000422 // TODO(b/189955605): shutdown existing connections?
Steven Moreland659416d2021-05-11 00:47:50 +0000423 if (!setupOneSocketConnection(addr, mId.value(), false /*reverse*/)) return false;
424 }
425
Steven Morelanda5036f02021-06-08 02:26:57 +0000426 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000427 // instead of all at once - the other side should be responsible for setting
428 // up additional connections. We need to create at least one (unless 0 are
429 // requested to be set) in order to allow the other side to reliably make
430 // any requests at all.
431
Steven Moreland103424e2021-06-02 18:16:19 +0000432 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland659416d2021-05-11 00:47:50 +0000433 if (!setupOneSocketConnection(addr, mId.value(), true /*reverse*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000434 }
435
436 return true;
437}
438
Steven Moreland01a6bad2021-06-11 00:59:20 +0000439bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, const RpcAddress& id,
440 bool reverse) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000441 for (size_t tries = 0; tries < 5; tries++) {
442 if (tries > 0) usleep(10000);
443
444 unique_fd serverFd(
445 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
446 if (serverFd == -1) {
447 int savedErrno = errno;
448 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
449 strerror(savedErrno));
450 return false;
451 }
452
453 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
454 if (errno == ECONNRESET) {
455 ALOGW("Connection reset on %s", addr.toString().c_str());
456 continue;
457 }
458 int savedErrno = errno;
459 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
460 strerror(savedErrno));
461 return false;
462 }
463
Steven Moreland01a6bad2021-06-11 00:59:20 +0000464 RpcConnectionHeader header{.options = 0};
465 memcpy(&header.sessionId, &id.viewRawEmbedded(), sizeof(RpcWireAddress));
466
Steven Moreland659416d2021-05-11 00:47:50 +0000467 if (reverse) header.options |= RPC_CONNECTION_OPTION_REVERSE;
468
469 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000470 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000471 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000472 strerror(savedErrno));
473 return false;
474 }
475
476 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
477
Steven Moreland659416d2021-05-11 00:47:50 +0000478 if (reverse) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000479 return addIncomingConnection(std::move(serverFd));
Steven Moreland659416d2021-05-11 00:47:50 +0000480 } else {
Steven Morelandb86e26b2021-06-12 00:35:58 +0000481 return addOutgoingConnection(std::move(serverFd), true);
Steven Moreland659416d2021-05-11 00:47:50 +0000482 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000483 }
484
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000485 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
486 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000487}
488
Steven Morelandfba6f772021-07-15 22:45:09 +0000489bool RpcSession::addIncomingConnection(unique_fd fd) {
490 std::mutex mutex;
491 std::condition_variable joinCv;
492 std::unique_lock<std::mutex> lock(mutex);
493 std::thread thread;
494 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
495 bool ownershipTransferred = false;
496 thread = std::thread([&]() {
497 std::unique_lock<std::mutex> threadLock(mutex);
498 unique_fd movedFd = std::move(fd);
499 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
500 sp<RpcSession> session = thiz;
501 session->preJoinThreadOwnership(std::move(thread));
502
503 // only continue once we have a response or the connection fails
504 auto setupResult = session->preJoinSetup(std::move(movedFd));
505
506 ownershipTransferred = true;
507 threadLock.unlock();
508 joinCv.notify_one();
509 // do not use & vars below
510
511 RpcSession::join(std::move(session), std::move(setupResult));
512 });
513 joinCv.wait(lock, [&] { return ownershipTransferred; });
514 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
515 return true;
516}
517
Steven Morelandb86e26b2021-06-12 00:35:58 +0000518bool RpcSession::addOutgoingConnection(unique_fd fd, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000519 sp<RpcConnection> connection = sp<RpcConnection>::make();
520 {
521 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000522
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000523 // first client connection added, but setForServer not called, so
524 // initializaing for a client.
525 if (mShutdownTrigger == nullptr) {
526 mShutdownTrigger = FdTrigger::make();
527 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
528 if (mShutdownTrigger == nullptr) return false;
529 }
530
531 connection->fd = std::move(fd);
532 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000533 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000534 }
535
Steven Morelandb86e26b2021-06-12 00:35:58 +0000536 status_t status = OK;
537 if (init) {
538 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
539 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000540
541 {
542 std::lock_guard<std::mutex> _l(mMutex);
543 connection->exclusiveTid = std::nullopt;
544 }
545
546 return status == OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000547}
548
Steven Morelanda8b44292021-06-08 01:27:53 +0000549bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000550 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000551 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
552 LOG_ALWAYS_FATAL_IF(server == nullptr);
553 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
554 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000555 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000556
557 mShutdownTrigger = FdTrigger::make();
558 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000559
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000560 mId = sessionId;
561 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000562 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000563 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000564}
565
Steven Moreland19fc9f72021-06-10 03:57:30 +0000566sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000567 std::lock_guard<std::mutex> _l(mMutex);
568 sp<RpcConnection> session = sp<RpcConnection>::make();
569 session->fd = std::move(fd);
570 session->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000571 mIncomingConnections.push_back(session);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000572
573 return session;
574}
575
Steven Moreland19fc9f72021-06-10 03:57:30 +0000576bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000577 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000578 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
579 it != mIncomingConnections.end()) {
580 mIncomingConnections.erase(it);
581 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000582 sp<EventListener> listener = mEventListener.promote();
583 if (listener) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000584 listener->onSessionLockedAllIncomingThreadsEnded(
585 sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000586 }
Steven Morelandee78e762021-05-05 21:12:51 +0000587 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000588 return true;
589 }
590 return false;
591}
592
Steven Moreland195edb82021-06-08 02:44:39 +0000593status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
594 ExclusiveConnection* connection) {
595 connection->mSession = session;
596 connection->mConnection = nullptr;
597 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000598
Steven Moreland195edb82021-06-08 02:44:39 +0000599 pid_t tid = gettid();
600 std::unique_lock<std::mutex> _l(session->mMutex);
601
602 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000603 while (true) {
604 sp<RpcConnection> exclusive;
605 sp<RpcConnection> available;
606
607 // CHECK FOR DEDICATED CLIENT SOCKET
608 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000609 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000610 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
611 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000612
613 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000614 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000615 //
616 // Imagine we have more than one thread in play, and a single thread
617 // sends a synchronous, then an asynchronous command. Imagine the
618 // asynchronous command is sent on the first client connection. Then, if
619 // we naively send a synchronous command to that same connection, the
620 // thread on the far side might be busy processing the asynchronous
621 // command. So, we move to considering the second available thread
622 // for subsequent calls.
623 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000624 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
625 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000626 }
627
Steven Morelandc7d40132021-06-10 03:42:11 +0000628 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000629 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000630 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000631 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000632 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
633 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000634
635 // asynchronous calls cannot be nested, we currently allow ref count
636 // calls to be nested (so that you can use this without having extra
637 // threads). Note 'drainCommands' is used so that these ref counts can't
638 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000639 if (exclusiveIncoming != nullptr) {
640 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000641 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000642 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000643 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
644 // prefer available socket, but if we don't have one, don't
645 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000646 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000647 }
648 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000649 }
650
Steven Moreland85e067b2021-05-26 17:43:53 +0000651 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000652 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000653 connection->mConnection = exclusive;
654 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000655 break;
656 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000657 connection->mConnection = available;
658 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000659 break;
660 }
661
Steven Moreland19fc9f72021-06-10 03:57:30 +0000662 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000663 ALOGE("Session has no client connections. This is required for an RPC server to make "
664 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
665 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000666 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000667 return WOULD_BLOCK;
668 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000669
Steven Moreland85e067b2021-05-26 17:43:53 +0000670 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000671 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000672 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000673 }
Steven Moreland195edb82021-06-08 02:44:39 +0000674 session->mWaitingThreads--;
675
676 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000677}
678
679void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
680 sp<RpcConnection>* available,
681 std::vector<sp<RpcConnection>>& sockets,
682 size_t socketsIndexHint) {
683 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
684 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
685
686 if (*exclusive != nullptr) return; // consistent with break below
687
688 for (size_t i = 0; i < sockets.size(); i++) {
689 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
690
Steven Moreland85e067b2021-05-26 17:43:53 +0000691 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000692 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
693 *available = socket;
694 continue;
695 }
696
Steven Moreland85e067b2021-05-26 17:43:53 +0000697 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000698 // (nested transactions)
699 if (exclusive && socket->exclusiveTid == tid) {
700 *exclusive = socket;
701 break; // consistent with return above
702 }
703 }
704}
705
706RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000707 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000708 // is using this fd, and it retains the right to it. So, we don't give up
709 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000710 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000711 std::unique_lock<std::mutex> _l(mSession->mMutex);
712 mConnection->exclusiveTid = std::nullopt;
713 if (mSession->mWaitingThreads > 0) {
714 _l.unlock();
715 mSession->mAvailableConnectionCv.notify_one();
716 }
717 }
718}
719
720} // namespace android