blob: 11150bcd77037b3782e1396c0c05f398880b4542 [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +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
Tomasz Wasilczyk38a22ee2023-10-19 20:04:46 +000017#ifndef __ANDROID_VENDOR__
18// only used on NDK tests outside of vendor
Andrei Homescu9d8adb12022-08-02 04:38:30 +000019#include <aidl/IBinderRpcTest.h>
Tomasz Wasilczyk38a22ee2023-10-19 20:04:46 +000020#endif
Steven Moreland5553ac42020-11-11 02:14:45 +000021
Devin Moore1df9c5f2024-07-23 22:09:29 +000022#if defined(__LP64__)
23#define TEST_FILE_SUFFIX "64"
24#else
25#define TEST_FILE_SUFFIX "32"
26#endif
27
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <chrono>
29#include <cstdlib>
30#include <iostream>
31#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000032#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000033
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070034#include <dirent.h>
Andrei Homescu2a298012022-06-15 01:08:54 +000035#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070036#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000037#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000038#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000039
Andrei Homescud65666d2023-03-03 07:28:02 +000040#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000041#include <binder/RpcTransportTipcAndroid.h>
42#include <trusty/tipc.h>
Andrei Homescud65666d2023-03-03 07:28:02 +000043#endif // BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000044
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -080045#include "../Utils.h"
Andrei Homescu2a298012022-06-15 01:08:54 +000046#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000047#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000048
Devin Moorec370db42024-08-09 23:18:05 +000049// TODO need to add IServiceManager.cpp/.h to libbinder_no_kernel
50#ifdef BINDER_WITH_KERNEL_IPC
51#include "android-base/logging.h"
52#include "android/binder_manager.h"
53#include "android/binder_rpc.h"
54#endif // BINDER_WITH_KERNEL_IPC
55
Yifan Hong1a235852021-05-13 16:07:47 -070056using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070057using namespace std::placeholders;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070058using android::binder::borrowed_fd;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -070059using android::binder::GetExecutableDirectory;
60using android::binder::ReadFdToString;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070061using android::binder::unique_fd;
Yifan Hong1deca4b2021-09-10 16:16:44 -070062using testing::AssertionFailure;
63using testing::AssertionResult;
64using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070065
Steven Moreland5553ac42020-11-11 02:14:45 +000066namespace android {
67
Andrei Homescu12106de2022-04-27 04:42:21 +000068#ifdef BINDER_TEST_NO_SHARED_LIBS
69constexpr bool kEnableSharedLibs = false;
70#else
71constexpr bool kEnableSharedLibs = true;
72#endif
73
Andrei Homescud65666d2023-03-03 07:28:02 +000074#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000075constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
76#endif
77
Frederick Maylea12b0962022-06-25 01:13:22 +000078static std::string WaitStatusToString(int wstatus) {
79 if (WIFEXITED(wstatus)) {
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070080 return "exit status " + std::to_string(WEXITSTATUS(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000081 }
82 if (WIFSIGNALED(wstatus)) {
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070083 return "term signal " + std::to_string(WTERMSIG(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000084 }
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070085 return "unexpected state " + std::to_string(wstatus);
Frederick Maylea12b0962022-06-25 01:13:22 +000086}
87
Steven Moreland276d8df2022-09-28 23:56:39 +000088static void debugBacktrace(pid_t pid) {
89 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
90 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
91}
92
Steven Moreland5553ac42020-11-11 02:14:45 +000093class Process {
94public:
Andrei Homescu96834632022-10-14 00:49:49 +000095 Process(Process&& other)
96 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
97 mReadEnd(std::move(other.mReadEnd)),
98 mWriteEnd(std::move(other.mWriteEnd)) {
99 // The default move constructor doesn't clear mPid after moving it,
100 // which we need to do because the destructor checks for mPid!=0
101 mPid = other.mPid;
102 other.mPid = 0;
103 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700104 Process(const std::function<void(borrowed_fd /* writeEnd */, borrowed_fd /* readEnd */)>& f) {
105 unique_fd childWriteEnd;
106 unique_fd childReadEnd;
107 if (!binder::Pipe(&mReadEnd, &childWriteEnd, 0)) PLOGF("child write pipe failed");
108 if (!binder::Pipe(&childReadEnd, &mWriteEnd, 0)) PLOGF("child read pipe failed");
Steven Moreland5553ac42020-11-11 02:14:45 +0000109 if (0 == (mPid = fork())) {
110 // racey: assume parent doesn't crash before this is set
111 prctl(PR_SET_PDEATHSIG, SIGHUP);
112
Yifan Hong1deca4b2021-09-10 16:16:44 -0700113 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000114
115 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000116 }
117 }
118 ~Process() {
119 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000120 int wstatus;
121 waitpid(mPid, &wstatus, 0);
122 if (mCustomExitStatusCheck) {
123 mCustomExitStatusCheck(wstatus);
124 } else {
125 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
126 << "server process failed: " << WaitStatusToString(wstatus);
127 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000128 }
129 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700130 borrowed_fd readEnd() { return mReadEnd; }
131 borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000132
Frederick Maylea12b0962022-06-25 01:13:22 +0000133 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
134 mCustomExitStatusCheck = std::move(f);
135 }
136
Frederick Mayle69a0c992022-05-26 20:38:39 +0000137 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
138 void terminate() { kill(mPid, SIGTERM); }
139
Steven Moreland276d8df2022-09-28 23:56:39 +0000140 pid_t getPid() { return mPid; }
141
Steven Moreland5553ac42020-11-11 02:14:45 +0000142private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000143 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000144 pid_t mPid = 0;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700145 unique_fd mReadEnd;
146 unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000147};
148
149static std::string allocateSocketAddress() {
150 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000151 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000152 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700153 unlink(ret.c_str());
154 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000155};
156
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700157static unique_fd initUnixSocket(std::string addr) {
Alice Wang893a9912022-10-24 10:44:09 +0000158 auto socket_addr = UnixSocketAddress(addr.c_str());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700159 unique_fd fd(TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700160 if (!fd.ok()) PLOGF("initUnixSocket failed to create socket");
161 if (0 != TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize()))) {
162 PLOGF("initUnixSocket failed to bind");
163 }
Alice Wang893a9912022-10-24 10:44:09 +0000164 return fd;
165}
166
Andrei Homescu96834632022-10-14 00:49:49 +0000167// Destructors need to be defined, even if pure virtual
168ProcessSession::~ProcessSession() {}
169
170class LinuxProcessSession : public ProcessSession {
171public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000172 // reference to process hosting a socket server
173 Process host;
174
Andrei Homescu96834632022-10-14 00:49:49 +0000175 LinuxProcessSession(LinuxProcessSession&&) = default;
176 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
177 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000178 for (auto& session : sessions) {
179 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000180 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000181
Steven Moreland67f85902023-03-15 01:13:49 +0000182 for (size_t sessionNum = 0; sessionNum < sessions.size(); sessionNum++) {
183 auto& info = sessions.at(sessionNum);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000184 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000185
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000186 EXPECT_NE(nullptr, session);
187 EXPECT_NE(nullptr, session->state());
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700188 EXPECT_EQ(0u, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000189
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000190 wp<RpcSession> weakSession = session;
191 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000192
Steven Moreland57042712022-10-04 23:56:45 +0000193 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
194 // the object should not actually be promotable. By looping, we distinguish a race here
195 // from a bug causing the object to not be promotable.
196 for (size_t i = 0; i < 3; i++) {
197 sp<RpcSession> strongSession = weakSession.promote();
198 EXPECT_EQ(nullptr, strongSession)
Steven Moreland67f85902023-03-15 01:13:49 +0000199 << "For session " << sessionNum << ". "
Steven Moreland57042712022-10-04 23:56:45 +0000200 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
201 "Leaked sess: ")
202 << strongSession->getStrongCount() << " checked time " << i;
203
204 if (strongSession != nullptr) {
205 sleep(1);
206 }
207 }
Steven Moreland736664b2021-05-01 04:27:25 +0000208 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000209 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000210
Andrei Homescu96834632022-10-14 00:49:49 +0000211 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
212 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000213 }
Andrei Homescu96834632022-10-14 00:49:49 +0000214
215 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000216};
217
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700218static unique_fd connectTo(const RpcSocketAddress& addr) {
219 unique_fd serverFd(
Steven Moreland4198a122021-08-03 17:37:58 -0700220 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700221 if (!serverFd.ok()) {
222 PLOGF("Could not create socket %s", addr.toString().c_str());
223 }
Steven Moreland4198a122021-08-03 17:37:58 -0700224
225 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700226 PLOGF("Could not connect to socket %s", addr.toString().c_str());
Steven Moreland4198a122021-08-03 17:37:58 -0700227 }
228 return serverFd;
229}
230
Andrei Homescud65666d2023-03-03 07:28:02 +0000231#ifndef BINDER_RPC_TO_TRUSTY_TEST
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700232static unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
233 unique_fd sockClient, sockServer;
234 if (!binder::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700235 PLOGF("Failed socketpair()");
David Brazdil21c887c2022-09-23 12:25:18 +0100236 }
237
238 int zero = 0;
239 iovec iov{&zero, sizeof(zero)};
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700240 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +0100241 fds.emplace_back(std::move(sockServer));
242
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000243 if (binder::os::sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700244 PLOGF("Failed sendMessageOnSocket");
David Brazdil21c887c2022-09-23 12:25:18 +0100245 }
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700246 return sockClient;
David Brazdil21c887c2022-09-23 12:25:18 +0100247}
Andrei Homescud65666d2023-03-03 07:28:02 +0000248#endif // BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100249
Andrei Homescuf30148c2023-03-10 00:31:45 +0000250std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
251 return newTlsFactory(rpcSecurity);
Andrei Homescu96834632022-10-14 00:49:49 +0000252}
Andrei Homescu2a298012022-06-15 01:08:54 +0000253
Andrei Homescu96834632022-10-14 00:49:49 +0000254// This creates a new process serving an interface on a certain number of
255// threads.
256std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
257 const BinderRpcOptions& options) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700258 LOG_ALWAYS_FATAL_IF(options.numSessions < 1, "Must have at least one session to a server");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000259
Steven Moreland67f85902023-03-15 01:13:49 +0000260 if (options.numIncomingConnectionsBySession.size() != 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700261 LOG_ALWAYS_FATAL_IF(options.numIncomingConnectionsBySession.size() != options.numSessions,
262 "%s: %zu != %zu", __func__,
263 options.numIncomingConnectionsBySession.size(), options.numSessions);
Steven Moreland67f85902023-03-15 01:13:49 +0000264 }
265
Steven Morelandb469f432023-07-28 22:13:47 +0000266 SocketType socketType = GetParam().type;
267 RpcSecurity rpcSecurity = GetParam().security;
268 uint32_t clientVersion = GetParam().clientVersion;
269 uint32_t serverVersion = GetParam().serverVersion;
270 bool singleThreaded = GetParam().singleThreaded;
271 bool noKernel = GetParam().noKernel;
Andrei Homescu96834632022-10-14 00:49:49 +0000272
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700273 std::string path = GetExecutableDirectory();
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -0700274 auto servicePath = path + "/binder_rpc_test_service" +
Devin Moore1df9c5f2024-07-23 22:09:29 +0000275 (singleThreaded ? "_single_threaded" : "") + (noKernel ? "_no_kernel" : "") +
276 TEST_FILE_SUFFIX;
Andrei Homescu96834632022-10-14 00:49:49 +0000277
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700278 unique_fd bootstrapClientFd, socketFd;
Alice Wang1ef010b2022-11-14 09:09:25 +0000279
Alice Wang893a9912022-10-24 10:44:09 +0000280 auto addr = allocateSocketAddress();
281 // Initializes the socket before the fork/exec.
282 if (socketType == SocketType::UNIX_RAW) {
283 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000284 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
285 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
286 // This is because we cannot pass ParcelFileDescriptor over a pipe.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700287 if (!binder::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700288 PLOGF("Failed socketpair()");
Alice Wang1ef010b2022-11-14 09:09:25 +0000289 }
Alice Wang893a9912022-10-24 10:44:09 +0000290 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000291
Andrei Homescu96834632022-10-14 00:49:49 +0000292 auto ret = std::make_unique<LinuxProcessSession>(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700293 Process([=](borrowed_fd writeEnd, borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000294 if (socketType == SocketType::TIPC) {
295 // Trusty has a single persistent service
296 return;
297 }
298
Andrei Homescu96834632022-10-14 00:49:49 +0000299 auto writeFd = std::to_string(writeEnd.get());
300 auto readFd = std::to_string(readEnd.get());
Tomasz Wasilczyk7ba2e7e2023-11-13 13:18:57 -0800301 auto status = execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(),
302 readFd.c_str(), NULL);
303 PLOGF("execl('%s', _, %s, %s) should not return at all, but it returned %d",
304 servicePath.c_str(), writeFd.c_str(), readFd.c_str(), status);
Andrei Homescu96834632022-10-14 00:49:49 +0000305 }));
306
307 BinderRpcTestServerConfig serverConfig;
308 serverConfig.numThreads = options.numThreads;
309 serverConfig.socketType = static_cast<int32_t>(socketType);
310 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
311 serverConfig.serverVersion = serverVersion;
Alice Wang893a9912022-10-24 10:44:09 +0000312 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000313 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000314 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
315 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
316 static_cast<int32_t>(mode));
317 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000318 if (socketType != SocketType::TIPC) {
319 writeToFd(ret->host.writeEnd(), serverConfig);
320 }
Andrei Homescu96834632022-10-14 00:49:49 +0000321
322 std::vector<sp<RpcSession>> sessions;
323 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
324 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000325 std::unique_ptr<RpcTransportCtxFactory> factory;
326 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000327#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000328 factory = RpcTransportCtxFactoryTipcAndroid::make();
329#else
330 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
331#endif
332 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000333 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000334 }
335 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100336 }
337
Andrei Homescu68a55612022-08-02 01:25:15 +0000338 BinderRpcTestServerInfo serverInfo;
339 if (socketType != SocketType::TIPC) {
340 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
341 BinderRpcTestClientInfo clientInfo;
342 for (const auto& session : sessions) {
343 auto& parcelableCert = clientInfo.certs.emplace_back();
344 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
345 }
346 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000347
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700348 LOG_ALWAYS_FATAL_IF(serverInfo.port > std::numeric_limits<unsigned int>::max());
Andrei Homescu68a55612022-08-02 01:25:15 +0000349 if (socketType == SocketType::INET) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700350 LOG_ALWAYS_FATAL_IF(0 == serverInfo.port);
Andrei Homescu68a55612022-08-02 01:25:15 +0000351 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000352
Andrei Homescu68a55612022-08-02 01:25:15 +0000353 if (rpcSecurity == RpcSecurity::TLS) {
354 const auto& serverCert = serverInfo.cert.data;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700355 LOG_ALWAYS_FATAL_IF(
356 OK !=
357 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Andrei Homescu68a55612022-08-02 01:25:15 +0000358 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700359 }
360
Andrei Homescu96834632022-10-14 00:49:49 +0000361 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000362
Steven Moreland67f85902023-03-15 01:13:49 +0000363 for (size_t i = 0; i < sessions.size(); i++) {
364 const auto& session = sessions.at(i);
365
366 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
367 ? options.numIncomingConnectionsBySession.at(i)
368 : 0;
369
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700370 LOG_ALWAYS_FATAL_IF(!session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000371 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000372 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000373 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000374
Devin Moore18f63752024-08-08 21:01:24 +0000375 sockaddr_storage addr{};
376 socklen_t addrLen = 0;
377
Andrei Homescu96834632022-10-14 00:49:49 +0000378 switch (socketType) {
Devin Moore18f63752024-08-08 21:01:24 +0000379 case SocketType::PRECONNECTED: {
380 sockaddr_un addr_un{};
381 addr_un.sun_family = AF_UNIX;
382 strcpy(addr_un.sun_path, serverConfig.addr.c_str());
383 addr = *reinterpret_cast<sockaddr_storage*>(&addr_un);
384 addrLen = sizeof(sockaddr_un);
385
Andrei Homescu96834632022-10-14 00:49:49 +0000386 status = session->setupPreconnectedClient({}, [=]() {
387 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
388 });
Devin Moore18f63752024-08-08 21:01:24 +0000389 } break;
Alice Wang893a9912022-10-24 10:44:09 +0000390 case SocketType::UNIX_RAW:
Devin Moore18f63752024-08-08 21:01:24 +0000391 case SocketType::UNIX: {
392 sockaddr_un addr_un{};
393 addr_un.sun_family = AF_UNIX;
394 strcpy(addr_un.sun_path, serverConfig.addr.c_str());
395 addr = *reinterpret_cast<sockaddr_storage*>(&addr_un);
396 addrLen = sizeof(sockaddr_un);
397
Andrei Homescu96834632022-10-14 00:49:49 +0000398 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Devin Moore18f63752024-08-08 21:01:24 +0000399 } break;
Andrei Homescu96834632022-10-14 00:49:49 +0000400 case SocketType::UNIX_BOOTSTRAP:
401 status = session->setupUnixDomainSocketBootstrapClient(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700402 unique_fd(dup(bootstrapClientFd.get())));
Andrei Homescu96834632022-10-14 00:49:49 +0000403 break;
Devin Moore18f63752024-08-08 21:01:24 +0000404 case SocketType::VSOCK: {
405 sockaddr_vm addr_vm{
406 .svm_family = AF_VSOCK,
407 .svm_port = static_cast<unsigned int>(serverInfo.port),
408 .svm_cid = VMADDR_CID_LOCAL,
409 };
410 addr = *reinterpret_cast<sockaddr_storage*>(&addr_vm);
411 addrLen = sizeof(sockaddr_vm);
412
Tomasz Wasilczyk022db682024-06-17 13:55:51 -0700413 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverInfo.port);
Devin Moore18f63752024-08-08 21:01:24 +0000414 } break;
415 case SocketType::INET: {
416 const std::string ip_addr = "127.0.0.1";
417 sockaddr_in addr_in{};
418 addr_in.sin_family = AF_INET;
419 addr_in.sin_port = htons(serverInfo.port);
420 inet_aton(ip_addr.c_str(), &addr_in.sin_addr);
421 addr = *reinterpret_cast<sockaddr_storage*>(&addr_in);
422 addrLen = sizeof(sockaddr_in);
423
424 status = session->setupInetClient(ip_addr.c_str(), serverInfo.port);
425 } break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000426 case SocketType::TIPC:
427 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000428#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000429 auto port = trustyIpcPort(serverVersion);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000430 for (size_t i = 0; i < 5; i++) {
431 // Try to connect several times,
432 // in case the service is slow to start
433 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
434 if (tipcFd >= 0) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700435 return unique_fd(tipcFd);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000436 }
437 usleep(50000);
438 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700439 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000440#else
441 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700442 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000443#endif
444 });
445 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000446 default:
447 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000448 }
Andrei Homescu96834632022-10-14 00:49:49 +0000449 if (options.allowConnectFailure && status != OK) {
450 ret->sessions.clear();
451 break;
452 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700453 LOG_ALWAYS_FATAL_IF(status != OK, "Could not connect: %s", statusToString(status).c_str());
Devin Moore18f63752024-08-08 21:01:24 +0000454 ret->sessions.push_back({session, session->getRootObject(), addr, addrLen});
Steven Morelandc1635952021-04-01 16:20:47 +0000455 }
Andrei Homescu96834632022-10-14 00:49:49 +0000456 return ret;
457}
Steven Morelandc1635952021-04-01 16:20:47 +0000458
Andrei Homescua858b0e2022-08-01 23:43:09 +0000459TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
460 if (clientOrServerSingleThreaded()) {
461 GTEST_SKIP() << "This test requires multiple threads";
462 }
463
Steven Moreland51cdc2c2024-09-17 17:21:27 +0000464 constexpr size_t kNumThreads = 5;
Steven Moreland5553ac42020-11-11 02:14:45 +0000465
Steven Moreland4313d7e2021-07-15 23:41:22 +0000466 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000467
468 EXPECT_OK(proc.rootIface->lock());
469
470 // block all but one thread taking locks
471 std::vector<std::thread> ts;
472 for (size_t i = 0; i < kNumThreads - 1; i++) {
473 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
474 }
475
Steven Morelandd6d816f2022-12-23 01:37:17 +0000476 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000477
478 // other calls still work
479 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
480
Steven Morelandd6d816f2022-12-23 01:37:17 +0000481 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000482 size_t epochMsBefore = epochMillis();
483 // after this, we should never see a response within this time
484 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
485
486 // this call should be blocked for blockTimeMs
487 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
488
489 size_t epochMsAfter = epochMillis();
490 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
491
492 for (auto& t : ts) t.join();
493}
494
Steven Moreland27f620a2023-03-06 19:44:36 +0000495static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000496 size_t epochMsBefore = epochMillis();
497
498 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700499 for (size_t i = 0; i < numCalls; i++) {
500 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000501 }
502
503 for (auto& t : ts) t.join();
504
505 size_t epochMsAfter = epochMillis();
506
Yifan Hong1f44f982021-10-08 17:16:47 -0700507 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000508
Steven Moreland68e2ee22024-09-18 01:18:48 +0000509 // b/272429574, b/365294257
510 // This flakes too much to test. Parallelization is tested
511 // in ThreadPoolGreaterThanEqualRequested and other tests.
512 // Test to make sure calls are handled in parallel.
513 // EXPECT_LE(epochMsAfter, epochMsBefore + (numCalls - 1) * sleepMs);
Yifan Hong1f44f982021-10-08 17:16:47 -0700514}
515
Andrei Homescua858b0e2022-08-01 23:43:09 +0000516TEST_P(BinderRpc, ThreadPoolOverSaturated) {
517 if (clientOrServerSingleThreaded()) {
518 GTEST_SKIP() << "This test requires multiple threads";
519 }
520
Yifan Hong1f44f982021-10-08 17:16:47 -0700521 constexpr size_t kNumThreads = 10;
522 constexpr size_t kNumCalls = kNumThreads + 3;
523 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000524
Steven Moreland68e2ee22024-09-18 01:18:48 +0000525 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 200 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700526}
527
Andrei Homescua858b0e2022-08-01 23:43:09 +0000528TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
529 if (clientOrServerSingleThreaded()) {
530 GTEST_SKIP() << "This test requires multiple threads";
531 }
532
Yifan Hong1f44f982021-10-08 17:16:47 -0700533 constexpr size_t kNumThreads = 20;
534 constexpr size_t kNumOutgoingConnections = 10;
535 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
536 auto proc = createRpcTestSocketServerProcess(
537 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000538
Steven Moreland68e2ee22024-09-18 01:18:48 +0000539 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 200 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000540}
541
Andrei Homescua858b0e2022-08-01 23:43:09 +0000542TEST_P(BinderRpc, ThreadingStressTest) {
543 if (clientOrServerSingleThreaded()) {
544 GTEST_SKIP() << "This test requires multiple threads";
545 }
546
Steven Moreland27f620a2023-03-06 19:44:36 +0000547 constexpr size_t kNumClientThreads = 5;
548 constexpr size_t kNumServerThreads = 5;
549 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000550
Steven Moreland4313d7e2021-07-15 23:41:22 +0000551 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000552
553 std::vector<std::thread> threads;
554 for (size_t i = 0; i < kNumClientThreads; i++) {
555 threads.push_back(std::thread([&] {
556 for (size_t j = 0; j < kNumCalls; j++) {
557 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000558 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000559 EXPECT_EQ(proc.rootBinder, out);
560 }
561 }));
562 }
563
564 for (auto& t : threads) t.join();
565}
566
Steven Moreland925ba0a2021-09-17 18:06:32 -0700567static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
568 std::vector<std::thread> threads;
569 for (size_t i = 0; i < threadCount; i++) {
570 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
571 }
572 for (auto& t : threads) t.join();
573}
574
Andrei Homescua858b0e2022-08-01 23:43:09 +0000575TEST_P(BinderRpc, OnewayStressTest) {
576 if (clientOrServerSingleThreaded()) {
577 GTEST_SKIP() << "This test requires multiple threads";
578 }
579
Steven Morelandc6046982021-04-20 00:49:42 +0000580 constexpr size_t kNumClientThreads = 10;
581 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700582 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000583
Steven Moreland4313d7e2021-07-15 23:41:22 +0000584 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000585
586 std::vector<std::thread> threads;
587 for (size_t i = 0; i < kNumClientThreads; i++) {
588 threads.push_back(std::thread([&] {
589 for (size_t j = 0; j < kNumCalls; j++) {
590 EXPECT_OK(proc.rootIface->sendString("a"));
591 }
Steven Morelandc6046982021-04-20 00:49:42 +0000592 }));
593 }
594
595 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700596
597 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000598}
599
Frederick Mayleb0221d12022-10-03 23:10:53 +0000600TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
601 if (!supportsFdTransport()) {
602 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
603 }
604 if (clientOrServerSingleThreaded()) {
605 GTEST_SKIP() << "This test requires multiple threads";
606 }
607
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000608 constexpr size_t kNumServerThreads = 3;
609
Frederick Mayleb0221d12022-10-03 23:10:53 +0000610 // This test forces a oneway transaction to be queued by issuing two
611 // `blockingSendFdOneway` calls, then drains the queue by issuing two
612 // `blockingRecvFd` calls.
613 //
614 // For more details about the queuing semantics see
615 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
616
617 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000618 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000619 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
620 .serverSupportedFileDescriptorTransportModes =
621 {RpcSession::FileDescriptorTransportMode::UNIX},
622 });
623
624 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
625 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
626 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
627 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
628
629 android::os::ParcelFileDescriptor fdA;
630 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
631 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700632 ASSERT_TRUE(ReadFdToString(fdA.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000633 EXPECT_EQ(result, "a");
634
635 android::os::ParcelFileDescriptor fdB;
636 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700637 ASSERT_TRUE(ReadFdToString(fdB.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000638 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000639
640 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000641}
642
Andrei Homescua858b0e2022-08-01 23:43:09 +0000643TEST_P(BinderRpc, OnewayCallQueueing) {
644 if (clientOrServerSingleThreaded()) {
645 GTEST_SKIP() << "This test requires multiple threads";
646 }
647
Frederick Mayle96872592023-03-07 14:56:15 -0800648 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000649 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000650
651 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000652 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000653
Frederick Mayle96872592023-03-07 14:56:15 -0800654 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700655 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800656 for (size_t i = 0; i + 1 < kNumQueued; i++) {
657 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000658 }
Frederick Mayle96872592023-03-07 14:56:15 -0800659 for (size_t i = 0; i + 1 < kNumQueued; i++) {
660 int n;
661 proc.rootIface->blockingRecvInt(&n);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700662 EXPECT_EQ(n, static_cast<ssize_t>(i));
Frederick Mayle96872592023-03-07 14:56:15 -0800663 }
Steven Morelandf5174272021-05-25 00:39:28 +0000664
Steven Moreland925ba0a2021-09-17 18:06:32 -0700665 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000666}
667
Andrei Homescua858b0e2022-08-01 23:43:09 +0000668TEST_P(BinderRpc, OnewayCallExhaustion) {
669 if (clientOrServerSingleThreaded()) {
670 GTEST_SKIP() << "This test requires multiple threads";
671 }
672
Steven Morelandd45be622021-06-04 02:19:37 +0000673 constexpr size_t kNumClients = 2;
674 constexpr size_t kTooLongMs = 1000;
675
Steven Moreland4313d7e2021-07-15 23:41:22 +0000676 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000677
678 // Build up oneway calls on the second session to make sure it terminates
679 // and shuts down. The first session should be unaffected (proc destructor
680 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000681 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000682
683 std::vector<std::thread> threads;
684 for (size_t i = 0; i < kNumClients; i++) {
685 // one of these threads will get stuck queueing a transaction once the
686 // socket fills up, the other will be able to fill up transactions on
687 // this object
688 threads.push_back(std::thread([&] {
689 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
690 }
691 }));
692 }
693 for (auto& t : threads) t.join();
694
695 Status status = iface->sleepMsAsync(kTooLongMs);
696 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
697
Steven Moreland798e0d12021-07-14 23:19:25 +0000698 // now that it has died, wait for the remote session to shutdown
699 std::vector<int32_t> remoteCounts;
700 do {
701 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
702 } while (remoteCounts.size() == kNumClients);
703
Steven Morelandd45be622021-06-04 02:19:37 +0000704 // the second session should be shutdown in the other process by the time we
705 // are able to join above (it'll only be hung up once it finishes processing
706 // any pending commands). We need to erase this session from the record
707 // here, so that the destructor for our session won't check that this
708 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000709 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000710}
711
Steven Moreland67f85902023-03-15 01:13:49 +0000712TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
713 if (clientOrServerSingleThreaded()) {
714 GTEST_SKIP() << "This test requires multiple threads";
715 }
716
717 // session 0 - will check for leaks in destrutor of proc
718 // session 1 - we want to make sure it gets deleted when we drop all references to it
719 auto proc = createRpcTestSocketServerProcess(
Tomasz Wasilczyk5da65602023-06-29 10:12:50 -0700720 {.numThreads = 1, .numSessions = 2, .numIncomingConnectionsBySession = {0, 1}});
Steven Moreland67f85902023-03-15 01:13:49 +0000721
722 wp<RpcSession> session = proc.proc->sessions.at(1).session;
723
724 // remove all references to the second session
725 proc.proc->sessions.at(1).root = nullptr;
726 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
727
728 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
729 // to drain commands.
730 for (size_t i = 0; i < 100; i++) {
731 usleep(10 * 1000);
732 if (session.promote() == nullptr) break;
733 }
734
735 EXPECT_EQ(nullptr, session.promote());
Steven Morelandb5d2b642023-05-04 00:31:45 +0000736
Steven Moreland0ebdaad2023-06-14 19:33:37 +0000737 // now that it has died, wait for the remote session to shutdown
738 std::vector<int32_t> remoteCounts;
739 do {
740 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
741 } while (remoteCounts.size() > 1);
Steven Moreland67f85902023-03-15 01:13:49 +0000742}
743
Devin Moore66d5b7a2022-07-07 21:42:10 +0000744TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000745 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000746 GTEST_SKIP() << "This test requires multiple threads";
747 }
748 class MyDeathRec : public IBinder::DeathRecipient {
749 public:
750 void binderDied(const wp<IBinder>& /* who */) override {
751 dead = true;
752 mCv.notify_one();
753 }
754 std::mutex mMtx;
755 std::condition_variable mCv;
756 bool dead = false;
757 };
758
759 // Death recipient needs to have an incoming connection to be called
760 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000761 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000762
763 auto dr = sp<MyDeathRec>::make();
764 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
765
766 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
767 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
768 }
769
770 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000771 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000772
773 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000774 // can't do this before checking the death recipient by calling
775 // forceShutdown earlier, because shutdownAndWait will also trigger
776 // a death recipient, but if we had a way to wait for the service
777 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000778 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000779 proc.expectAlreadyShutdown = true;
780}
781
782TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000783 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000784 GTEST_SKIP() << "This test requires multiple threads";
785 }
786 class MyDeathRec : public IBinder::DeathRecipient {
787 public:
788 void binderDied(const wp<IBinder>& /* who */) override {
789 dead = true;
790 mCv.notify_one();
791 }
792 std::mutex mMtx;
793 std::condition_variable mCv;
794 bool dead = false;
795 };
796
797 // Death recipient needs to have an incoming connection to be called
798 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000799 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000800
801 auto dr = sp<MyDeathRec>::make();
802 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
803
804 // Explicitly calling shutDownAndWait will cause the death recipients
805 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000806 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000807
808 std::unique_lock<std::mutex> lock(dr->mMtx);
809 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000810 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000811 }
812 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
813
Andrei Homescu96834632022-10-14 00:49:49 +0000814 proc.proc->terminate();
815 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000816 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
817 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
818 });
819 proc.expectAlreadyShutdown = true;
820}
821
Steven Moreland5ec743f2023-01-18 01:02:06 +0000822TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000823 if (socketType() == SocketType::TIPC) {
824 // This should work, but Trusty takes too long to restart the service
825 GTEST_SKIP() << "Service death test not supported on Trusty";
826 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000827 class MyDeathRec : public IBinder::DeathRecipient {
828 public:
829 void binderDied(const wp<IBinder>& /* who */) override {}
830 };
831
Steven Moreland67f85902023-03-15 01:13:49 +0000832 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000833
834 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000835 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000836}
837
838TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000839 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000840 GTEST_SKIP() << "This test requires multiple threads";
841 }
842 class MyDeathRec : public IBinder::DeathRecipient {
843 public:
844 void binderDied(const wp<IBinder>& /* who */) override {
845 GTEST_FAIL() << "This should not be called after unlinkToDeath";
846 }
847 };
848
849 // Death recipient needs to have an incoming connection to be called
850 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000851 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000852
853 auto dr = sp<MyDeathRec>::make();
854 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
855 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
856
Steven Moreland67f85902023-03-15 01:13:49 +0000857 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000858}
859
Steven Morelandc1635952021-04-01 16:20:47 +0000860TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000861 if (socketType() == SocketType::TIPC) {
862 // This should work, but Trusty takes too long to restart the service
863 GTEST_SKIP() << "Service death test not supported on Trusty";
864 }
865
Steven Moreland5553ac42020-11-11 02:14:45 +0000866 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000867 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000868
869 // make sure there is some state during crash
870 // 1. we hold their binder
871 sp<IBinderRpcSession> session;
872 EXPECT_OK(proc.rootIface->openSession("happy", &session));
873 // 2. they hold our binder
874 sp<IBinder> binder = new BBinder();
875 EXPECT_OK(proc.rootIface->holdBinder(binder));
876
877 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
878 << "Do death cleanup: " << doDeathCleanup;
879
Andrei Homescu96834632022-10-14 00:49:49 +0000880 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000881 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
882 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
883 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000884 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000885 }
886}
887
Steven Morelandd7302072021-05-15 01:32:04 +0000888TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000889 // This test only works if the current process shared the internal state of
890 // ProcessState with the service across the call to fork(). Both the static
891 // libraries and libbinder.so have their own separate copies of all the
892 // globals, so the test only works when the test client and service both use
893 // libbinder.so (when using static libraries, even a client and service
894 // using the same kind of static library should have separate copies of the
895 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000896 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000897 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
898 "at build time.";
899 }
900
Steven Moreland4313d7e2021-07-15 23:41:22 +0000901 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000902
Andrei Homescu2a298012022-06-15 01:08:54 +0000903 // we can't allocate IPCThreadState so actually the first time should
904 // succeed :(
905 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000906
907 // second time! we catch the error :)
908 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
909
Andrei Homescu96834632022-10-14 00:49:49 +0000910 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000911 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
912 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
913 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000914 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000915}
916
Frederick Mayle69a0c992022-05-26 20:38:39 +0000917TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000918 if (socketType() == SocketType::TIPC) {
919 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
920 }
921
Frederick Mayle69a0c992022-05-26 20:38:39 +0000922 auto proc = createRpcTestSocketServerProcess({
923 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
924 .serverSupportedFileDescriptorTransportModes =
925 {RpcSession::FileDescriptorTransportMode::UNIX},
926 .allowConnectFailure = true,
927 });
Andrei Homescu96834632022-10-14 00:49:49 +0000928 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
929 proc.proc->terminate();
930 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000931 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
932 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
933 });
934 proc.expectAlreadyShutdown = true;
935}
936
937TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000938 if (socketType() == SocketType::TIPC) {
939 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
940 }
941
Frederick Mayle69a0c992022-05-26 20:38:39 +0000942 auto proc = createRpcTestSocketServerProcess({
943 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
944 .serverSupportedFileDescriptorTransportModes =
945 {RpcSession::FileDescriptorTransportMode::NONE},
946 .allowConnectFailure = true,
947 });
Andrei Homescu96834632022-10-14 00:49:49 +0000948 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
949 proc.proc->terminate();
950 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000951 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
952 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
953 });
954 proc.expectAlreadyShutdown = true;
955}
956
957TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000958 if (socketType() == SocketType::TIPC) {
959 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
960 }
961
Frederick Mayle69a0c992022-05-26 20:38:39 +0000962 auto proc = createRpcTestSocketServerProcess({
963 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
964 .serverSupportedFileDescriptorTransportModes =
965 {RpcSession::FileDescriptorTransportMode::NONE,
966 RpcSession::FileDescriptorTransportMode::UNIX},
967 });
968
969 android::os::ParcelFileDescriptor out;
970 auto status = proc.rootIface->echoAsFile("hello", &out);
971 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
972}
973
974TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000975 if (socketType() == SocketType::TIPC) {
976 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
977 }
978
Frederick Mayle69a0c992022-05-26 20:38:39 +0000979 auto proc = createRpcTestSocketServerProcess({
980 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
981 .serverSupportedFileDescriptorTransportModes =
982 {RpcSession::FileDescriptorTransportMode::UNIX},
983 });
984
985 android::os::ParcelFileDescriptor out;
986 auto status = proc.rootIface->echoAsFile("hello", &out);
987 if (!supportsFdTransport()) {
988 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
989 return;
990 }
991 ASSERT_TRUE(status.isOk()) << status;
992
993 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700994 ASSERT_TRUE(ReadFdToString(out.get(), &result));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700995 ASSERT_EQ(result, "hello");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000996}
997
998TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000999 if (socketType() == SocketType::TIPC) {
1000 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1001 }
1002
Frederick Mayle69a0c992022-05-26 20:38:39 +00001003 auto proc = createRpcTestSocketServerProcess({
1004 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1005 .serverSupportedFileDescriptorTransportModes =
1006 {RpcSession::FileDescriptorTransportMode::UNIX},
1007 });
1008
1009 std::vector<android::os::ParcelFileDescriptor> files;
1010 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1011 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1012 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1013 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1014
1015 android::os::ParcelFileDescriptor out;
1016 auto status = proc.rootIface->concatFiles(files, &out);
1017 if (!supportsFdTransport()) {
1018 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1019 return;
1020 }
1021 ASSERT_TRUE(status.isOk()) << status;
1022
1023 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -07001024 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001025 EXPECT_EQ(result, "123abcd");
1026}
1027
1028TEST_P(BinderRpc, SendMaxFiles) {
1029 if (!supportsFdTransport()) {
1030 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1031 }
1032
1033 auto proc = createRpcTestSocketServerProcess({
1034 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1035 .serverSupportedFileDescriptorTransportModes =
1036 {RpcSession::FileDescriptorTransportMode::UNIX},
1037 });
1038
1039 std::vector<android::os::ParcelFileDescriptor> files;
1040 for (int i = 0; i < 253; i++) {
1041 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1042 }
1043
1044 android::os::ParcelFileDescriptor out;
1045 auto status = proc.rootIface->concatFiles(files, &out);
1046 ASSERT_TRUE(status.isOk()) << status;
1047
1048 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -07001049 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001050 EXPECT_EQ(result, std::string(253, 'a'));
1051}
1052
1053TEST_P(BinderRpc, SendTooManyFiles) {
1054 if (!supportsFdTransport()) {
1055 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1056 }
1057
1058 auto proc = createRpcTestSocketServerProcess({
1059 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1060 .serverSupportedFileDescriptorTransportModes =
1061 {RpcSession::FileDescriptorTransportMode::UNIX},
1062 });
1063
1064 std::vector<android::os::ParcelFileDescriptor> files;
1065 for (int i = 0; i < 254; i++) {
1066 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1067 }
1068
1069 android::os::ParcelFileDescriptor out;
1070 auto status = proc.rootIface->concatFiles(files, &out);
1071 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1072}
1073
Andrei Homescufc221502022-10-08 03:51:17 +00001074TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001075 if (socketType() == SocketType::TIPC) {
1076 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1077 }
1078
Andrei Homescufc221502022-10-08 03:51:17 +00001079 auto proc = createRpcTestSocketServerProcess({
1080 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1081 .serverSupportedFileDescriptorTransportModes =
1082 {RpcSession::FileDescriptorTransportMode::UNIX},
1083 });
1084
1085 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1086 ASSERT_NE(badFd, -1);
1087
1088 // Close the file descriptor so it becomes invalid for dup
1089 close(badFd);
1090
1091 Parcel p1;
1092 p1.markForBinder(proc.rootBinder);
1093 p1.writeInt32(3);
1094 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1095
1096 Parcel pRaw;
1097 pRaw.markForBinder(proc.rootBinder);
1098 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1099
1100 pRaw.setDataPosition(0);
1101 EXPECT_EQ(3, pRaw.readInt32());
1102 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1103}
1104
Andrei Homescu68a55612022-08-02 01:25:15 +00001105#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001106TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001107 if constexpr (!kEnableSharedLibs) {
1108 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1109 }
1110
Steven Moreland4313d7e2021-07-15 23:41:22 +00001111 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001112
1113 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1114 ASSERT_NE(binder, nullptr);
1115
1116 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1117}
1118
1119TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001120 if constexpr (!kEnableSharedLibs) {
1121 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1122 }
1123
Steven Moreland4313d7e2021-07-15 23:41:22 +00001124 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001125
1126 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1127 ASSERT_NE(binder, nullptr);
1128
1129 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1130 ASSERT_NE(ndkBinder, nullptr);
1131
1132 std::string out;
1133 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1134 ASSERT_TRUE(status.isOk()) << status.getDescription();
1135 ASSERT_EQ("aoeuaoeu", out);
1136}
Andrei Homescu68a55612022-08-02 01:25:15 +00001137#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001138
Steven Moreland5553ac42020-11-11 02:14:45 +00001139ssize_t countFds() {
1140 DIR* dir = opendir("/proc/self/fd/");
1141 if (dir == nullptr) return -1;
1142 ssize_t ret = 0;
1143 dirent* ent;
1144 while ((ent = readdir(dir)) != nullptr) ret++;
1145 closedir(dir);
1146 return ret;
1147}
1148
Andrei Homescua858b0e2022-08-01 23:43:09 +00001149TEST_P(BinderRpc, Fds) {
1150 if (serverSingleThreaded()) {
1151 GTEST_SKIP() << "This test requires multiple threads";
1152 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001153 if (socketType() == SocketType::TIPC) {
1154 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1155 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001156
Steven Moreland5553ac42020-11-11 02:14:45 +00001157 ssize_t beforeFds = countFds();
1158 ASSERT_GE(beforeFds, 0);
1159 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001160 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001161 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1162 }
1163 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1164}
1165
Devin Moore18f63752024-08-08 21:01:24 +00001166// TODO need to add IServiceManager.cpp/.h to libbinder_no_kernel
1167#ifdef BINDER_WITH_KERNEL_IPC
1168
1169class BinderRpcAccessor : public BinderRpc {
1170 void SetUp() override {
1171 if (serverSingleThreaded()) {
1172 // This blocks on android::FdTrigger::triggerablePoll when attempting to set
1173 // up the client RpcSession
1174 GTEST_SKIP() << "Accessors are not supported for single threaded libbinder";
1175 }
1176 if (rpcSecurity() == RpcSecurity::TLS) {
1177 GTEST_SKIP() << "Accessors are not supported with TLS";
1178 // ... for now
1179 }
1180
1181 if (socketType() == SocketType::UNIX_BOOTSTRAP) {
1182 GTEST_SKIP() << "Accessors do not support UNIX_BOOTSTRAP because no connection "
1183 "information is known";
1184 }
1185 if (socketType() == SocketType::TIPC) {
1186 GTEST_SKIP() << "Accessors do not support TIPC because the socket transport is not "
1187 "known in libbinder";
1188 }
1189 BinderRpc::SetUp();
1190 }
1191};
1192
1193inline void waitForExtraSessionCleanup(const BinderRpcTestProcessSession& proc) {
1194 // Need to give the server some time to delete its RpcSession after our last
1195 // reference is dropped, closing the connection. Check for up to 1 second,
1196 // every 10 ms.
1197 for (size_t i = 0; i < 100; i++) {
1198 std::vector<int32_t> remoteCounts;
1199 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1200 // We exect the original binder to still be alive, we just want to wait
1201 // for this extra session to be cleaned up.
1202 if (remoteCounts.size() == proc.proc->sessions.size()) break;
1203 usleep(10000);
1204 }
1205}
1206
1207TEST_P(BinderRpcAccessor, InjectAndGetServiceHappyPath) {
1208 constexpr size_t kNumThreads = 10;
1209 const String16 kInstanceName("super.cool.service/better_than_default");
1210
1211 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1212 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1213
Devin Moorec370db42024-08-09 23:18:05 +00001214 auto receipt = addAccessorProvider(
1215 {String8(kInstanceName).c_str()}, [&](const String16& name) -> sp<IBinder> {
1216 return createAccessor(name,
1217 [&](const String16& name, sockaddr* outAddr,
1218 socklen_t addrSize) -> status_t {
1219 if (outAddr == nullptr ||
1220 addrSize < proc.proc->sessions[0].addrLen) {
1221 return BAD_VALUE;
1222 }
1223 if (name == kInstanceName) {
1224 if (proc.proc->sessions[0].addr.ss_family ==
1225 AF_UNIX) {
1226 sockaddr_un* un = reinterpret_cast<sockaddr_un*>(
1227 &proc.proc->sessions[0].addr);
1228 ALOGE("inside callback: %s", un->sun_path);
1229 }
1230 std::memcpy(outAddr, &proc.proc->sessions[0].addr,
1231 proc.proc->sessions[0].addrLen);
1232 return OK;
1233 }
1234 return NAME_NOT_FOUND;
1235 });
1236 });
Devin Moore18f63752024-08-08 21:01:24 +00001237
1238 EXPECT_FALSE(receipt.expired());
1239
1240 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1241 sp<IBinderRpcTest> service = checked_interface_cast<IBinderRpcTest>(binder);
1242 EXPECT_NE(service, nullptr);
1243
1244 sp<IBinder> out;
1245 EXPECT_OK(service->repeatBinder(binder, &out));
1246 EXPECT_EQ(binder, out);
1247
1248 out.clear();
1249 binder.clear();
1250 service.clear();
1251
1252 status_t status = removeAccessorProvider(receipt);
1253 EXPECT_EQ(status, OK);
1254
1255 waitForExtraSessionCleanup(proc);
1256}
1257
1258TEST_P(BinderRpcAccessor, InjectNoAccessorProvided) {
1259 const String16 kInstanceName("doesnt_matter_nothing_checks");
1260
1261 bool isProviderDeleted = false;
1262
Devin Moorec370db42024-08-09 23:18:05 +00001263 auto receipt = addAccessorProvider({String8(kInstanceName).c_str()},
1264 [&](const String16&) -> sp<IBinder> { return nullptr; });
Devin Moore18f63752024-08-08 21:01:24 +00001265 EXPECT_FALSE(receipt.expired());
1266
1267 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1268 EXPECT_EQ(binder, nullptr);
1269
1270 status_t status = removeAccessorProvider(receipt);
1271 EXPECT_EQ(status, OK);
1272}
1273
Devin Moorec370db42024-08-09 23:18:05 +00001274TEST_P(BinderRpcAccessor, InjectDuplicateAccessorProvider) {
1275 const String16 kInstanceName("super.cool.service/better_than_default");
1276 const String16 kInstanceName2("super.cool.service/better_than_default2");
1277
1278 auto receipt =
1279 addAccessorProvider({String8(kInstanceName).c_str(), String8(kInstanceName2).c_str()},
1280 [&](const String16&) -> sp<IBinder> { return nullptr; });
1281 EXPECT_FALSE(receipt.expired());
1282 // reject this because it's associated with an already used instance name
1283 auto receipt2 = addAccessorProvider({String8(kInstanceName).c_str()},
1284 [&](const String16&) -> sp<IBinder> { return nullptr; });
1285 EXPECT_TRUE(receipt2.expired());
1286
1287 // the first provider should still be usable
1288 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1289 EXPECT_EQ(binder, nullptr);
1290
1291 status_t status = removeAccessorProvider(receipt);
1292 EXPECT_EQ(status, OK);
1293}
1294
1295TEST_P(BinderRpcAccessor, InjectAccessorProviderNoInstance) {
1296 auto receipt = addAccessorProvider({}, [&](const String16&) -> sp<IBinder> { return nullptr; });
1297 EXPECT_TRUE(receipt.expired());
1298}
1299
Devin Moore18f63752024-08-08 21:01:24 +00001300TEST_P(BinderRpcAccessor, InjectNoSockaddrProvided) {
1301 constexpr size_t kNumThreads = 10;
1302 const String16 kInstanceName("super.cool.service/better_than_default");
1303
1304 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1305 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1306
1307 bool isProviderDeleted = false;
1308 bool isAccessorDeleted = false;
1309
Devin Moorec370db42024-08-09 23:18:05 +00001310 auto receipt = addAccessorProvider({String8(kInstanceName).c_str()},
1311 [&](const String16& name) -> sp<IBinder> {
1312 return createAccessor(name,
1313 [&](const String16&, sockaddr*,
1314 socklen_t) -> status_t {
1315 // don't fill in outAddr
1316 return NAME_NOT_FOUND;
1317 });
1318 });
Devin Moore18f63752024-08-08 21:01:24 +00001319
1320 EXPECT_FALSE(receipt.expired());
1321
1322 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1323 EXPECT_EQ(binder, nullptr);
1324
1325 status_t status = removeAccessorProvider(receipt);
1326 EXPECT_EQ(status, OK);
1327}
1328
Devin Moorec370db42024-08-09 23:18:05 +00001329constexpr const char* kARpcInstance = "some.instance.name.IFoo/default";
1330const char* kARpcSupportedServices[] = {
1331 kARpcInstance,
1332};
1333const uint32_t kARpcNumSupportedServices = 1;
1334
1335struct ConnectionInfoData {
1336 sockaddr_storage addr;
1337 socklen_t len;
1338 bool* isDeleted;
1339 ~ConnectionInfoData() {
1340 if (isDeleted) *isDeleted = true;
1341 }
1342};
1343
1344struct AccessorProviderData {
1345 sockaddr_storage addr;
1346 socklen_t len;
1347 bool* isDeleted;
1348 ~AccessorProviderData() {
1349 if (isDeleted) *isDeleted = true;
1350 }
1351};
1352
1353void accessorProviderDataOnDelete(void* data) {
1354 delete reinterpret_cast<AccessorProviderData*>(data);
1355}
1356void infoProviderDataOnDelete(void* data) {
1357 delete reinterpret_cast<ConnectionInfoData*>(data);
1358}
1359
1360ABinderRpc_ConnectionInfo* infoProvider(const char* instance, void* cookie) {
1361 if (instance == nullptr || cookie == nullptr) return nullptr;
1362 ConnectionInfoData* data = reinterpret_cast<ConnectionInfoData*>(cookie);
1363 return ABinderRpc_ConnectionInfo_new(reinterpret_cast<const sockaddr*>(&data->addr), data->len);
1364}
1365
1366ABinderRpc_Accessor* getAccessor(const char* instance, void* cookie) {
1367 if (instance == nullptr || cookie == nullptr) return nullptr;
1368 if (0 != strcmp(instance, kARpcInstance)) return nullptr;
1369
1370 AccessorProviderData* data = reinterpret_cast<AccessorProviderData*>(cookie);
1371
1372 ConnectionInfoData* info = new ConnectionInfoData{
1373 .addr = data->addr,
1374 .len = data->len,
1375 .isDeleted = nullptr,
1376 };
1377
1378 return ABinderRpc_Accessor_new(instance, infoProvider, info, infoProviderDataOnDelete);
1379}
1380
1381class BinderARpcNdk : public ::testing::Test {};
1382
1383TEST_F(BinderARpcNdk, ARpcProviderNewDelete) {
1384 bool isDeleted = false;
1385
1386 AccessorProviderData* data = new AccessorProviderData{{}, 0, &isDeleted};
1387
1388 ABinderRpc_AccessorProvider* provider =
1389 ABinderRpc_registerAccessorProvider(getAccessor, kARpcSupportedServices,
1390 kARpcNumSupportedServices, data,
1391 accessorProviderDataOnDelete);
1392
1393 ASSERT_NE(provider, nullptr);
1394 EXPECT_FALSE(isDeleted);
1395
1396 ABinderRpc_unregisterAccessorProvider(provider);
1397
1398 EXPECT_TRUE(isDeleted);
1399}
1400
1401TEST_F(BinderARpcNdk, ARpcProviderDuplicateInstance) {
1402 const char* instance = "some.instance.name.IFoo/default";
1403 const uint32_t numInstances = 2;
1404 const char* instances[numInstances] = {
1405 instance,
1406 "some.other.instance/default",
1407 };
1408
1409 bool isDeleted = false;
1410
1411 AccessorProviderData* data = new AccessorProviderData{{}, 0, &isDeleted};
1412
1413 ABinderRpc_AccessorProvider* provider =
1414 ABinderRpc_registerAccessorProvider(getAccessor, instances, numInstances, data,
1415 accessorProviderDataOnDelete);
1416
1417 ASSERT_NE(provider, nullptr);
1418 EXPECT_FALSE(isDeleted);
1419
1420 const uint32_t numInstances2 = 1;
1421 const char* instances2[numInstances2] = {
1422 instance,
1423 };
1424 bool isDeleted2 = false;
1425 AccessorProviderData* data2 = new AccessorProviderData{{}, 0, &isDeleted2};
1426 ABinderRpc_AccessorProvider* provider2 =
1427 ABinderRpc_registerAccessorProvider(getAccessor, instances2, numInstances2, data2,
1428 accessorProviderDataOnDelete);
1429
1430 EXPECT_EQ(provider2, nullptr);
1431 // If it fails to be registered, the data is still cleaned up with
1432 // accessorProviderDataOnDelete
1433 EXPECT_TRUE(isDeleted2);
1434
1435 ABinderRpc_unregisterAccessorProvider(provider);
1436
1437 EXPECT_TRUE(isDeleted);
1438}
1439
1440TEST_F(BinderARpcNdk, ARpcProviderRegisterNoInstance) {
1441 const uint32_t numInstances = 0;
1442 const char* instances[numInstances] = {};
1443
1444 bool isDeleted = false;
1445 AccessorProviderData* data = new AccessorProviderData{{}, 0, &isDeleted};
1446
1447 ABinderRpc_AccessorProvider* provider =
1448 ABinderRpc_registerAccessorProvider(getAccessor, instances, numInstances, data,
1449 accessorProviderDataOnDelete);
1450 ASSERT_EQ(provider, nullptr);
1451}
1452
1453TEST_F(BinderARpcNdk, ARpcAccessorNewDelete) {
1454 bool isDeleted = false;
1455
1456 ConnectionInfoData* data = new ConnectionInfoData{{}, 0, &isDeleted};
1457
1458 ABinderRpc_Accessor* accessor =
1459 ABinderRpc_Accessor_new("gshoe_service", infoProvider, data, infoProviderDataOnDelete);
1460 ASSERT_NE(accessor, nullptr);
1461 EXPECT_FALSE(isDeleted);
1462
1463 ABinderRpc_Accessor_delete(accessor);
1464 EXPECT_TRUE(isDeleted);
1465}
1466
1467TEST_F(BinderARpcNdk, ARpcConnectionInfoNewDelete) {
1468 sockaddr_vm addr{
1469 .svm_family = AF_VSOCK,
1470 .svm_port = VMADDR_PORT_ANY,
1471 .svm_cid = VMADDR_CID_ANY,
1472 };
1473
1474 ABinderRpc_ConnectionInfo* info =
1475 ABinderRpc_ConnectionInfo_new(reinterpret_cast<sockaddr*>(&addr), sizeof(sockaddr_vm));
1476 EXPECT_NE(info, nullptr);
1477
1478 ABinderRpc_ConnectionInfo_delete(info);
1479}
1480
1481TEST_F(BinderARpcNdk, ARpcAsFromBinderAsBinder) {
1482 bool isDeleted = false;
1483
1484 ConnectionInfoData* data = new ConnectionInfoData{{}, 0, &isDeleted};
1485
1486 ABinderRpc_Accessor* accessor =
1487 ABinderRpc_Accessor_new("gshoe_service", infoProvider, data, infoProviderDataOnDelete);
1488 ASSERT_NE(accessor, nullptr);
1489 EXPECT_FALSE(isDeleted);
1490
1491 {
1492 ndk::SpAIBinder binder = ndk::SpAIBinder(ABinderRpc_Accessor_asBinder(accessor));
1493 EXPECT_NE(binder.get(), nullptr);
1494
1495 ABinderRpc_Accessor* accessor2 =
1496 ABinderRpc_Accessor_fromBinder("wrong_service_name", binder.get());
1497 // The API checks for the expected service name that is associated with
1498 // the accessor!
1499 EXPECT_EQ(accessor2, nullptr);
1500
1501 accessor2 = ABinderRpc_Accessor_fromBinder("gshoe_service", binder.get());
1502 EXPECT_NE(accessor2, nullptr);
1503
1504 // this is a new ABinderRpc_Accessor object that wraps the underlying
1505 // libbinder object.
1506 EXPECT_NE(accessor, accessor2);
1507
1508 ndk::SpAIBinder binder2 = ndk::SpAIBinder(ABinderRpc_Accessor_asBinder(accessor2));
1509 EXPECT_EQ(binder.get(), binder2.get());
1510
1511 ABinderRpc_Accessor_delete(accessor2);
1512 }
1513
1514 EXPECT_FALSE(isDeleted);
1515 ABinderRpc_Accessor_delete(accessor);
1516 EXPECT_TRUE(isDeleted);
1517}
1518
1519TEST_F(BinderARpcNdk, ARpcRequireProviderOnDeleteCallback) {
1520 EXPECT_EQ(nullptr,
1521 ABinderRpc_registerAccessorProvider(getAccessor, kARpcSupportedServices,
1522 kARpcNumSupportedServices,
1523 reinterpret_cast<void*>(1), nullptr));
1524}
1525
1526TEST_F(BinderARpcNdk, ARpcRequireInfoOnDeleteCallback) {
1527 EXPECT_EQ(nullptr,
1528 ABinderRpc_Accessor_new("the_best_service_name", infoProvider,
1529 reinterpret_cast<void*>(1), nullptr));
1530}
1531
1532TEST_F(BinderARpcNdk, ARpcNoDataNoProviderOnDeleteCallback) {
1533 ABinderRpc_AccessorProvider* provider =
1534 ABinderRpc_registerAccessorProvider(getAccessor, kARpcSupportedServices,
1535 kARpcNumSupportedServices, nullptr, nullptr);
1536 ASSERT_NE(nullptr, provider);
1537 ABinderRpc_unregisterAccessorProvider(provider);
1538}
1539
1540TEST_F(BinderARpcNdk, ARpcNoDataNoInfoOnDeleteCallback) {
1541 ABinderRpc_Accessor* accessor =
1542 ABinderRpc_Accessor_new("the_best_service_name", infoProvider, nullptr, nullptr);
1543 ASSERT_NE(nullptr, accessor);
1544 ABinderRpc_Accessor_delete(accessor);
1545}
1546
1547TEST_F(BinderARpcNdk, ARpcDoubleRemoveProvider) {
1548 ABinderRpc_AccessorProvider* provider =
1549 ABinderRpc_registerAccessorProvider(getAccessor, kARpcSupportedServices,
1550 kARpcNumSupportedServices, nullptr, nullptr);
1551 ASSERT_NE(nullptr, provider);
1552 ABinderRpc_unregisterAccessorProvider(provider);
1553 EXPECT_DEATH(ABinderRpc_unregisterAccessorProvider(provider), " was already unregistered");
1554}
1555
1556TEST_F(BinderARpcNdk, ARpcNullArgs_ConnectionInfo_new) {
1557 sockaddr_storage addr;
1558 EXPECT_EQ(nullptr, ABinderRpc_ConnectionInfo_new(reinterpret_cast<const sockaddr*>(&addr), 0));
1559}
1560
1561TEST_P(BinderRpcAccessor, ARpcGetService) {
1562 constexpr size_t kNumThreads = 10;
1563 bool isDeleted = false;
1564
1565 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1566 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1567
1568 AccessorProviderData* data =
1569 new AccessorProviderData{proc.proc->sessions[0].addr, proc.proc->sessions[0].addrLen,
1570 &isDeleted};
1571
1572 ABinderRpc_AccessorProvider* provider =
1573 ABinderRpc_registerAccessorProvider(getAccessor, kARpcSupportedServices,
1574 kARpcNumSupportedServices, data,
1575 accessorProviderDataOnDelete);
1576
1577 EXPECT_NE(provider, nullptr);
1578 EXPECT_FALSE(isDeleted);
1579
1580 {
1581 ndk::SpAIBinder binder = ndk::SpAIBinder(AServiceManager_checkService(kARpcInstance));
1582 ASSERT_NE(binder.get(), nullptr);
1583 EXPECT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1584 }
1585
1586 ABinderRpc_unregisterAccessorProvider(provider);
1587 EXPECT_TRUE(isDeleted);
1588
1589 waitForExtraSessionCleanup(proc);
1590}
1591
Devin Moore18f63752024-08-08 21:01:24 +00001592#endif // BINDER_WITH_KERNEL_IPC
1593
Andrei Homescud65666d2023-03-03 07:28:02 +00001594#ifdef BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandb469f432023-07-28 22:13:47 +00001595
1596static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() {
1597 std::vector<BinderRpc::ParamType> ret;
1598
1599 for (const auto& clientVersion : testVersions()) {
1600 for (const auto& serverVersion : testVersions()) {
1601 ret.push_back(BinderRpc::ParamType{
1602 .type = SocketType::TIPC,
1603 .security = RpcSecurity::RAW,
1604 .clientVersion = clientVersion,
1605 .serverVersion = serverVersion,
1606 .singleThreaded = true,
1607 .noKernel = true,
1608 });
1609 }
1610 }
1611
1612 return ret;
1613}
1614
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001615INSTANTIATE_TEST_SUITE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()),
1616 BinderRpc::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00001617#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Moreland9f250b02023-05-16 23:27:42 +00001618bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001619 // We don't need to enable TLS to know if vsock is supported.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001620 unique_fd serverFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001621 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Morelanda27311b2023-04-11 22:13:35 +00001622
1623 if (errno == EAFNOSUPPORT) {
1624 return false;
1625 }
1626
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -08001627 LOG_ALWAYS_FATAL_IF(!serverFd.ok(), "Could not create socket: %s", strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001628
1629 sockaddr_vm serverAddr{
1630 .svm_family = AF_VSOCK,
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001631 .svm_port = VMADDR_PORT_ANY,
Andrei Homescu992a4052022-06-28 21:26:18 +00001632 .svm_cid = VMADDR_CID_ANY,
1633 };
1634 int ret = TEMP_FAILURE_RETRY(
1635 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001636 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port VMADDR_PORT_ANY: %s",
Andrei Homescu992a4052022-06-28 21:26:18 +00001637 strerror(errno));
1638
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001639 socklen_t len = sizeof(serverAddr);
1640 ret = getsockname(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), &len);
1641 LOG_ALWAYS_FATAL_IF(0 != ret, "Failed to getsockname: %s", strerror(errno));
Hannah.Hsu6b1036f2024-07-09 11:20:20 +08001642 LOG_ALWAYS_FATAL_IF(len < static_cast<socklen_t>(sizeof(serverAddr)),
1643 "getsockname didn't read the full addr struct");
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001644
Andrei Homescu992a4052022-06-28 21:26:18 +00001645 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001646 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", serverAddr.svm_port,
Andrei Homescu992a4052022-06-28 21:26:18 +00001647 strerror(errno));
1648
1649 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1650 // to see if the kernel supports it. It's safe to use a blocking
1651 // connect because vsock sockets have a 2 second connection timeout,
1652 // and they return ETIMEDOUT after that.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001653 unique_fd connectFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001654 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001655 LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s",
1656 serverAddr.svm_port, strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001657
1658 bool success = false;
1659 sockaddr_vm connectAddr{
1660 .svm_family = AF_VSOCK,
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001661 .svm_port = serverAddr.svm_port,
Andrei Homescu992a4052022-06-28 21:26:18 +00001662 .svm_cid = VMADDR_CID_LOCAL,
1663 };
1664 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1665 sizeof(connectAddr)));
1666 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001667 unique_fd acceptFd;
Andrei Homescu992a4052022-06-28 21:26:18 +00001668 while (true) {
1669 pollfd pfd[]{
1670 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1671 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1672 };
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -08001673 ret = TEMP_FAILURE_RETRY(poll(pfd, countof(pfd), -1));
Andrei Homescu992a4052022-06-28 21:26:18 +00001674 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1675
1676 if (pfd[0].revents & POLLIN) {
1677 sockaddr_vm acceptAddr;
1678 socklen_t acceptAddrLen = sizeof(acceptAddr);
1679 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1680 reinterpret_cast<sockaddr*>(&acceptAddr),
1681 &acceptAddrLen, SOCK_CLOEXEC));
1682 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1683 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1684 "Truncated address");
1685
1686 // Store the fd in acceptFd so we keep the connection alive
1687 // while polling connectFd
1688 acceptFd.reset(ret);
1689 }
1690
1691 if (pfd[1].revents & POLLOUT) {
1692 // Connect either succeeded or timed out
1693 int connectErrno;
1694 socklen_t connectErrnoLen = sizeof(connectErrno);
1695 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1696 &connectErrnoLen);
1697 LOG_ALWAYS_FATAL_IF(ret == -1,
1698 "Could not getsockopt() after connect() "
1699 "on non-blocking socket: %s.",
1700 strerror(errno));
1701
1702 // We're done, this is all we wanted
1703 success = connectErrno == 0;
1704 break;
1705 }
1706 }
1707 } else {
1708 success = ret == 0;
1709 }
1710
1711 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1712
1713 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001714}
1715
Yifan Hong1deca4b2021-09-10 16:16:44 -07001716static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001717 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1718 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001719
1720 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001721
Steven Moreland9f250b02023-05-16 23:27:42 +00001722#ifdef __BIONIC__
1723 // Devices may not have vsock support. AVF tests will verify whether they do, but
1724 // we can't require it due to old kernels for the time being.
Steven Morelandda573042021-06-12 01:13:45 +00001725 static bool hasVsockLoopback = testSupportVsockLoopback();
Steven Moreland9f250b02023-05-16 23:27:42 +00001726#else
1727 // On host machines, we always assume we have vsock loopback. If we don't, the
1728 // subsequent failures will be more clear than showing one now.
1729 static bool hasVsockLoopback = true;
1730#endif
Steven Morelandda573042021-06-12 01:13:45 +00001731
1732 if (hasVsockLoopback) {
1733 ret.push_back(SocketType::VSOCK);
1734 }
1735
1736 return ret;
1737}
1738
Steven Morelandb469f432023-07-28 22:13:47 +00001739static std::vector<BinderRpc::ParamType> getBinderRpcParams() {
1740 std::vector<BinderRpc::ParamType> ret;
1741
Steven Morelandf7421432023-07-28 22:41:44 +00001742 constexpr bool full = false;
1743
Steven Morelandb469f432023-07-28 22:13:47 +00001744 for (const auto& type : testSocketTypes()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001745 if (full || type == SocketType::UNIX) {
1746 for (const auto& security : RpcSecurityValues()) {
1747 for (const auto& clientVersion : testVersions()) {
1748 for (const auto& serverVersion : testVersions()) {
1749 for (bool singleThreaded : {false, true}) {
Tomasz Wasilczyk2265ad92024-05-01 12:54:46 -07001750 for (bool noKernel : noKernelValues()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001751 ret.push_back(BinderRpc::ParamType{
1752 .type = type,
1753 .security = security,
1754 .clientVersion = clientVersion,
1755 .serverVersion = serverVersion,
1756 .singleThreaded = singleThreaded,
1757 .noKernel = noKernel,
1758 });
1759 }
Steven Morelandb469f432023-07-28 22:13:47 +00001760 }
1761 }
1762 }
1763 }
Steven Morelandf7421432023-07-28 22:41:44 +00001764 } else {
1765 ret.push_back(BinderRpc::ParamType{
1766 .type = type,
1767 .security = RpcSecurity::RAW,
1768 .clientVersion = RPC_WIRE_PROTOCOL_VERSION,
1769 .serverVersion = RPC_WIRE_PROTOCOL_VERSION,
1770 .singleThreaded = false,
Tomasz Wasilczyk2265ad92024-05-01 12:54:46 -07001771 .noKernel = !kEnableKernelIpcTesting,
Steven Morelandf7421432023-07-28 22:41:44 +00001772 });
Steven Morelandb469f432023-07-28 22:13:47 +00001773 }
1774 }
Steven Morelandf7421432023-07-28 22:41:44 +00001775
Steven Morelandb469f432023-07-28 22:13:47 +00001776 return ret;
1777}
1778
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001779INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()),
1780 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001781
Devin Moore18f63752024-08-08 21:01:24 +00001782#ifdef BINDER_WITH_KERNEL_IPC
1783INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpcAccessor, ::testing::ValuesIn(getBinderRpcParams()),
1784 BinderRpc::PrintParamInfo);
1785#endif // BINDER_WITH_KERNEL_IPC
1786
Yifan Hong702115c2021-06-24 15:39:18 -07001787class BinderRpcServerRootObject
1788 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001789
1790TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1791 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1792 auto setRootObject = [](bool isStrong) -> SetFn {
1793 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1794 };
1795
Yifan Hong702115c2021-06-24 15:39:18 -07001796 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001797 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001798 auto binder1 = sp<BBinder>::make();
1799 IBinder* binderRaw1 = binder1.get();
1800 setRootObject(isStrong1)(server.get(), binder1);
1801 EXPECT_EQ(binderRaw1, server->getRootObject());
1802 binder1.clear();
1803 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1804
1805 auto binder2 = sp<BBinder>::make();
1806 IBinder* binderRaw2 = binder2.get();
1807 setRootObject(isStrong2)(server.get(), binder2);
1808 EXPECT_EQ(binderRaw2, server->getRootObject());
1809 binder2.clear();
1810 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1811}
1812
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001813INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerRootObject,
1814 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1815 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001816
Yifan Hong1a235852021-05-13 16:07:47 -07001817class OneOffSignal {
1818public:
1819 // If notify() was previously called, or is called within |duration|, return true; else false.
1820 template <typename R, typename P>
1821 bool wait(std::chrono::duration<R, P> duration) {
1822 std::unique_lock<std::mutex> lock(mMutex);
1823 return mCv.wait_for(lock, duration, [this] { return mValue; });
1824 }
1825 void notify() {
1826 std::unique_lock<std::mutex> lock(mMutex);
1827 mValue = true;
1828 lock.unlock();
1829 mCv.notify_all();
1830 }
1831
1832private:
1833 std::mutex mMutex;
1834 std::condition_variable mCv;
1835 bool mValue = false;
1836};
1837
Yifan Hong194acf22021-06-29 18:44:56 -07001838TEST(BinderRpc, Java) {
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001839 bool expectDebuggable = false;
1840#if defined(__ANDROID__)
1841 expectDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1842 android::base::GetProperty("ro.build.type", "") != "user";
1843#else
Yifan Hong194acf22021-06-29 18:44:56 -07001844 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1845 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1846 "to binderHostDeviceTest. Hence, just disable this test on host.";
1847#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001848 if constexpr (!kEnableKernelIpc) {
1849 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1850 "at build time.";
1851 }
1852
Yifan Hong194acf22021-06-29 18:44:56 -07001853 sp<IServiceManager> sm = defaultServiceManager();
1854 ASSERT_NE(nullptr, sm);
1855 // Any Java service with non-empty getInterfaceDescriptor() would do.
Devin Moore29db8602024-08-14 22:21:04 +00001856 // Let's pick activity.
1857 auto binder = sm->checkService(String16("activity"));
Yifan Hong194acf22021-06-29 18:44:56 -07001858 ASSERT_NE(nullptr, binder);
1859 auto descriptor = binder->getInterfaceDescriptor();
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001860 ASSERT_GE(descriptor.size(), 0u);
Yifan Hong194acf22021-06-29 18:44:56 -07001861 ASSERT_EQ(OK, binder->pingBinder());
1862
1863 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001864 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001865 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001866 auto socket = rpcServer->releaseServer();
1867
1868 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001869 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1870
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001871 if (!expectDebuggable) {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001872 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001873 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1874 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001875 << statusToString(setRpcClientDebugStatus);
1876 GTEST_SKIP();
1877 }
1878
1879 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001880
1881 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001882 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001883 auto rpcBinder = rpcSession->getRootObject();
1884 ASSERT_NE(nullptr, rpcBinder);
1885
1886 ASSERT_EQ(OK, rpcBinder->pingBinder());
1887
1888 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1889 << "getInterfaceDescriptor should not crash system_server";
1890 ASSERT_EQ(OK, rpcBinder->pingBinder());
1891}
1892
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001893class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1894public:
1895 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001896 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001897 std::to_string(std::get<1>(info.param));
1898 }
1899};
1900
1901TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001902 unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001903 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001904 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001905 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001906 ASSERT_FALSE(server->hasServer());
1907 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1908 ASSERT_TRUE(server->hasServer());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001909 unique_fd retrieved = server->releaseServer();
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001910 ASSERT_FALSE(server->hasServer());
1911 ASSERT_EQ(sinkFd, retrieved.get());
1912}
1913
1914TEST_P(BinderRpcServerOnly, Shutdown) {
1915 if constexpr (!kEnableRpcThreads) {
1916 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1917 }
1918
1919 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001920 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001921 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001922 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1923 auto joinEnds = std::make_shared<OneOffSignal>();
1924
1925 // If things are broken and the thread never stops, don't block other tests. Because the thread
1926 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1927 // shared pointers are passed.
1928 std::thread([server, joinEnds] {
1929 server->join();
1930 joinEnds->notify();
1931 }).detach();
1932
1933 bool shutdown = false;
1934 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001935 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001936 if (server->shutdown()) shutdown = true;
1937 }
1938 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1939
1940 ASSERT_TRUE(joinEnds->wait(2s))
1941 << "After server->shutdown() returns true, join() did not stop after 2s";
1942}
1943
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001944INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerOnly,
1945 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1946 ::testing::ValuesIn(testVersions())),
1947 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001948
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001949class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001950public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001951 // Only parameterized only server version because `RpcSession` is bypassed
1952 // in the client half of the tests.
1953 using Param =
1954 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001955 using ConnectToServer = std::function<unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001956
1957 // A server that handles client socket connections.
1958 class Server {
1959 public:
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001960 using AcceptConnection = std::function<unique_fd(Server*)>;
David Brazdil21c887c2022-09-23 12:25:18 +01001961
Yifan Hong1deca4b2021-09-10 16:16:44 -07001962 explicit Server() {}
1963 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001964 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001965 [[nodiscard]] AssertionResult setUp(
1966 const Param& param,
1967 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001968 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001969 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Steven Morelandca3f6382023-05-11 23:23:26 +00001970 if (!rpcServer->setProtocolVersion(serverVersion)) {
1971 return AssertionFailure() << "Invalid protocol version: " << serverVersion;
1972 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001973 switch (socketType) {
1974 case SocketType::PRECONNECTED: {
1975 return AssertionFailure() << "Not supported by this test";
1976 } break;
1977 case SocketType::UNIX: {
1978 auto addr = allocateSocketAddress();
1979 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1980 if (status != OK) {
1981 return AssertionFailure()
1982 << "setupUnixDomainServer: " << statusToString(status);
1983 }
1984 mConnectToServer = [addr] {
1985 return connectTo(UnixSocketAddress(addr.c_str()));
1986 };
1987 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001988 case SocketType::UNIX_BOOTSTRAP: {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001989 unique_fd bootstrapFdClient, bootstrapFdServer;
1990 if (!binder::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001991 return AssertionFailure() << "Socketpair() failed";
1992 }
1993 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1994 std::move(bootstrapFdServer));
1995 if (status != OK) {
1996 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1997 << statusToString(status);
1998 }
1999 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
2000 mAcceptConnection = &Server::recvmsgServerConnection;
2001 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
2002 } break;
Alice Wang893a9912022-10-24 10:44:09 +00002003 case SocketType::UNIX_RAW: {
2004 auto addr = allocateSocketAddress();
2005 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
2006 if (status != OK) {
2007 return AssertionFailure()
2008 << "setupRawSocketServer: " << statusToString(status);
2009 }
2010 mConnectToServer = [addr] {
2011 return connectTo(UnixSocketAddress(addr.c_str()));
2012 };
2013 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002014 case SocketType::VSOCK: {
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07002015 unsigned port;
2016 auto status =
2017 rpcServer->setupVsockServer(VMADDR_CID_LOCAL, VMADDR_PORT_ANY, &port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002018 if (status != OK) {
2019 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
2020 }
2021 mConnectToServer = [port] {
2022 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
2023 };
2024 } break;
2025 case SocketType::INET: {
2026 unsigned int port;
2027 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
2028 if (status != OK) {
2029 return AssertionFailure() << "setupInetServer: " << statusToString(status);
2030 }
2031 mConnectToServer = [port] {
2032 const char* addr = kLocalInetAddress;
2033 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002034 if (aiStart == nullptr) return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07002035 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
2036 auto fd = connectTo(
2037 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
2038 if (fd.ok()) return fd;
2039 }
2040 ALOGE("None of the socket address resolved for %s:%u can be connected",
2041 addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002042 return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07002043 };
Andrei Homescu68a55612022-08-02 01:25:15 +00002044 } break;
2045 case SocketType::TIPC: {
2046 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
2047 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002048 }
2049 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00002050 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00002051 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07002052 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
2053 mSetup = true;
2054 return AssertionSuccess();
2055 }
2056 RpcTransportCtx* getCtx() const { return mCtx.get(); }
2057 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
2058 return mCertVerifier;
2059 }
2060 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
2061 void start() {
2062 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
2063 mThread = std::make_unique<std::thread>(&Server::run, this);
2064 }
David Brazdil21c887c2022-09-23 12:25:18 +01002065
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002066 unique_fd acceptServerConnection() {
2067 return unique_fd(TEMP_FAILURE_RETRY(
David Brazdil21c887c2022-09-23 12:25:18 +01002068 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
2069 }
2070
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002071 unique_fd recvmsgServerConnection() {
2072 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +01002073 int buf;
2074 iovec iov{&buf, sizeof(buf)};
2075
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +00002076 if (binder::os::receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002077 PLOGF("Failed receiveMessage");
David Brazdil21c887c2022-09-23 12:25:18 +01002078 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002079 LOG_ALWAYS_FATAL_IF(fds.size() != 1, "Expected one FD from receiveMessage(), got %zu",
2080 fds.size());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002081 return std::move(std::get<unique_fd>(fds[0]));
David Brazdil21c887c2022-09-23 12:25:18 +01002082 }
2083
Yifan Hong1deca4b2021-09-10 16:16:44 -07002084 void run() {
2085 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
2086
2087 std::vector<std::thread> threads;
2088 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002089 unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002090 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
2091 }
2092
2093 for (auto& thread : threads) thread.join();
2094 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002095 void handleOne(unique_fd acceptedFd) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07002096 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00002097 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00002098 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07002099 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07002100 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002101 }
Yifan Honge07d2732021-09-13 21:59:14 -07002102 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07002103 shutdown();
2104 join();
2105 }
2106 void shutdown() { mFdTrigger->trigger(); }
2107
2108 void setPostConnect(
2109 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
2110 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002111 }
2112
2113 private:
2114 std::unique_ptr<std::thread> mThread;
2115 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01002116 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002117 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01002118 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002119 std::unique_ptr<RpcTransportCtx> mCtx;
2120 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
2121 std::make_shared<RpcCertificateVerifierSimple>();
2122 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07002123 // The function invoked after connection and handshake. By default, it is
2124 // |defaultPostConnect| that sends |kMessage| to the client.
2125 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
2126 Server::defaultPostConnect;
2127
2128 void join() {
2129 if (mThread != nullptr) {
2130 mThread->join();
2131 mThread = nullptr;
2132 }
2133 }
2134
2135 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
2136 FdTrigger* fdTrigger) {
2137 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002138 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00002139 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00002140 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002141 if (status != OK) return AssertionFailure() << statusToString(status);
2142 return AssertionSuccess();
2143 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002144 };
2145
2146 class Client {
2147 public:
2148 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
2149 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002150 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002151 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
2152 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002153 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00002154 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07002155 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
2156 return AssertionSuccess();
2157 }
2158 RpcTransportCtx* getCtx() const { return mCtx.get(); }
2159 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
2160 return mCertVerifier;
2161 }
Yifan Hong67519322021-09-13 18:51:16 -07002162 // connect() and do handshake
2163 bool setUpTransport() {
2164 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00002165 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07002166 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
2167 return mClientTransport != nullptr;
2168 }
2169 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
2170 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
2171 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002172 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00002173 status_t readStatus =
2174 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00002175 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002176 if (readStatus != OK) {
2177 return AssertionFailure() << statusToString(readStatus);
2178 }
2179 if (readMessage != expectedMessage) {
2180 return AssertionFailure()
2181 << "Expected " << expectedMessage << ", actual " << readMessage;
2182 }
2183 return AssertionSuccess();
2184 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002185 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07002186 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07002187 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
2188 return;
2189 }
2190 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07002191 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07002192 }
2193
Pawan49d74cb2022-08-03 21:19:11 +00002194 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
2195
Yifan Hong1deca4b2021-09-10 16:16:44 -07002196 private:
2197 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00002198 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002199 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
2200 std::unique_ptr<RpcTransportCtx> mCtx;
2201 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
2202 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07002203 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002204 };
2205
2206 // Make A trust B.
2207 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002208 static status_t trust(RpcSecurity rpcSecurity,
2209 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
2210 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07002211 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07002212 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
2213 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
2214 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002215 }
2216
2217 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002218};
2219
2220class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
2221public:
2222 using Server = RpcTransportTestUtils::Server;
2223 using Client = RpcTransportTestUtils::Client;
2224 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002225 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00002226 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002227 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00002228 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002229 return ret;
2230 }
2231 static std::vector<ParamType> getRpcTranportTestParams() {
2232 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00002233 for (auto serverVersion : testVersions()) {
2234 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
2235 for (auto rpcSecurity : RpcSecurityValues()) {
2236 switch (rpcSecurity) {
2237 case RpcSecurity::RAW: {
2238 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
2239 } break;
2240 case RpcSecurity::TLS: {
2241 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
2242 serverVersion);
2243 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
2244 serverVersion);
2245 } break;
2246 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002247 }
2248 }
2249 }
2250 return ret;
2251 }
2252 template <typename A, typename B>
2253 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002254 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2255 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002256 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
2257 }
Andrei Homescu12106de2022-04-27 04:42:21 +00002258 void SetUp() override {
2259 if constexpr (!kEnableRpcThreads) {
2260 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2261 }
2262 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002263};
2264
2265TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002266 auto server = std::make_unique<Server>();
2267 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002268
2269 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002270 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002271
2272 ASSERT_EQ(OK, trust(&client, server));
2273 ASSERT_EQ(OK, trust(server, &client));
2274
2275 server->start();
2276 client.run();
2277}
2278
2279TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002280 auto server = std::make_unique<Server>();
2281 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002282
2283 std::vector<Client> clients;
2284 for (int i = 0; i < 2; i++) {
2285 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002286 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002287 ASSERT_EQ(OK, trust(&client, server));
2288 ASSERT_EQ(OK, trust(server, &client));
2289 }
2290
2291 server->start();
2292 for (auto& client : clients) client.run();
2293}
2294
2295TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002296 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2297 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002298
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002299 auto untrustedServer = std::make_unique<Server>();
2300 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002301
2302 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002303 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002304
2305 ASSERT_EQ(OK, trust(untrustedServer, &client));
2306
2307 untrustedServer->start();
2308
2309 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2310 // the client can't verify the server's identity.
2311 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2312 client.run(handshakeOk);
2313}
2314TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002315 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2316 (void)serverVersion;
2317
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002318 auto validServer = std::make_unique<Server>();
2319 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002320
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002321 auto maliciousServer = std::make_unique<Server>();
2322 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002323
2324 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002325 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002326
2327 ASSERT_EQ(OK, trust(&client, validServer));
2328 ASSERT_EQ(OK, trust(validServer, &client));
2329 ASSERT_EQ(OK, trust(maliciousServer, &client));
2330
2331 maliciousServer->start();
2332
2333 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2334 // the client can't verify the server's identity.
2335 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2336 client.run(handshakeOk);
2337}
2338
2339TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002340 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2341 (void)serverVersion;
2342
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002343 auto server = std::make_unique<Server>();
2344 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002345
2346 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002347 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002348
2349 ASSERT_EQ(OK, trust(&client, server));
2350
2351 server->start();
2352
2353 // For TLS, Client should be able to verify server's identity, so client should see
2354 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2355 // identity and should drop the connection, so client shouldn't be able to read anything.
2356 bool readOk = rpcSecurity != RpcSecurity::TLS;
2357 client.run(true, readOk);
2358}
2359
2360TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002361 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2362 (void)serverVersion;
2363
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002364 auto server = std::make_unique<Server>();
2365 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002366
2367 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002368 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002369 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002370 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002371
2372 ASSERT_EQ(OK, trust(&validClient, server));
2373 ASSERT_EQ(OK, trust(&maliciousClient, server));
2374
2375 server->start();
2376
2377 // See UntrustedClient.
2378 bool readOk = rpcSecurity != RpcSecurity::TLS;
2379 maliciousClient.run(true, readOk);
2380}
2381
Yifan Hong67519322021-09-13 18:51:16 -07002382TEST_P(RpcTransportTest, Trigger) {
2383 std::string msg2 = ", world!";
2384 std::mutex writeMutex;
2385 std::condition_variable writeCv;
2386 bool shouldContinueWriting = false;
2387 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002388 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002389 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002390 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2391 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002392 if (status != OK) return AssertionFailure() << statusToString(status);
2393
2394 {
2395 std::unique_lock<std::mutex> lock(writeMutex);
2396 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2397 return AssertionFailure() << "write barrier not cleared in time!";
2398 }
2399 }
2400
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002401 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002402 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2403 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002404 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002405 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002406 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002407 << statusToString(status);
2408 return AssertionSuccess();
2409 };
2410
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002411 auto server = std::make_unique<Server>();
2412 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002413
2414 // Set up client
2415 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002416 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002417
2418 // Exchange keys
2419 ASSERT_EQ(OK, trust(&client, server));
2420 ASSERT_EQ(OK, trust(server, &client));
2421
2422 server->setPostConnect(serverPostConnect);
2423
Yifan Hong67519322021-09-13 18:51:16 -07002424 server->start();
2425 // connect() to server and do handshake
2426 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002427 // read the first message. This ensures that server has finished handshake and start handling
2428 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002429 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002430 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2431 // write is on an FdTrigger that has been shut down.
2432 server->shutdown();
2433 // Continues server thread to write the second message.
2434 {
Yifan Hong22211f82021-09-14 12:32:25 -07002435 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002436 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002437 }
Yifan Hong22211f82021-09-14 12:32:25 -07002438 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002439 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002440 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002441 // On the client side, second read fails with DEAD_OBJECT
2442 ASSERT_FALSE(client.readMessage(msg2));
2443}
2444
Pawan49d74cb2022-08-03 21:19:11 +00002445TEST_P(RpcTransportTest, CheckWaitingForRead) {
2446 std::mutex readMutex;
2447 std::condition_variable readCv;
2448 bool shouldContinueReading = false;
2449 // Server will write data on transport once its started
2450 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
2451 std::string message(RpcTransportTestUtils::kMessage);
2452 iovec messageIov{message.data(), message.size()};
2453 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2454 std::nullopt, nullptr);
2455 if (status != OK) return AssertionFailure() << statusToString(status);
2456
2457 {
2458 std::unique_lock<std::mutex> lock(readMutex);
2459 shouldContinueReading = true;
2460 lock.unlock();
2461 readCv.notify_all();
2462 }
2463 return AssertionSuccess();
2464 };
2465
2466 // Setup Server and client
2467 auto server = std::make_unique<Server>();
2468 ASSERT_TRUE(server->setUp(GetParam()));
2469
2470 Client client(server->getConnectToServerFn());
2471 ASSERT_TRUE(client.setUp(GetParam()));
2472
2473 ASSERT_EQ(OK, trust(&client, server));
2474 ASSERT_EQ(OK, trust(server, &client));
2475 server->setPostConnect(serverPostConnect);
2476
2477 server->start();
2478 ASSERT_TRUE(client.setUpTransport());
2479 {
2480 // Wait till server writes data
2481 std::unique_lock<std::mutex> lock(readMutex);
2482 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2483 }
2484
2485 // Since there is no read polling here, we will get polling count 0
2486 ASSERT_FALSE(client.isTransportWaiting());
2487 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2488 // Thread should increment polling count, read and decrement polling count
2489 // Again, polling count should be zero here
2490 ASSERT_FALSE(client.isTransportWaiting());
2491
2492 server->shutdown();
2493}
2494
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002495INSTANTIATE_TEST_SUITE_P(BinderRpc, RpcTransportTest,
2496 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
2497 RpcTransportTest::PrintParamInfo);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002498
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002499class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002500 : public testing::TestWithParam<
2501 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002502public:
2503 template <typename A, typename B>
2504 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002505 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2506 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002507 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2508 }
2509 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002510 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2511 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2512 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002513 };
2514};
2515
2516TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002517 if constexpr (!kEnableRpcThreads) {
2518 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2519 }
2520
Frederick Mayledc07cf82022-05-26 20:30:12 +00002521 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002522
2523 std::vector<uint8_t> pkeyData, certData;
2524 {
2525 auto pkey = makeKeyPairForSelfSignedCert();
2526 ASSERT_NE(nullptr, pkey);
2527 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2528 ASSERT_NE(nullptr, cert);
2529 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2530 certData = serializeCertificate(cert.get(), certificateFormat);
2531 }
2532
2533 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2534 auto desCert = deserializeCertificate(certData, certificateFormat);
2535 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002536 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2537 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002538
2539 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2540 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2541
2542 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2543 ASSERT_TRUE(client.setUp(utilsParam));
2544
2545 ASSERT_EQ(OK, trust(&client, server));
2546 ASSERT_EQ(OK, trust(server, &client));
2547
2548 server->start();
2549 client.run();
2550}
2551
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002552INSTANTIATE_TEST_SUITE_P(
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002553 BinderRpc, RpcTransportTlsKeyTest,
2554 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2555 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002556 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2557 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002558 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00002559#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002560
Steven Morelandc1635952021-04-01 16:20:47 +00002561} // namespace android
2562
2563int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002564 ::testing::InitGoogleTest(&argc, argv);
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002565 __android_log_set_logger(__android_log_stderr_logger);
Steven Morelanda83191d2021-10-27 10:14:53 -07002566
Steven Moreland5553ac42020-11-11 02:14:45 +00002567 return RUN_ALL_TESTS();
2568}