blob: 254b99c29a1006b5e5f4abe4e4e07ffc7a1b7aee [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);
Steven Moreland40b736e2021-07-30 14:37:10 -070090 if (mProtocolVersion && version > *mProtocolVersion) {
91 ALOGE("Cannot upgrade explicitly capped protocol version %u to newer version %u",
92 *mProtocolVersion, version);
93 return false;
94 }
95
Steven Morelandbf57bce2021-07-26 15:26:12 -070096 mProtocolVersion = version;
97 return true;
98}
99
100std::optional<uint32_t> RpcSession::getProtocolVersion() {
101 std::lock_guard<std::mutex> _l(mMutex);
102 return mProtocolVersion;
103}
104
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000105bool RpcSession::setupUnixDomainClient(const char* path) {
106 return setupSocketClient(UnixSocketAddress(path));
107}
108
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000109bool RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
110 return setupSocketClient(VsockSocketAddress(cid, port));
111}
112
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000113bool RpcSession::setupInetClient(const char* addr, unsigned int port) {
114 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
115 if (aiStart == nullptr) return false;
116 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
117 InetSocketAddress socketAddress(ai->ai_addr, ai->ai_addrlen, addr, port);
118 if (setupSocketClient(socketAddress)) return true;
119 }
120 ALOGE("None of the socket address resolved for %s:%u can be added as inet client.", addr, port);
121 return false;
122}
123
124bool RpcSession::addNullDebuggingClient() {
125 unique_fd serverFd(TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY | O_CLOEXEC)));
126
127 if (serverFd == -1) {
128 ALOGE("Could not connect to /dev/null: %s", strerror(errno));
129 return false;
130 }
131
Steven Morelandb86e26b2021-06-12 00:35:58 +0000132 return addOutgoingConnection(std::move(serverFd), false);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000133}
134
135sp<IBinder> RpcSession::getRootObject() {
Steven Moreland195edb82021-06-08 02:44:39 +0000136 ExclusiveConnection connection;
137 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
138 ConnectionUse::CLIENT, &connection);
139 if (status != OK) return nullptr;
Steven Moreland5ae62562021-06-10 03:21:42 +0000140 return state()->getRootObject(connection.get(), sp<RpcSession>::fromExisting(this));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000141}
142
Steven Moreland1be91352021-05-11 22:12:15 +0000143status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
Steven Moreland195edb82021-06-08 02:44:39 +0000144 ExclusiveConnection connection;
145 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
146 ConnectionUse::CLIENT, &connection);
147 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000148 return state()->getMaxThreads(connection.get(), sp<RpcSession>::fromExisting(this), maxThreads);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000149}
150
Steven Morelandc9d7b532021-06-04 20:57:41 +0000151bool RpcSession::shutdownAndWait(bool wait) {
Steven Moreland659416d2021-05-11 00:47:50 +0000152 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000153 LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr, "Shutdown trigger not installed");
Steven Moreland659416d2021-05-11 00:47:50 +0000154
155 mShutdownTrigger->trigger();
Steven Moreland659416d2021-05-11 00:47:50 +0000156
Steven Morelandc9d7b532021-06-04 20:57:41 +0000157 if (wait) {
158 LOG_ALWAYS_FATAL_IF(mShutdownListener == nullptr, "Shutdown listener not installed");
159 mShutdownListener->waitForShutdown(_l);
Steven Morelanddd67b942021-07-23 17:15:41 -0700160
Steven Morelandc9d7b532021-06-04 20:57:41 +0000161 LOG_ALWAYS_FATAL_IF(!mThreads.empty(), "Shutdown failed");
162 }
163
164 _l.unlock();
165 mState->clear();
166
Steven Moreland659416d2021-05-11 00:47:50 +0000167 return true;
168}
169
Steven Morelandf5174272021-05-25 00:39:28 +0000170status_t RpcSession::transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000171 Parcel* reply, uint32_t flags) {
Steven Moreland195edb82021-06-08 02:44:39 +0000172 ExclusiveConnection connection;
173 status_t status =
174 ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
175 (flags & IBinder::FLAG_ONEWAY) ? ConnectionUse::CLIENT_ASYNC
176 : ConnectionUse::CLIENT,
177 &connection);
178 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000179 return state()->transact(connection.get(), binder, code, data,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000180 sp<RpcSession>::fromExisting(this), reply, flags);
181}
182
183status_t RpcSession::sendDecStrong(const RpcAddress& address) {
Steven Moreland195edb82021-06-08 02:44:39 +0000184 ExclusiveConnection connection;
185 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
186 ConnectionUse::CLIENT_REFCOUNT, &connection);
187 if (status != OK) return status;
Steven Moreland5ae62562021-06-10 03:21:42 +0000188 return state()->sendDecStrong(connection.get(), sp<RpcSession>::fromExisting(this), address);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000189}
190
Steven Morelande47511f2021-05-20 00:07:41 +0000191std::unique_ptr<RpcSession::FdTrigger> RpcSession::FdTrigger::make() {
192 auto ret = std::make_unique<RpcSession::FdTrigger>();
Steven Morelanda8b44292021-06-08 01:27:53 +0000193 if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) {
194 ALOGE("Could not create pipe %s", strerror(errno));
195 return nullptr;
196 }
Steven Morelande47511f2021-05-20 00:07:41 +0000197 return ret;
198}
199
200void RpcSession::FdTrigger::trigger() {
201 mWrite.reset();
202}
203
Steven Morelanda8b44292021-06-08 01:27:53 +0000204bool RpcSession::FdTrigger::isTriggered() {
205 return mWrite == -1;
206}
207
Steven Moreland798e0d12021-07-14 23:19:25 +0000208status_t RpcSession::FdTrigger::triggerablePoll(base::borrowed_fd fd, int16_t event) {
Steven Moreland4ec3c432021-05-20 00:32:47 +0000209 while (true) {
Steven Moreland441bb0e2021-07-21 22:36:32 +0000210 pollfd pfd[]{{.fd = fd.get(), .events = static_cast<int16_t>(event), .revents = 0},
Steven Moreland4ec3c432021-05-20 00:32:47 +0000211 {.fd = mRead.get(), .events = POLLHUP, .revents = 0}};
212 int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
213 if (ret < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000214 return -errno;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000215 }
216 if (ret == 0) {
217 continue;
218 }
219 if (pfd[1].revents & POLLHUP) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000220 return -ECANCELED;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000221 }
Steven Moreland798e0d12021-07-14 23:19:25 +0000222 return pfd[0].revents & event ? OK : DEAD_OBJECT;
Steven Moreland4ec3c432021-05-20 00:32:47 +0000223 }
224}
225
Steven Moreland798e0d12021-07-14 23:19:25 +0000226status_t RpcSession::FdTrigger::interruptableWriteFully(base::borrowed_fd fd, const void* data,
227 size_t size) {
228 const uint8_t* buffer = reinterpret_cast<const uint8_t*>(data);
229 const uint8_t* end = buffer + size;
230
231 MAYBE_WAIT_IN_FLAKE_MODE;
232
233 status_t status;
234 while ((status = triggerablePoll(fd, POLLOUT)) == OK) {
235 ssize_t writeSize = TEMP_FAILURE_RETRY(send(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
236 if (writeSize == 0) return DEAD_OBJECT;
237
238 if (writeSize < 0) {
239 return -errno;
240 }
241 buffer += writeSize;
242 if (buffer == end) return OK;
243 }
244 return status;
245}
246
Steven Moreland2b4f3802021-05-22 01:46:27 +0000247status_t RpcSession::FdTrigger::interruptableReadFully(base::borrowed_fd fd, void* data,
248 size_t size) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000249 uint8_t* buffer = reinterpret_cast<uint8_t*>(data);
250 uint8_t* end = buffer + size;
251
Steven Morelandb8176792021-06-22 20:29:21 +0000252 MAYBE_WAIT_IN_FLAKE_MODE;
253
Steven Moreland2b4f3802021-05-22 01:46:27 +0000254 status_t status;
Steven Moreland798e0d12021-07-14 23:19:25 +0000255 while ((status = triggerablePoll(fd, POLLIN)) == OK) {
Steven Moreland9d11b922021-05-20 01:22:58 +0000256 ssize_t readSize = TEMP_FAILURE_RETRY(recv(fd.get(), buffer, end - buffer, MSG_NOSIGNAL));
Steven Moreland2b4f3802021-05-22 01:46:27 +0000257 if (readSize == 0) return DEAD_OBJECT; // EOF
Steven Morelanddfe3be92021-05-22 00:24:29 +0000258
Steven Moreland9d11b922021-05-20 01:22:58 +0000259 if (readSize < 0) {
Steven Moreland2b4f3802021-05-22 01:46:27 +0000260 return -errno;
Steven Moreland9d11b922021-05-20 01:22:58 +0000261 }
262 buffer += readSize;
Steven Moreland2b4f3802021-05-22 01:46:27 +0000263 if (buffer == end) return OK;
Steven Moreland9d11b922021-05-20 01:22:58 +0000264 }
Steven Moreland2b4f3802021-05-22 01:46:27 +0000265 return status;
Steven Moreland9d11b922021-05-20 01:22:58 +0000266}
267
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000268status_t RpcSession::readId() {
269 {
270 std::lock_guard<std::mutex> _l(mMutex);
271 LOG_ALWAYS_FATAL_IF(mForServer != nullptr, "Can only update ID for client.");
272 }
273
Steven Moreland195edb82021-06-08 02:44:39 +0000274 ExclusiveConnection connection;
275 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
276 ConnectionUse::CLIENT, &connection);
277 if (status != OK) return status;
278
Steven Moreland01a6bad2021-06-11 00:59:20 +0000279 mId = RpcAddress::zero();
280 status = state()->getSessionId(connection.get(), sp<RpcSession>::fromExisting(this),
281 &mId.value());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000282 if (status != OK) return status;
283
Steven Moreland01a6bad2021-06-11 00:59:20 +0000284 LOG_RPC_DETAIL("RpcSession %p has id %s", this, mId->toString().c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000285 return OK;
286}
287
Steven Morelanddd67b942021-07-23 17:15:41 -0700288void RpcSession::WaitForShutdownListener::onSessionAllIncomingThreadsEnded(
Steven Moreland659416d2021-05-11 00:47:50 +0000289 const sp<RpcSession>& session) {
290 (void)session;
291 mShutdown = true;
292}
293
Steven Moreland19fc9f72021-06-10 03:57:30 +0000294void RpcSession::WaitForShutdownListener::onSessionIncomingThreadEnded() {
Steven Moreland659416d2021-05-11 00:47:50 +0000295 mCv.notify_all();
296}
297
298void RpcSession::WaitForShutdownListener::waitForShutdown(std::unique_lock<std::mutex>& lock) {
299 while (!mShutdown) {
300 if (std::cv_status::timeout == mCv.wait_for(lock, std::chrono::seconds(1))) {
301 ALOGE("Waiting for RpcSession to shut down (1s w/o progress).");
302 }
303 }
304}
305
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000306void RpcSession::preJoinThreadOwnership(std::thread thread) {
Steven Morelanda63ff932021-05-12 00:03:15 +0000307 LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000308
Steven Morelanda63ff932021-05-12 00:03:15 +0000309 {
310 std::lock_guard<std::mutex> _l(mMutex);
311 mThreads[thread.get_id()] = std::move(thread);
312 }
Steven Moreland5802c2b2021-05-12 20:13:04 +0000313}
Steven Morelanda63ff932021-05-12 00:03:15 +0000314
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000315RpcSession::PreJoinSetupResult RpcSession::preJoinSetup(base::unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000316 // must be registered to allow arbitrary client code executing commands to
317 // be able to do nested calls (we can't only read from it)
Steven Moreland19fc9f72021-06-10 03:57:30 +0000318 sp<RpcConnection> connection = assignIncomingConnectionToThisThread(std::move(fd));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000319
Steven Morelanddd67b942021-07-23 17:15:41 -0700320 status_t status;
321
322 if (connection == nullptr) {
323 status = DEAD_OBJECT;
324 } else {
325 status = mState->readConnectionInit(connection, sp<RpcSession>::fromExisting(this));
326 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000327
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000328 return PreJoinSetupResult{
329 .connection = std::move(connection),
330 .status = status,
331 };
332}
333
Yifan Hong194acf22021-06-29 18:44:56 -0700334namespace {
335// RAII object for attaching / detaching current thread to JVM if Android Runtime exists. If
336// Android Runtime doesn't exist, no-op.
337class JavaThreadAttacher {
338public:
339 JavaThreadAttacher() {
340 // Use dlsym to find androidJavaAttachThread because libandroid_runtime is loaded after
341 // libbinder.
342 auto vm = getJavaVM();
343 if (vm == nullptr) return;
344
345 char threadName[16];
346 if (0 != pthread_getname_np(pthread_self(), threadName, sizeof(threadName))) {
347 constexpr const char* defaultThreadName = "UnknownRpcSessionThread";
348 memcpy(threadName, defaultThreadName,
349 std::min<size_t>(sizeof(threadName), strlen(defaultThreadName) + 1));
350 }
351 LOG_RPC_DETAIL("Attaching current thread %s to JVM", threadName);
352 JavaVMAttachArgs args;
353 args.version = JNI_VERSION_1_2;
354 args.name = threadName;
355 args.group = nullptr;
356 JNIEnv* env;
357
358 LOG_ALWAYS_FATAL_IF(vm->AttachCurrentThread(&env, &args) != JNI_OK,
359 "Cannot attach thread %s to JVM", threadName);
360 mAttached = true;
361 }
362 ~JavaThreadAttacher() {
363 if (!mAttached) return;
364 auto vm = getJavaVM();
365 LOG_ALWAYS_FATAL_IF(vm == nullptr,
366 "Unable to detach thread. No JavaVM, but it was present before!");
367
368 LOG_RPC_DETAIL("Detaching current thread from JVM");
369 if (vm->DetachCurrentThread() != JNI_OK) {
370 mAttached = false;
371 } else {
372 ALOGW("Unable to detach current thread from JVM");
373 }
374 }
375
376private:
377 DISALLOW_COPY_AND_ASSIGN(JavaThreadAttacher);
378 bool mAttached = false;
379
380 static JavaVM* getJavaVM() {
381 static auto fn = reinterpret_cast<decltype(&AndroidRuntimeGetJavaVM)>(
382 dlsym(RTLD_DEFAULT, "AndroidRuntimeGetJavaVM"));
383 if (fn == nullptr) return nullptr;
384 return fn();
385 }
386};
387} // namespace
388
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000389void RpcSession::join(sp<RpcSession>&& session, PreJoinSetupResult&& setupResult) {
390 sp<RpcConnection>& connection = setupResult.connection;
391
392 if (setupResult.status == OK) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700393 LOG_ALWAYS_FATAL_IF(!connection, "must have connection if setup succeeded");
Yifan Hong194acf22021-06-29 18:44:56 -0700394 JavaThreadAttacher javaThreadAttacher;
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000395 while (true) {
Steven Moreland5ae62562021-06-10 03:21:42 +0000396 status_t status = session->state()->getAndExecuteCommand(connection, session,
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000397 RpcState::CommandType::ANY);
398 if (status != OK) {
399 LOG_RPC_DETAIL("Binder connection thread closing w/ status %s",
400 statusToString(status).c_str());
401 break;
402 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000403 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000404 } else {
405 ALOGE("Connection failed to init, closing with status %s",
406 statusToString(setupResult.status).c_str());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000407 }
408
Steven Moreland659416d2021-05-11 00:47:50 +0000409 sp<RpcSession::EventListener> listener;
Steven Morelanda63ff932021-05-12 00:03:15 +0000410 {
Steven Moreland659416d2021-05-11 00:47:50 +0000411 std::lock_guard<std::mutex> _l(session->mMutex);
412 auto it = session->mThreads.find(std::this_thread::get_id());
413 LOG_ALWAYS_FATAL_IF(it == session->mThreads.end());
Steven Morelanda63ff932021-05-12 00:03:15 +0000414 it->second.detach();
Steven Moreland659416d2021-05-11 00:47:50 +0000415 session->mThreads.erase(it);
Steven Morelandee3f4662021-05-22 01:07:33 +0000416
Steven Moreland659416d2021-05-11 00:47:50 +0000417 listener = session->mEventListener.promote();
Steven Morelandee3f4662021-05-22 01:07:33 +0000418 }
419
Steven Morelanddd67b942021-07-23 17:15:41 -0700420 // done after all cleanup, since session shutdown progresses via callbacks here
421 if (connection != nullptr) {
422 LOG_ALWAYS_FATAL_IF(!session->removeIncomingConnection(connection),
423 "bad state: connection object guaranteed to be in list");
424 }
425
Steven Moreland659416d2021-05-11 00:47:50 +0000426 session = nullptr;
427
428 if (listener != nullptr) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000429 listener->onSessionIncomingThreadEnded();
Steven Morelandee78e762021-05-05 21:12:51 +0000430 }
431}
432
Steven Moreland7b8bc4c2021-06-10 22:50:27 +0000433sp<RpcServer> RpcSession::server() {
434 RpcServer* unsafeServer = mForServer.unsafe_get();
435 sp<RpcServer> server = mForServer.promote();
436
437 LOG_ALWAYS_FATAL_IF((unsafeServer == nullptr) != (server == nullptr),
438 "wp<> is to avoid strong cycle only");
439 return server;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440}
441
442bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
443 {
444 std::lock_guard<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000445 LOG_ALWAYS_FATAL_IF(mOutgoingConnections.size() != 0,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000446 "Must only setup session once, but already has %zu clients",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000447 mOutgoingConnections.size());
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000448 }
449
Steven Moreland1b304292021-07-15 22:59:34 +0000450 if (!setupOneSocketConnection(addr, RpcAddress::zero(), false /*incoming*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000451
Steven Morelandbf57bce2021-07-26 15:26:12 -0700452 {
453 ExclusiveConnection connection;
454 status_t status = ExclusiveConnection::find(sp<RpcSession>::fromExisting(this),
455 ConnectionUse::CLIENT, &connection);
456 if (status != OK) return false;
457
458 uint32_t version;
459 status = state()->readNewSessionResponse(connection.get(),
460 sp<RpcSession>::fromExisting(this), &version);
461 if (!setProtocolVersion(version)) return false;
462 }
463
Steven Morelanda5036f02021-06-08 02:26:57 +0000464 // TODO(b/189955605): we should add additional sessions dynamically
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000465 // instead of all at once.
466 // TODO(b/186470974): first risk of blocking
467 size_t numThreadsAvailable;
Steven Moreland1be91352021-05-11 22:12:15 +0000468 if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000469 ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
470 statusToString(status).c_str());
471 return false;
472 }
473
474 if (status_t status = readId(); status != OK) {
475 ALOGE("Could not get session id after initial session to %s; %s", addr.toString().c_str(),
476 statusToString(status).c_str());
477 return false;
478 }
479
480 // we've already setup one client
481 for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
Steven Morelanda5036f02021-06-08 02:26:57 +0000482 // TODO(b/189955605): shutdown existing connections?
Steven Moreland1b304292021-07-15 22:59:34 +0000483 if (!setupOneSocketConnection(addr, mId.value(), false /*incoming*/)) return false;
Steven Moreland659416d2021-05-11 00:47:50 +0000484 }
485
Steven Morelanda5036f02021-06-08 02:26:57 +0000486 // TODO(b/189955605): we should add additional sessions dynamically
Steven Moreland659416d2021-05-11 00:47:50 +0000487 // instead of all at once - the other side should be responsible for setting
488 // up additional connections. We need to create at least one (unless 0 are
489 // requested to be set) in order to allow the other side to reliably make
490 // any requests at all.
491
Steven Moreland103424e2021-06-02 18:16:19 +0000492 for (size_t i = 0; i < mMaxThreads; i++) {
Steven Moreland1b304292021-07-15 22:59:34 +0000493 if (!setupOneSocketConnection(addr, mId.value(), true /*incoming*/)) return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000494 }
495
496 return true;
497}
498
Steven Moreland01a6bad2021-06-11 00:59:20 +0000499bool RpcSession::setupOneSocketConnection(const RpcSocketAddress& addr, const RpcAddress& id,
Steven Moreland1b304292021-07-15 22:59:34 +0000500 bool incoming) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000501 for (size_t tries = 0; tries < 5; tries++) {
502 if (tries > 0) usleep(10000);
503
504 unique_fd serverFd(
505 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
506 if (serverFd == -1) {
507 int savedErrno = errno;
508 ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
509 strerror(savedErrno));
510 return false;
511 }
512
513 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
514 if (errno == ECONNRESET) {
515 ALOGW("Connection reset on %s", addr.toString().c_str());
516 continue;
517 }
518 int savedErrno = errno;
519 ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
520 strerror(savedErrno));
521 return false;
522 }
523
Steven Morelandbf57bce2021-07-26 15:26:12 -0700524 RpcConnectionHeader header{
525 .version = mProtocolVersion.value_or(RPC_WIRE_PROTOCOL_VERSION),
526 .options = 0,
527 };
Steven Moreland01a6bad2021-06-11 00:59:20 +0000528 memcpy(&header.sessionId, &id.viewRawEmbedded(), sizeof(RpcWireAddress));
529
Steven Moreland1b304292021-07-15 22:59:34 +0000530 if (incoming) header.options |= RPC_CONNECTION_OPTION_INCOMING;
Steven Moreland659416d2021-05-11 00:47:50 +0000531
532 if (sizeof(header) != TEMP_FAILURE_RETRY(write(serverFd.get(), &header, sizeof(header)))) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000533 int savedErrno = errno;
Steven Moreland659416d2021-05-11 00:47:50 +0000534 ALOGE("Could not write connection header to socket at %s: %s", addr.toString().c_str(),
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000535 strerror(savedErrno));
536 return false;
537 }
538
539 LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
540
Steven Moreland1b304292021-07-15 22:59:34 +0000541 if (incoming) {
Steven Morelandfba6f772021-07-15 22:45:09 +0000542 return addIncomingConnection(std::move(serverFd));
Steven Moreland659416d2021-05-11 00:47:50 +0000543 } else {
Steven Morelandb86e26b2021-06-12 00:35:58 +0000544 return addOutgoingConnection(std::move(serverFd), true);
Steven Moreland659416d2021-05-11 00:47:50 +0000545 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000546 }
547
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000548 ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
549 return false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000550}
551
Steven Morelandfba6f772021-07-15 22:45:09 +0000552bool RpcSession::addIncomingConnection(unique_fd fd) {
553 std::mutex mutex;
554 std::condition_variable joinCv;
555 std::unique_lock<std::mutex> lock(mutex);
556 std::thread thread;
557 sp<RpcSession> thiz = sp<RpcSession>::fromExisting(this);
558 bool ownershipTransferred = false;
559 thread = std::thread([&]() {
560 std::unique_lock<std::mutex> threadLock(mutex);
561 unique_fd movedFd = std::move(fd);
562 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
563 sp<RpcSession> session = thiz;
564 session->preJoinThreadOwnership(std::move(thread));
565
566 // only continue once we have a response or the connection fails
567 auto setupResult = session->preJoinSetup(std::move(movedFd));
568
569 ownershipTransferred = true;
570 threadLock.unlock();
571 joinCv.notify_one();
572 // do not use & vars below
573
574 RpcSession::join(std::move(session), std::move(setupResult));
575 });
576 joinCv.wait(lock, [&] { return ownershipTransferred; });
577 LOG_ALWAYS_FATAL_IF(!ownershipTransferred);
578 return true;
579}
580
Steven Morelandb86e26b2021-06-12 00:35:58 +0000581bool RpcSession::addOutgoingConnection(unique_fd fd, bool init) {
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000582 sp<RpcConnection> connection = sp<RpcConnection>::make();
583 {
584 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelandee3f4662021-05-22 01:07:33 +0000585
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000586 // first client connection added, but setForServer not called, so
587 // initializaing for a client.
588 if (mShutdownTrigger == nullptr) {
589 mShutdownTrigger = FdTrigger::make();
590 mEventListener = mShutdownListener = sp<WaitForShutdownListener>::make();
591 if (mShutdownTrigger == nullptr) return false;
592 }
593
594 connection->fd = std::move(fd);
595 connection->exclusiveTid = gettid();
Steven Moreland19fc9f72021-06-10 03:57:30 +0000596 mOutgoingConnections.push_back(connection);
Steven Morelandee3f4662021-05-22 01:07:33 +0000597 }
598
Steven Morelandb86e26b2021-06-12 00:35:58 +0000599 status_t status = OK;
600 if (init) {
601 mState->sendConnectionInit(connection, sp<RpcSession>::fromExisting(this));
602 }
Steven Morelandc88b7fc2021-06-10 00:40:39 +0000603
604 {
605 std::lock_guard<std::mutex> _l(mMutex);
606 connection->exclusiveTid = std::nullopt;
607 }
608
609 return status == OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000610}
611
Steven Morelanda8b44292021-06-08 01:27:53 +0000612bool RpcSession::setForServer(const wp<RpcServer>& server, const wp<EventListener>& eventListener,
Steven Moreland01a6bad2021-06-11 00:59:20 +0000613 const RpcAddress& sessionId) {
Steven Moreland659416d2021-05-11 00:47:50 +0000614 LOG_ALWAYS_FATAL_IF(mForServer != nullptr);
615 LOG_ALWAYS_FATAL_IF(server == nullptr);
616 LOG_ALWAYS_FATAL_IF(mEventListener != nullptr);
617 LOG_ALWAYS_FATAL_IF(eventListener == nullptr);
Steven Morelandee3f4662021-05-22 01:07:33 +0000618 LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr);
Steven Morelanda8b44292021-06-08 01:27:53 +0000619
620 mShutdownTrigger = FdTrigger::make();
621 if (mShutdownTrigger == nullptr) return false;
Steven Morelandee3f4662021-05-22 01:07:33 +0000622
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000623 mId = sessionId;
624 mForServer = server;
Steven Moreland659416d2021-05-11 00:47:50 +0000625 mEventListener = eventListener;
Steven Morelanda8b44292021-06-08 01:27:53 +0000626 return true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000627}
628
Steven Moreland19fc9f72021-06-10 03:57:30 +0000629sp<RpcSession::RpcConnection> RpcSession::assignIncomingConnectionToThisThread(unique_fd fd) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000630 std::lock_guard<std::mutex> _l(mMutex);
Steven Morelanddd67b942021-07-23 17:15:41 -0700631
632 // Don't accept any more connections, some have shutdown. Usually this
633 // happens when new connections are still being established as part of a
634 // very short-lived session which shuts down after it already started
635 // accepting new connections.
636 if (mIncomingConnections.size() < mMaxIncomingConnections) {
637 return nullptr;
638 }
639
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000640 sp<RpcConnection> session = sp<RpcConnection>::make();
641 session->fd = std::move(fd);
642 session->exclusiveTid = gettid();
Steven Morelanddd67b942021-07-23 17:15:41 -0700643
Steven Moreland19fc9f72021-06-10 03:57:30 +0000644 mIncomingConnections.push_back(session);
Steven Morelanddd67b942021-07-23 17:15:41 -0700645 mMaxIncomingConnections = mIncomingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000646
647 return session;
648}
649
Steven Moreland19fc9f72021-06-10 03:57:30 +0000650bool RpcSession::removeIncomingConnection(const sp<RpcConnection>& connection) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700651 std::unique_lock<std::mutex> _l(mMutex);
Steven Moreland19fc9f72021-06-10 03:57:30 +0000652 if (auto it = std::find(mIncomingConnections.begin(), mIncomingConnections.end(), connection);
653 it != mIncomingConnections.end()) {
654 mIncomingConnections.erase(it);
655 if (mIncomingConnections.size() == 0) {
Steven Moreland659416d2021-05-11 00:47:50 +0000656 sp<EventListener> listener = mEventListener.promote();
657 if (listener) {
Steven Morelanddd67b942021-07-23 17:15:41 -0700658 _l.unlock();
659 listener->onSessionAllIncomingThreadsEnded(sp<RpcSession>::fromExisting(this));
Steven Morelanda86e8fe2021-05-26 22:52:35 +0000660 }
Steven Morelandee78e762021-05-05 21:12:51 +0000661 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000662 return true;
663 }
664 return false;
665}
666
Steven Moreland195edb82021-06-08 02:44:39 +0000667status_t RpcSession::ExclusiveConnection::find(const sp<RpcSession>& session, ConnectionUse use,
668 ExclusiveConnection* connection) {
669 connection->mSession = session;
670 connection->mConnection = nullptr;
671 connection->mReentrant = false;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000672
Steven Moreland195edb82021-06-08 02:44:39 +0000673 pid_t tid = gettid();
674 std::unique_lock<std::mutex> _l(session->mMutex);
675
676 session->mWaitingThreads++;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000677 while (true) {
678 sp<RpcConnection> exclusive;
679 sp<RpcConnection> available;
680
681 // CHECK FOR DEDICATED CLIENT SOCKET
682 //
Steven Moreland85e067b2021-05-26 17:43:53 +0000683 // A server/looper should always use a dedicated connection if available
Steven Moreland19fc9f72021-06-10 03:57:30 +0000684 findConnection(tid, &exclusive, &available, session->mOutgoingConnections,
685 session->mOutgoingConnectionsOffset);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000686
687 // WARNING: this assumes a server cannot request its client to send
Steven Moreland19fc9f72021-06-10 03:57:30 +0000688 // a transaction, as mIncomingConnections is excluded below.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000689 //
690 // Imagine we have more than one thread in play, and a single thread
691 // sends a synchronous, then an asynchronous command. Imagine the
692 // asynchronous command is sent on the first client connection. Then, if
693 // we naively send a synchronous command to that same connection, the
694 // thread on the far side might be busy processing the asynchronous
695 // command. So, we move to considering the second available thread
696 // for subsequent calls.
697 if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000698 session->mOutgoingConnectionsOffset = (session->mOutgoingConnectionsOffset + 1) %
699 session->mOutgoingConnections.size();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000700 }
701
Steven Morelandc7d40132021-06-10 03:42:11 +0000702 // USE SERVING SOCKET (e.g. nested transaction)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000703 if (use != ConnectionUse::CLIENT_ASYNC) {
Steven Moreland19fc9f72021-06-10 03:57:30 +0000704 sp<RpcConnection> exclusiveIncoming;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000705 // server connections are always assigned to a thread
Steven Moreland19fc9f72021-06-10 03:57:30 +0000706 findConnection(tid, &exclusiveIncoming, nullptr /*available*/,
707 session->mIncomingConnections, 0 /* index hint */);
Steven Morelandc7d40132021-06-10 03:42:11 +0000708
709 // asynchronous calls cannot be nested, we currently allow ref count
710 // calls to be nested (so that you can use this without having extra
711 // threads). Note 'drainCommands' is used so that these ref counts can't
712 // build up.
Steven Moreland19fc9f72021-06-10 03:57:30 +0000713 if (exclusiveIncoming != nullptr) {
714 if (exclusiveIncoming->allowNested) {
Steven Morelandc7d40132021-06-10 03:42:11 +0000715 // guaranteed to be processed as nested command
Steven Moreland19fc9f72021-06-10 03:57:30 +0000716 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000717 } else if (use == ConnectionUse::CLIENT_REFCOUNT && available == nullptr) {
718 // prefer available socket, but if we don't have one, don't
719 // wait for one
Steven Moreland19fc9f72021-06-10 03:57:30 +0000720 exclusive = exclusiveIncoming;
Steven Morelandc7d40132021-06-10 03:42:11 +0000721 }
722 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000723 }
724
Steven Moreland85e067b2021-05-26 17:43:53 +0000725 // if our thread is already using a connection, prioritize using that
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000726 if (exclusive != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000727 connection->mConnection = exclusive;
728 connection->mReentrant = true;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000729 break;
730 } else if (available != nullptr) {
Steven Moreland195edb82021-06-08 02:44:39 +0000731 connection->mConnection = available;
732 connection->mConnection->exclusiveTid = tid;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000733 break;
734 }
735
Steven Moreland19fc9f72021-06-10 03:57:30 +0000736 if (session->mOutgoingConnections.size() == 0) {
Steven Moreland195edb82021-06-08 02:44:39 +0000737 ALOGE("Session has no client connections. This is required for an RPC server to make "
738 "any non-nested (e.g. oneway or on another thread) calls. Use: %d. Server "
739 "connections: %zu",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000740 static_cast<int>(use), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000741 return WOULD_BLOCK;
742 }
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000743
Steven Moreland85e067b2021-05-26 17:43:53 +0000744 LOG_RPC_DETAIL("No available connections (have %zu clients and %zu servers). Waiting...",
Steven Moreland19fc9f72021-06-10 03:57:30 +0000745 session->mOutgoingConnections.size(), session->mIncomingConnections.size());
Steven Moreland195edb82021-06-08 02:44:39 +0000746 session->mAvailableConnectionCv.wait(_l);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000747 }
Steven Moreland195edb82021-06-08 02:44:39 +0000748 session->mWaitingThreads--;
749
750 return OK;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000751}
752
753void RpcSession::ExclusiveConnection::findConnection(pid_t tid, sp<RpcConnection>* exclusive,
754 sp<RpcConnection>* available,
755 std::vector<sp<RpcConnection>>& sockets,
756 size_t socketsIndexHint) {
757 LOG_ALWAYS_FATAL_IF(sockets.size() > 0 && socketsIndexHint >= sockets.size(),
758 "Bad index %zu >= %zu", socketsIndexHint, sockets.size());
759
760 if (*exclusive != nullptr) return; // consistent with break below
761
762 for (size_t i = 0; i < sockets.size(); i++) {
763 sp<RpcConnection>& socket = sockets[(i + socketsIndexHint) % sockets.size()];
764
Steven Moreland85e067b2021-05-26 17:43:53 +0000765 // take first available connection (intuition = caching)
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000766 if (available && *available == nullptr && socket->exclusiveTid == std::nullopt) {
767 *available = socket;
768 continue;
769 }
770
Steven Moreland85e067b2021-05-26 17:43:53 +0000771 // though, prefer to take connection which is already inuse by this thread
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000772 // (nested transactions)
773 if (exclusive && socket->exclusiveTid == tid) {
774 *exclusive = socket;
775 break; // consistent with return above
776 }
777 }
778}
779
780RpcSession::ExclusiveConnection::~ExclusiveConnection() {
Steven Moreland85e067b2021-05-26 17:43:53 +0000781 // reentrant use of a connection means something less deep in the call stack
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000782 // is using this fd, and it retains the right to it. So, we don't give up
783 // exclusive ownership, and no thread is freed.
Steven Moreland195edb82021-06-08 02:44:39 +0000784 if (!mReentrant && mConnection != nullptr) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000785 std::unique_lock<std::mutex> _l(mSession->mMutex);
786 mConnection->exclusiveTid = std::nullopt;
787 if (mSession->mWaitingThreads > 0) {
788 _l.unlock();
789 mSession->mAvailableConnectionCv.notify_one();
790 }
791 }
792}
793
794} // namespace android