blob: 1ff1de4db870be62356d9f007ab31040c68a4d6d [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
Andrei Homescu9d8adb12022-08-02 04:38:30 +000017#include <aidl/IBinderRpcTest.h>
Frederick Maylea12b0962022-06-25 01:13:22 +000018#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000019
Steven Morelandc1635952021-04-01 16:20:47 +000020#include <chrono>
21#include <cstdlib>
22#include <iostream>
23#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000024#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000025
Andrei Homescu2a298012022-06-15 01:08:54 +000026#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070027#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000029#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000030
Andrei Homescud65666d2023-03-03 07:28:02 +000031#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000032#include <binder/RpcTransportTipcAndroid.h>
33#include <trusty/tipc.h>
Andrei Homescud65666d2023-03-03 07:28:02 +000034#endif // BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000035
Andrei Homescu2a298012022-06-15 01:08:54 +000036#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000037#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000038
Yifan Hong1a235852021-05-13 16:07:47 -070039using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070040using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070041using testing::AssertionFailure;
42using testing::AssertionResult;
43using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070044
Steven Moreland5553ac42020-11-11 02:14:45 +000045namespace android {
46
Andrei Homescu12106de2022-04-27 04:42:21 +000047#ifdef BINDER_TEST_NO_SHARED_LIBS
48constexpr bool kEnableSharedLibs = false;
49#else
50constexpr bool kEnableSharedLibs = true;
51#endif
52
Andrei Homescud65666d2023-03-03 07:28:02 +000053#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000054constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
55#endif
56
Frederick Maylea12b0962022-06-25 01:13:22 +000057static std::string WaitStatusToString(int wstatus) {
58 if (WIFEXITED(wstatus)) {
59 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
60 }
61 if (WIFSIGNALED(wstatus)) {
62 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
63 }
64 return base::StringPrintf("unexpected state %d", wstatus);
65}
66
Steven Moreland276d8df2022-09-28 23:56:39 +000067static void debugBacktrace(pid_t pid) {
68 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
69 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
70}
71
Steven Moreland5553ac42020-11-11 02:14:45 +000072class Process {
73public:
Andrei Homescu96834632022-10-14 00:49:49 +000074 Process(Process&& other)
75 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
76 mReadEnd(std::move(other.mReadEnd)),
77 mWriteEnd(std::move(other.mWriteEnd)) {
78 // The default move constructor doesn't clear mPid after moving it,
79 // which we need to do because the destructor checks for mPid!=0
80 mPid = other.mPid;
81 other.mPid = 0;
82 }
Yifan Hong1deca4b2021-09-10 16:16:44 -070083 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
84 android::base::borrowed_fd /* readEnd */)>& f) {
85 android::base::unique_fd childWriteEnd;
86 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +000087 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
88 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +000089 if (0 == (mPid = fork())) {
90 // racey: assume parent doesn't crash before this is set
91 prctl(PR_SET_PDEATHSIG, SIGHUP);
92
Yifan Hong1deca4b2021-09-10 16:16:44 -070093 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +000094
95 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +000096 }
97 }
98 ~Process() {
99 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000100 int wstatus;
101 waitpid(mPid, &wstatus, 0);
102 if (mCustomExitStatusCheck) {
103 mCustomExitStatusCheck(wstatus);
104 } else {
105 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
106 << "server process failed: " << WaitStatusToString(wstatus);
107 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000108 }
109 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700110 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700111 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000112
Frederick Maylea12b0962022-06-25 01:13:22 +0000113 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
114 mCustomExitStatusCheck = std::move(f);
115 }
116
Frederick Mayle69a0c992022-05-26 20:38:39 +0000117 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
118 void terminate() { kill(mPid, SIGTERM); }
119
Steven Moreland276d8df2022-09-28 23:56:39 +0000120 pid_t getPid() { return mPid; }
121
Steven Moreland5553ac42020-11-11 02:14:45 +0000122private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000123 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000124 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700125 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700126 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000127};
128
129static std::string allocateSocketAddress() {
130 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000131 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000132 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700133 unlink(ret.c_str());
134 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000135};
136
Steven Morelandda573042021-06-12 01:13:45 +0000137static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000138 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000139 return vsockPort++;
140}
141
Alice Wang893a9912022-10-24 10:44:09 +0000142static base::unique_fd initUnixSocket(std::string addr) {
143 auto socket_addr = UnixSocketAddress(addr.c_str());
144 base::unique_fd fd(
145 TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
146 CHECK(fd.ok());
147 CHECK_EQ(0, TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize())));
148 return fd;
149}
150
Andrei Homescu96834632022-10-14 00:49:49 +0000151// Destructors need to be defined, even if pure virtual
152ProcessSession::~ProcessSession() {}
153
154class LinuxProcessSession : public ProcessSession {
155public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000156 // reference to process hosting a socket server
157 Process host;
158
Andrei Homescu96834632022-10-14 00:49:49 +0000159 LinuxProcessSession(LinuxProcessSession&&) = default;
160 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
161 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000162 for (auto& session : sessions) {
163 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000164 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000165
Steven Moreland67f85902023-03-15 01:13:49 +0000166 for (size_t sessionNum = 0; sessionNum < sessions.size(); sessionNum++) {
167 auto& info = sessions.at(sessionNum);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000168 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000169
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000170 EXPECT_NE(nullptr, session);
171 EXPECT_NE(nullptr, session->state());
172 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000173
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000174 wp<RpcSession> weakSession = session;
175 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000176
Steven Moreland57042712022-10-04 23:56:45 +0000177 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
178 // the object should not actually be promotable. By looping, we distinguish a race here
179 // from a bug causing the object to not be promotable.
180 for (size_t i = 0; i < 3; i++) {
181 sp<RpcSession> strongSession = weakSession.promote();
182 EXPECT_EQ(nullptr, strongSession)
Steven Moreland67f85902023-03-15 01:13:49 +0000183 << "For session " << sessionNum << ". "
Steven Moreland57042712022-10-04 23:56:45 +0000184 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
185 "Leaked sess: ")
186 << strongSession->getStrongCount() << " checked time " << i;
187
188 if (strongSession != nullptr) {
189 sleep(1);
190 }
191 }
Steven Moreland736664b2021-05-01 04:27:25 +0000192 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000193 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000194
Andrei Homescu96834632022-10-14 00:49:49 +0000195 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
196 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000197 }
Andrei Homescu96834632022-10-14 00:49:49 +0000198
199 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000200};
201
Yifan Hong1deca4b2021-09-10 16:16:44 -0700202static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700203 base::unique_fd serverFd(
204 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
205 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700206 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
207 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700208
209 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
210 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700211 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
212 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700213 }
214 return serverFd;
215}
216
Andrei Homescud65666d2023-03-03 07:28:02 +0000217#ifndef BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100218static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
219 base::unique_fd sockClient, sockServer;
220 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
221 int savedErrno = errno;
222 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
223 }
224
225 int zero = 0;
226 iovec iov{&zero, sizeof(zero)};
227 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
228 fds.emplace_back(std::move(sockServer));
229
230 if (sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
231 int savedErrno = errno;
232 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
233 }
234 return std::move(sockClient);
235}
Andrei Homescud65666d2023-03-03 07:28:02 +0000236#endif // BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100237
Andrei Homescuf30148c2023-03-10 00:31:45 +0000238std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
239 return newTlsFactory(rpcSecurity);
Andrei Homescu96834632022-10-14 00:49:49 +0000240}
Andrei Homescu2a298012022-06-15 01:08:54 +0000241
Andrei Homescu96834632022-10-14 00:49:49 +0000242// This creates a new process serving an interface on a certain number of
243// threads.
244std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
245 const BinderRpcOptions& options) {
246 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000247
Steven Moreland67f85902023-03-15 01:13:49 +0000248 if (options.numIncomingConnectionsBySession.size() != 0) {
249 CHECK_EQ(options.numIncomingConnectionsBySession.size(), options.numSessions);
250 }
251
Andrei Homescu96834632022-10-14 00:49:49 +0000252 SocketType socketType = std::get<0>(GetParam());
253 RpcSecurity rpcSecurity = std::get<1>(GetParam());
254 uint32_t clientVersion = std::get<2>(GetParam());
255 uint32_t serverVersion = std::get<3>(GetParam());
256 bool singleThreaded = std::get<4>(GetParam());
257 bool noKernel = std::get<5>(GetParam());
258
259 std::string path = android::base::GetExecutableDirectory();
260 auto servicePath = android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
261 singleThreaded ? "_single_threaded" : "",
262 noKernel ? "_no_kernel" : "");
263
Alice Wang1ef010b2022-11-14 09:09:25 +0000264 base::unique_fd bootstrapClientFd, socketFd;
265
Alice Wang893a9912022-10-24 10:44:09 +0000266 auto addr = allocateSocketAddress();
267 // Initializes the socket before the fork/exec.
268 if (socketType == SocketType::UNIX_RAW) {
269 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000270 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
271 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
272 // This is because we cannot pass ParcelFileDescriptor over a pipe.
273 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
274 int savedErrno = errno;
275 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
276 }
Alice Wang893a9912022-10-24 10:44:09 +0000277 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000278
Andrei Homescu96834632022-10-14 00:49:49 +0000279 auto ret = std::make_unique<LinuxProcessSession>(
280 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000281 if (socketType == SocketType::TIPC) {
282 // Trusty has a single persistent service
283 return;
284 }
285
Andrei Homescu96834632022-10-14 00:49:49 +0000286 auto writeFd = std::to_string(writeEnd.get());
287 auto readFd = std::to_string(readEnd.get());
288 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
289 NULL);
290 }));
291
292 BinderRpcTestServerConfig serverConfig;
293 serverConfig.numThreads = options.numThreads;
294 serverConfig.socketType = static_cast<int32_t>(socketType);
295 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
296 serverConfig.serverVersion = serverVersion;
297 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000298 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000299 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000300 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
301 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
302 static_cast<int32_t>(mode));
303 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000304 if (socketType != SocketType::TIPC) {
305 writeToFd(ret->host.writeEnd(), serverConfig);
306 }
Andrei Homescu96834632022-10-14 00:49:49 +0000307
308 std::vector<sp<RpcSession>> sessions;
309 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
310 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000311 std::unique_ptr<RpcTransportCtxFactory> factory;
312 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000313#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000314 factory = RpcTransportCtxFactoryTipcAndroid::make();
315#else
316 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
317#endif
318 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000319 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000320 }
321 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100322 }
323
Andrei Homescu68a55612022-08-02 01:25:15 +0000324 BinderRpcTestServerInfo serverInfo;
325 if (socketType != SocketType::TIPC) {
326 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
327 BinderRpcTestClientInfo clientInfo;
328 for (const auto& session : sessions) {
329 auto& parcelableCert = clientInfo.certs.emplace_back();
330 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
331 }
332 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000333
Andrei Homescu68a55612022-08-02 01:25:15 +0000334 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
335 if (socketType == SocketType::INET) {
336 CHECK_NE(0, serverInfo.port);
337 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000338
Andrei Homescu68a55612022-08-02 01:25:15 +0000339 if (rpcSecurity == RpcSecurity::TLS) {
340 const auto& serverCert = serverInfo.cert.data;
341 CHECK_EQ(OK,
342 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
343 serverCert));
344 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700345 }
346
Andrei Homescu96834632022-10-14 00:49:49 +0000347 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000348
Steven Moreland67f85902023-03-15 01:13:49 +0000349 for (size_t i = 0; i < sessions.size(); i++) {
350 const auto& session = sessions.at(i);
351
352 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
353 ? options.numIncomingConnectionsBySession.at(i)
354 : 0;
355
Andrei Homescu96834632022-10-14 00:49:49 +0000356 CHECK(session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000357 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000358 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000359 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000360
Andrei Homescu96834632022-10-14 00:49:49 +0000361 switch (socketType) {
362 case SocketType::PRECONNECTED:
363 status = session->setupPreconnectedClient({}, [=]() {
364 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
365 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000366 break;
Alice Wang893a9912022-10-24 10:44:09 +0000367 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000368 case SocketType::UNIX:
369 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
370 break;
371 case SocketType::UNIX_BOOTSTRAP:
372 status = session->setupUnixDomainSocketBootstrapClient(
373 base::unique_fd(dup(bootstrapClientFd.get())));
374 break;
375 case SocketType::VSOCK:
376 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
377 break;
378 case SocketType::INET:
379 status = session->setupInetClient("127.0.0.1", serverInfo.port);
380 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000381 case SocketType::TIPC:
382 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000383#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000384 auto port = trustyIpcPort(serverVersion);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000385 for (size_t i = 0; i < 5; i++) {
386 // Try to connect several times,
387 // in case the service is slow to start
388 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
389 if (tipcFd >= 0) {
390 return android::base::unique_fd(tipcFd);
391 }
392 usleep(50000);
393 }
394 return android::base::unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000395#else
396 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
397 return android::base::unique_fd();
398#endif
399 });
400 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000401 default:
402 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000403 }
Andrei Homescu96834632022-10-14 00:49:49 +0000404 if (options.allowConnectFailure && status != OK) {
405 ret->sessions.clear();
406 break;
407 }
408 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
409 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000410 }
Andrei Homescu96834632022-10-14 00:49:49 +0000411 return ret;
412}
Steven Morelandc1635952021-04-01 16:20:47 +0000413
Andrei Homescua858b0e2022-08-01 23:43:09 +0000414TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
415 if (clientOrServerSingleThreaded()) {
416 GTEST_SKIP() << "This test requires multiple threads";
417 }
418
Steven Moreland5553ac42020-11-11 02:14:45 +0000419 constexpr size_t kNumThreads = 10;
420
Steven Moreland4313d7e2021-07-15 23:41:22 +0000421 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000422
423 EXPECT_OK(proc.rootIface->lock());
424
425 // block all but one thread taking locks
426 std::vector<std::thread> ts;
427 for (size_t i = 0; i < kNumThreads - 1; i++) {
428 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
429 }
430
Steven Morelandd6d816f2022-12-23 01:37:17 +0000431 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000432
433 // other calls still work
434 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
435
Steven Morelandd6d816f2022-12-23 01:37:17 +0000436 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000437 size_t epochMsBefore = epochMillis();
438 // after this, we should never see a response within this time
439 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
440
441 // this call should be blocked for blockTimeMs
442 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
443
444 size_t epochMsAfter = epochMillis();
445 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
446
447 for (auto& t : ts) t.join();
448}
449
Steven Moreland27f620a2023-03-06 19:44:36 +0000450static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000451 size_t epochMsBefore = epochMillis();
452
453 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700454 for (size_t i = 0; i < numCalls; i++) {
455 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000456 }
457
458 for (auto& t : ts) t.join();
459
460 size_t epochMsAfter = epochMillis();
461
Yifan Hong1f44f982021-10-08 17:16:47 -0700462 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000463
Steven Moreland9c203222023-05-31 21:26:41 +0000464 // Potential flake, but make sure calls are handled in parallel. Due
465 // to past flakes, this only checks that the amount of time taken has
466 // some parallelism. Other tests such as ThreadPoolGreaterThanEqualRequested
467 // check this more exactly.
468 EXPECT_LE(epochMsAfter, epochMsBefore + (numCalls - 1) * sleepMs);
Yifan Hong1f44f982021-10-08 17:16:47 -0700469}
470
Andrei Homescua858b0e2022-08-01 23:43:09 +0000471TEST_P(BinderRpc, ThreadPoolOverSaturated) {
472 if (clientOrServerSingleThreaded()) {
473 GTEST_SKIP() << "This test requires multiple threads";
474 }
475
Yifan Hong1f44f982021-10-08 17:16:47 -0700476 constexpr size_t kNumThreads = 10;
477 constexpr size_t kNumCalls = kNumThreads + 3;
478 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000479
480 // b/272429574 - below 500ms, the test fails
481 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700482}
483
Andrei Homescua858b0e2022-08-01 23:43:09 +0000484TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
485 if (clientOrServerSingleThreaded()) {
486 GTEST_SKIP() << "This test requires multiple threads";
487 }
488
Yifan Hong1f44f982021-10-08 17:16:47 -0700489 constexpr size_t kNumThreads = 20;
490 constexpr size_t kNumOutgoingConnections = 10;
491 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
492 auto proc = createRpcTestSocketServerProcess(
493 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000494
495 // b/272429574 - below 500ms, the test fails
496 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000497}
498
Andrei Homescua858b0e2022-08-01 23:43:09 +0000499TEST_P(BinderRpc, ThreadingStressTest) {
500 if (clientOrServerSingleThreaded()) {
501 GTEST_SKIP() << "This test requires multiple threads";
502 }
503
Steven Moreland27f620a2023-03-06 19:44:36 +0000504 constexpr size_t kNumClientThreads = 5;
505 constexpr size_t kNumServerThreads = 5;
506 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000507
Steven Moreland4313d7e2021-07-15 23:41:22 +0000508 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000509
510 std::vector<std::thread> threads;
511 for (size_t i = 0; i < kNumClientThreads; i++) {
512 threads.push_back(std::thread([&] {
513 for (size_t j = 0; j < kNumCalls; j++) {
514 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000515 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000516 EXPECT_EQ(proc.rootBinder, out);
517 }
518 }));
519 }
520
521 for (auto& t : threads) t.join();
522}
523
Steven Moreland925ba0a2021-09-17 18:06:32 -0700524static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
525 std::vector<std::thread> threads;
526 for (size_t i = 0; i < threadCount; i++) {
527 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
528 }
529 for (auto& t : threads) t.join();
530}
531
Andrei Homescua858b0e2022-08-01 23:43:09 +0000532TEST_P(BinderRpc, OnewayStressTest) {
533 if (clientOrServerSingleThreaded()) {
534 GTEST_SKIP() << "This test requires multiple threads";
535 }
536
Steven Morelandc6046982021-04-20 00:49:42 +0000537 constexpr size_t kNumClientThreads = 10;
538 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700539 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000540
Steven Moreland4313d7e2021-07-15 23:41:22 +0000541 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000542
543 std::vector<std::thread> threads;
544 for (size_t i = 0; i < kNumClientThreads; i++) {
545 threads.push_back(std::thread([&] {
546 for (size_t j = 0; j < kNumCalls; j++) {
547 EXPECT_OK(proc.rootIface->sendString("a"));
548 }
Steven Morelandc6046982021-04-20 00:49:42 +0000549 }));
550 }
551
552 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700553
554 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000555}
556
Frederick Mayleb0221d12022-10-03 23:10:53 +0000557TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
558 if (!supportsFdTransport()) {
559 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
560 }
561 if (clientOrServerSingleThreaded()) {
562 GTEST_SKIP() << "This test requires multiple threads";
563 }
564
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000565 constexpr size_t kNumServerThreads = 3;
566
Frederick Mayleb0221d12022-10-03 23:10:53 +0000567 // This test forces a oneway transaction to be queued by issuing two
568 // `blockingSendFdOneway` calls, then drains the queue by issuing two
569 // `blockingRecvFd` calls.
570 //
571 // For more details about the queuing semantics see
572 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
573
574 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000575 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000576 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
577 .serverSupportedFileDescriptorTransportModes =
578 {RpcSession::FileDescriptorTransportMode::UNIX},
579 });
580
581 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
582 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
583 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
584 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
585
586 android::os::ParcelFileDescriptor fdA;
587 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
588 std::string result;
589 CHECK(android::base::ReadFdToString(fdA.get(), &result));
590 EXPECT_EQ(result, "a");
591
592 android::os::ParcelFileDescriptor fdB;
593 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
594 CHECK(android::base::ReadFdToString(fdB.get(), &result));
595 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000596
597 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000598}
599
Andrei Homescua858b0e2022-08-01 23:43:09 +0000600TEST_P(BinderRpc, OnewayCallQueueing) {
601 if (clientOrServerSingleThreaded()) {
602 GTEST_SKIP() << "This test requires multiple threads";
603 }
604
Frederick Mayle96872592023-03-07 14:56:15 -0800605 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000606 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000607
608 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000609 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000610
Frederick Mayle96872592023-03-07 14:56:15 -0800611 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700612 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800613 for (size_t i = 0; i + 1 < kNumQueued; i++) {
614 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000615 }
Frederick Mayle96872592023-03-07 14:56:15 -0800616 for (size_t i = 0; i + 1 < kNumQueued; i++) {
617 int n;
618 proc.rootIface->blockingRecvInt(&n);
619 EXPECT_EQ(n, i);
620 }
Steven Morelandf5174272021-05-25 00:39:28 +0000621
Steven Moreland925ba0a2021-09-17 18:06:32 -0700622 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000623}
624
Andrei Homescua858b0e2022-08-01 23:43:09 +0000625TEST_P(BinderRpc, OnewayCallExhaustion) {
626 if (clientOrServerSingleThreaded()) {
627 GTEST_SKIP() << "This test requires multiple threads";
628 }
629
Steven Morelandd45be622021-06-04 02:19:37 +0000630 constexpr size_t kNumClients = 2;
631 constexpr size_t kTooLongMs = 1000;
632
Steven Moreland4313d7e2021-07-15 23:41:22 +0000633 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000634
635 // Build up oneway calls on the second session to make sure it terminates
636 // and shuts down. The first session should be unaffected (proc destructor
637 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000638 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000639
640 std::vector<std::thread> threads;
641 for (size_t i = 0; i < kNumClients; i++) {
642 // one of these threads will get stuck queueing a transaction once the
643 // socket fills up, the other will be able to fill up transactions on
644 // this object
645 threads.push_back(std::thread([&] {
646 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
647 }
648 }));
649 }
650 for (auto& t : threads) t.join();
651
652 Status status = iface->sleepMsAsync(kTooLongMs);
653 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
654
Steven Moreland798e0d12021-07-14 23:19:25 +0000655 // now that it has died, wait for the remote session to shutdown
656 std::vector<int32_t> remoteCounts;
657 do {
658 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
659 } while (remoteCounts.size() == kNumClients);
660
Steven Morelandd45be622021-06-04 02:19:37 +0000661 // the second session should be shutdown in the other process by the time we
662 // are able to join above (it'll only be hung up once it finishes processing
663 // any pending commands). We need to erase this session from the record
664 // here, so that the destructor for our session won't check that this
665 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000666 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000667}
668
Steven Moreland67f85902023-03-15 01:13:49 +0000669TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
670 if (clientOrServerSingleThreaded()) {
671 GTEST_SKIP() << "This test requires multiple threads";
672 }
673
674 // session 0 - will check for leaks in destrutor of proc
675 // session 1 - we want to make sure it gets deleted when we drop all references to it
676 auto proc = createRpcTestSocketServerProcess(
677 {.numThreads = 1, .numIncomingConnectionsBySession = {0, 1}, .numSessions = 2});
678
679 wp<RpcSession> session = proc.proc->sessions.at(1).session;
680
681 // remove all references to the second session
682 proc.proc->sessions.at(1).root = nullptr;
683 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
684
685 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
686 // to drain commands.
687 for (size_t i = 0; i < 100; i++) {
688 usleep(10 * 1000);
689 if (session.promote() == nullptr) break;
690 }
691
692 EXPECT_EQ(nullptr, session.promote());
Steven Morelandb5d2b642023-05-04 00:31:45 +0000693
694 sleep(1); // give time for remote session to shutdown
Steven Moreland67f85902023-03-15 01:13:49 +0000695}
696
Devin Moore66d5b7a2022-07-07 21:42:10 +0000697TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000698 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000699 GTEST_SKIP() << "This test requires multiple threads";
700 }
701 class MyDeathRec : public IBinder::DeathRecipient {
702 public:
703 void binderDied(const wp<IBinder>& /* who */) override {
704 dead = true;
705 mCv.notify_one();
706 }
707 std::mutex mMtx;
708 std::condition_variable mCv;
709 bool dead = false;
710 };
711
712 // Death recipient needs to have an incoming connection to be called
713 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000714 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000715
716 auto dr = sp<MyDeathRec>::make();
717 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
718
719 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
720 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
721 }
722
723 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000724 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000725
726 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000727 // can't do this before checking the death recipient by calling
728 // forceShutdown earlier, because shutdownAndWait will also trigger
729 // a death recipient, but if we had a way to wait for the service
730 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000731 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000732 proc.expectAlreadyShutdown = true;
733}
734
735TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000736 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000737 GTEST_SKIP() << "This test requires multiple threads";
738 }
739 class MyDeathRec : public IBinder::DeathRecipient {
740 public:
741 void binderDied(const wp<IBinder>& /* who */) override {
742 dead = true;
743 mCv.notify_one();
744 }
745 std::mutex mMtx;
746 std::condition_variable mCv;
747 bool dead = false;
748 };
749
750 // Death recipient needs to have an incoming connection to be called
751 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000752 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000753
754 auto dr = sp<MyDeathRec>::make();
755 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
756
757 // Explicitly calling shutDownAndWait will cause the death recipients
758 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000759 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000760
761 std::unique_lock<std::mutex> lock(dr->mMtx);
762 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000763 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000764 }
765 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
766
Andrei Homescu96834632022-10-14 00:49:49 +0000767 proc.proc->terminate();
768 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000769 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
770 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
771 });
772 proc.expectAlreadyShutdown = true;
773}
774
Steven Moreland5ec743f2023-01-18 01:02:06 +0000775TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000776 if (socketType() == SocketType::TIPC) {
777 // This should work, but Trusty takes too long to restart the service
778 GTEST_SKIP() << "Service death test not supported on Trusty";
779 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000780 class MyDeathRec : public IBinder::DeathRecipient {
781 public:
782 void binderDied(const wp<IBinder>& /* who */) override {}
783 };
784
Steven Moreland67f85902023-03-15 01:13:49 +0000785 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000786
787 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000788 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000789}
790
791TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000792 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000793 GTEST_SKIP() << "This test requires multiple threads";
794 }
795 class MyDeathRec : public IBinder::DeathRecipient {
796 public:
797 void binderDied(const wp<IBinder>& /* who */) override {
798 GTEST_FAIL() << "This should not be called after unlinkToDeath";
799 }
800 };
801
802 // Death recipient needs to have an incoming connection to be called
803 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000804 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000805
806 auto dr = sp<MyDeathRec>::make();
807 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
808 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
809
Steven Moreland67f85902023-03-15 01:13:49 +0000810 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000811}
812
Steven Morelandc1635952021-04-01 16:20:47 +0000813TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000814 if (socketType() == SocketType::TIPC) {
815 // This should work, but Trusty takes too long to restart the service
816 GTEST_SKIP() << "Service death test not supported on Trusty";
817 }
818
Steven Moreland5553ac42020-11-11 02:14:45 +0000819 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000820 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000821
822 // make sure there is some state during crash
823 // 1. we hold their binder
824 sp<IBinderRpcSession> session;
825 EXPECT_OK(proc.rootIface->openSession("happy", &session));
826 // 2. they hold our binder
827 sp<IBinder> binder = new BBinder();
828 EXPECT_OK(proc.rootIface->holdBinder(binder));
829
830 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
831 << "Do death cleanup: " << doDeathCleanup;
832
Andrei Homescu96834632022-10-14 00:49:49 +0000833 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000834 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
835 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
836 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000837 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000838 }
839}
840
Steven Morelandd7302072021-05-15 01:32:04 +0000841TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000842 // This test only works if the current process shared the internal state of
843 // ProcessState with the service across the call to fork(). Both the static
844 // libraries and libbinder.so have their own separate copies of all the
845 // globals, so the test only works when the test client and service both use
846 // libbinder.so (when using static libraries, even a client and service
847 // using the same kind of static library should have separate copies of the
848 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000849 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000850 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
851 "at build time.";
852 }
853
Steven Moreland4313d7e2021-07-15 23:41:22 +0000854 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000855
Andrei Homescu2a298012022-06-15 01:08:54 +0000856 // we can't allocate IPCThreadState so actually the first time should
857 // succeed :(
858 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000859
860 // second time! we catch the error :)
861 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
862
Andrei Homescu96834632022-10-14 00:49:49 +0000863 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000864 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
865 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
866 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000867 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000868}
869
Frederick Mayle69a0c992022-05-26 20:38:39 +0000870TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000871 if (socketType() == SocketType::TIPC) {
872 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
873 }
874
Frederick Mayle69a0c992022-05-26 20:38:39 +0000875 auto proc = createRpcTestSocketServerProcess({
876 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
877 .serverSupportedFileDescriptorTransportModes =
878 {RpcSession::FileDescriptorTransportMode::UNIX},
879 .allowConnectFailure = true,
880 });
Andrei Homescu96834632022-10-14 00:49:49 +0000881 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
882 proc.proc->terminate();
883 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000884 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
885 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
886 });
887 proc.expectAlreadyShutdown = true;
888}
889
890TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000891 if (socketType() == SocketType::TIPC) {
892 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
893 }
894
Frederick Mayle69a0c992022-05-26 20:38:39 +0000895 auto proc = createRpcTestSocketServerProcess({
896 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
897 .serverSupportedFileDescriptorTransportModes =
898 {RpcSession::FileDescriptorTransportMode::NONE},
899 .allowConnectFailure = true,
900 });
Andrei Homescu96834632022-10-14 00:49:49 +0000901 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
902 proc.proc->terminate();
903 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000904 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
905 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
906 });
907 proc.expectAlreadyShutdown = true;
908}
909
910TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000911 if (socketType() == SocketType::TIPC) {
912 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
913 }
914
Frederick Mayle69a0c992022-05-26 20:38:39 +0000915 auto proc = createRpcTestSocketServerProcess({
916 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
917 .serverSupportedFileDescriptorTransportModes =
918 {RpcSession::FileDescriptorTransportMode::NONE,
919 RpcSession::FileDescriptorTransportMode::UNIX},
920 });
921
922 android::os::ParcelFileDescriptor out;
923 auto status = proc.rootIface->echoAsFile("hello", &out);
924 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
925}
926
927TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000928 if (socketType() == SocketType::TIPC) {
929 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
930 }
931
Frederick Mayle69a0c992022-05-26 20:38:39 +0000932 auto proc = createRpcTestSocketServerProcess({
933 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
934 .serverSupportedFileDescriptorTransportModes =
935 {RpcSession::FileDescriptorTransportMode::UNIX},
936 });
937
938 android::os::ParcelFileDescriptor out;
939 auto status = proc.rootIface->echoAsFile("hello", &out);
940 if (!supportsFdTransport()) {
941 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
942 return;
943 }
944 ASSERT_TRUE(status.isOk()) << status;
945
946 std::string result;
947 CHECK(android::base::ReadFdToString(out.get(), &result));
948 EXPECT_EQ(result, "hello");
949}
950
951TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000952 if (socketType() == SocketType::TIPC) {
953 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
954 }
955
Frederick Mayle69a0c992022-05-26 20:38:39 +0000956 auto proc = createRpcTestSocketServerProcess({
957 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
958 .serverSupportedFileDescriptorTransportModes =
959 {RpcSession::FileDescriptorTransportMode::UNIX},
960 });
961
962 std::vector<android::os::ParcelFileDescriptor> files;
963 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
964 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
965 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
966 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
967
968 android::os::ParcelFileDescriptor out;
969 auto status = proc.rootIface->concatFiles(files, &out);
970 if (!supportsFdTransport()) {
971 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
972 return;
973 }
974 ASSERT_TRUE(status.isOk()) << status;
975
976 std::string result;
977 CHECK(android::base::ReadFdToString(out.get(), &result));
978 EXPECT_EQ(result, "123abcd");
979}
980
981TEST_P(BinderRpc, SendMaxFiles) {
982 if (!supportsFdTransport()) {
983 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
984 }
985
986 auto proc = createRpcTestSocketServerProcess({
987 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
988 .serverSupportedFileDescriptorTransportModes =
989 {RpcSession::FileDescriptorTransportMode::UNIX},
990 });
991
992 std::vector<android::os::ParcelFileDescriptor> files;
993 for (int i = 0; i < 253; i++) {
994 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
995 }
996
997 android::os::ParcelFileDescriptor out;
998 auto status = proc.rootIface->concatFiles(files, &out);
999 ASSERT_TRUE(status.isOk()) << status;
1000
1001 std::string result;
1002 CHECK(android::base::ReadFdToString(out.get(), &result));
1003 EXPECT_EQ(result, std::string(253, 'a'));
1004}
1005
1006TEST_P(BinderRpc, SendTooManyFiles) {
1007 if (!supportsFdTransport()) {
1008 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1009 }
1010
1011 auto proc = createRpcTestSocketServerProcess({
1012 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1013 .serverSupportedFileDescriptorTransportModes =
1014 {RpcSession::FileDescriptorTransportMode::UNIX},
1015 });
1016
1017 std::vector<android::os::ParcelFileDescriptor> files;
1018 for (int i = 0; i < 254; i++) {
1019 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1020 }
1021
1022 android::os::ParcelFileDescriptor out;
1023 auto status = proc.rootIface->concatFiles(files, &out);
1024 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1025}
1026
Andrei Homescufc221502022-10-08 03:51:17 +00001027TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001028 if (socketType() == SocketType::TIPC) {
1029 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1030 }
1031
Andrei Homescufc221502022-10-08 03:51:17 +00001032 auto proc = createRpcTestSocketServerProcess({
1033 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1034 .serverSupportedFileDescriptorTransportModes =
1035 {RpcSession::FileDescriptorTransportMode::UNIX},
1036 });
1037
1038 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1039 ASSERT_NE(badFd, -1);
1040
1041 // Close the file descriptor so it becomes invalid for dup
1042 close(badFd);
1043
1044 Parcel p1;
1045 p1.markForBinder(proc.rootBinder);
1046 p1.writeInt32(3);
1047 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1048
1049 Parcel pRaw;
1050 pRaw.markForBinder(proc.rootBinder);
1051 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1052
1053 pRaw.setDataPosition(0);
1054 EXPECT_EQ(3, pRaw.readInt32());
1055 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1056}
1057
Andrei Homescu68a55612022-08-02 01:25:15 +00001058#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001059TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001060 if constexpr (!kEnableSharedLibs) {
1061 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1062 }
1063
Steven Moreland4313d7e2021-07-15 23:41:22 +00001064 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001065
1066 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1067 ASSERT_NE(binder, nullptr);
1068
1069 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1070}
1071
1072TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001073 if constexpr (!kEnableSharedLibs) {
1074 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1075 }
1076
Steven Moreland4313d7e2021-07-15 23:41:22 +00001077 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001078
1079 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1080 ASSERT_NE(binder, nullptr);
1081
1082 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1083 ASSERT_NE(ndkBinder, nullptr);
1084
1085 std::string out;
1086 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1087 ASSERT_TRUE(status.isOk()) << status.getDescription();
1088 ASSERT_EQ("aoeuaoeu", out);
1089}
Andrei Homescu68a55612022-08-02 01:25:15 +00001090#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001091
Steven Moreland5553ac42020-11-11 02:14:45 +00001092ssize_t countFds() {
1093 DIR* dir = opendir("/proc/self/fd/");
1094 if (dir == nullptr) return -1;
1095 ssize_t ret = 0;
1096 dirent* ent;
1097 while ((ent = readdir(dir)) != nullptr) ret++;
1098 closedir(dir);
1099 return ret;
1100}
1101
Andrei Homescua858b0e2022-08-01 23:43:09 +00001102TEST_P(BinderRpc, Fds) {
1103 if (serverSingleThreaded()) {
1104 GTEST_SKIP() << "This test requires multiple threads";
1105 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001106 if (socketType() == SocketType::TIPC) {
1107 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1108 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001109
Steven Moreland5553ac42020-11-11 02:14:45 +00001110 ssize_t beforeFds = countFds();
1111 ASSERT_GE(beforeFds, 0);
1112 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001113 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001114 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1115 }
1116 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1117}
1118
Andrei Homescud65666d2023-03-03 07:28:02 +00001119#ifdef BINDER_RPC_TO_TRUSTY_TEST
1120INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc,
1121 ::testing::Combine(::testing::Values(SocketType::TIPC),
1122 ::testing::Values(RpcSecurity::RAW),
1123 ::testing::ValuesIn(testVersions()),
1124 ::testing::ValuesIn(testVersions()),
1125 ::testing::Values(true), ::testing::Values(true)),
1126 BinderRpc::PrintParamInfo);
1127#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Moreland9f250b02023-05-16 23:27:42 +00001128bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001129 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001130 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001131
Andrei Homescu992a4052022-06-28 21:26:18 +00001132 android::base::unique_fd serverFd(
1133 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Morelanda27311b2023-04-11 22:13:35 +00001134
1135 if (errno == EAFNOSUPPORT) {
1136 return false;
1137 }
1138
Andrei Homescu992a4052022-06-28 21:26:18 +00001139 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1140
1141 sockaddr_vm serverAddr{
1142 .svm_family = AF_VSOCK,
1143 .svm_port = vsockPort,
1144 .svm_cid = VMADDR_CID_ANY,
1145 };
1146 int ret = TEMP_FAILURE_RETRY(
1147 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1148 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1149 strerror(errno));
1150
1151 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1152 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1153 strerror(errno));
1154
1155 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1156 // to see if the kernel supports it. It's safe to use a blocking
1157 // connect because vsock sockets have a 2 second connection timeout,
1158 // and they return ETIMEDOUT after that.
1159 android::base::unique_fd connectFd(
1160 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1161 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1162 strerror(errno));
1163
1164 bool success = false;
1165 sockaddr_vm connectAddr{
1166 .svm_family = AF_VSOCK,
1167 .svm_port = vsockPort,
1168 .svm_cid = VMADDR_CID_LOCAL,
1169 };
1170 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1171 sizeof(connectAddr)));
1172 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1173 android::base::unique_fd acceptFd;
1174 while (true) {
1175 pollfd pfd[]{
1176 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1177 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1178 };
1179 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1180 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1181
1182 if (pfd[0].revents & POLLIN) {
1183 sockaddr_vm acceptAddr;
1184 socklen_t acceptAddrLen = sizeof(acceptAddr);
1185 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1186 reinterpret_cast<sockaddr*>(&acceptAddr),
1187 &acceptAddrLen, SOCK_CLOEXEC));
1188 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1189 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1190 "Truncated address");
1191
1192 // Store the fd in acceptFd so we keep the connection alive
1193 // while polling connectFd
1194 acceptFd.reset(ret);
1195 }
1196
1197 if (pfd[1].revents & POLLOUT) {
1198 // Connect either succeeded or timed out
1199 int connectErrno;
1200 socklen_t connectErrnoLen = sizeof(connectErrno);
1201 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1202 &connectErrnoLen);
1203 LOG_ALWAYS_FATAL_IF(ret == -1,
1204 "Could not getsockopt() after connect() "
1205 "on non-blocking socket: %s.",
1206 strerror(errno));
1207
1208 // We're done, this is all we wanted
1209 success = connectErrno == 0;
1210 break;
1211 }
1212 }
1213 } else {
1214 success = ret == 0;
1215 }
1216
1217 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1218
1219 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001220}
1221
Yifan Hong1deca4b2021-09-10 16:16:44 -07001222static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001223 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1224 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001225
1226 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001227
Steven Moreland9f250b02023-05-16 23:27:42 +00001228#ifdef __BIONIC__
1229 // Devices may not have vsock support. AVF tests will verify whether they do, but
1230 // we can't require it due to old kernels for the time being.
Steven Morelandda573042021-06-12 01:13:45 +00001231 static bool hasVsockLoopback = testSupportVsockLoopback();
Steven Moreland9f250b02023-05-16 23:27:42 +00001232#else
1233 // On host machines, we always assume we have vsock loopback. If we don't, the
1234 // subsequent failures will be more clear than showing one now.
1235 static bool hasVsockLoopback = true;
1236#endif
Steven Morelandda573042021-06-12 01:13:45 +00001237
1238 if (hasVsockLoopback) {
1239 ret.push_back(SocketType::VSOCK);
1240 }
1241
1242 return ret;
1243}
1244
Yifan Hong702115c2021-06-24 15:39:18 -07001245INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1246 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001247 ::testing::ValuesIn(RpcSecurityValues()),
1248 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001249 ::testing::ValuesIn(testVersions()),
1250 ::testing::Values(false, true),
1251 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001252 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001253
Yifan Hong702115c2021-06-24 15:39:18 -07001254class BinderRpcServerRootObject
1255 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001256
1257TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1258 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1259 auto setRootObject = [](bool isStrong) -> SetFn {
1260 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1261 };
1262
Yifan Hong702115c2021-06-24 15:39:18 -07001263 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001264 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001265 auto binder1 = sp<BBinder>::make();
1266 IBinder* binderRaw1 = binder1.get();
1267 setRootObject(isStrong1)(server.get(), binder1);
1268 EXPECT_EQ(binderRaw1, server->getRootObject());
1269 binder1.clear();
1270 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1271
1272 auto binder2 = sp<BBinder>::make();
1273 IBinder* binderRaw2 = binder2.get();
1274 setRootObject(isStrong2)(server.get(), binder2);
1275 EXPECT_EQ(binderRaw2, server->getRootObject());
1276 binder2.clear();
1277 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1278}
1279
1280INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001281 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1282 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001283
Yifan Hong1a235852021-05-13 16:07:47 -07001284class OneOffSignal {
1285public:
1286 // If notify() was previously called, or is called within |duration|, return true; else false.
1287 template <typename R, typename P>
1288 bool wait(std::chrono::duration<R, P> duration) {
1289 std::unique_lock<std::mutex> lock(mMutex);
1290 return mCv.wait_for(lock, duration, [this] { return mValue; });
1291 }
1292 void notify() {
1293 std::unique_lock<std::mutex> lock(mMutex);
1294 mValue = true;
1295 lock.unlock();
1296 mCv.notify_all();
1297 }
1298
1299private:
1300 std::mutex mMutex;
1301 std::condition_variable mCv;
1302 bool mValue = false;
1303};
1304
Yifan Hong194acf22021-06-29 18:44:56 -07001305TEST(BinderRpc, Java) {
1306#if !defined(__ANDROID__)
1307 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1308 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1309 "to binderHostDeviceTest. Hence, just disable this test on host.";
1310#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001311 if constexpr (!kEnableKernelIpc) {
1312 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1313 "at build time.";
1314 }
1315
Yifan Hong194acf22021-06-29 18:44:56 -07001316 sp<IServiceManager> sm = defaultServiceManager();
1317 ASSERT_NE(nullptr, sm);
1318 // Any Java service with non-empty getInterfaceDescriptor() would do.
1319 // Let's pick batteryproperties.
1320 auto binder = sm->checkService(String16("batteryproperties"));
1321 ASSERT_NE(nullptr, binder);
1322 auto descriptor = binder->getInterfaceDescriptor();
1323 ASSERT_GE(descriptor.size(), 0);
1324 ASSERT_EQ(OK, binder->pingBinder());
1325
1326 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001327 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001328 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001329 auto socket = rpcServer->releaseServer();
1330
1331 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001332 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1333
Yifan Honge3caaf22022-01-12 14:46:56 -08001334 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1335 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001336 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001337 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1338 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001339 << statusToString(setRpcClientDebugStatus);
1340 GTEST_SKIP();
1341 }
1342
1343 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001344
1345 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001346 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001347 auto rpcBinder = rpcSession->getRootObject();
1348 ASSERT_NE(nullptr, rpcBinder);
1349
1350 ASSERT_EQ(OK, rpcBinder->pingBinder());
1351
1352 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1353 << "getInterfaceDescriptor should not crash system_server";
1354 ASSERT_EQ(OK, rpcBinder->pingBinder());
1355}
1356
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001357class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1358public:
1359 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001360 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001361 std::to_string(std::get<1>(info.param));
1362 }
1363};
1364
1365TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1366 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1367 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001368 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001369 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001370 ASSERT_FALSE(server->hasServer());
1371 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1372 ASSERT_TRUE(server->hasServer());
1373 base::unique_fd retrieved = server->releaseServer();
1374 ASSERT_FALSE(server->hasServer());
1375 ASSERT_EQ(sinkFd, retrieved.get());
1376}
1377
1378TEST_P(BinderRpcServerOnly, Shutdown) {
1379 if constexpr (!kEnableRpcThreads) {
1380 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1381 }
1382
1383 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001384 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001385 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001386 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1387 auto joinEnds = std::make_shared<OneOffSignal>();
1388
1389 // If things are broken and the thread never stops, don't block other tests. Because the thread
1390 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1391 // shared pointers are passed.
1392 std::thread([server, joinEnds] {
1393 server->join();
1394 joinEnds->notify();
1395 }).detach();
1396
1397 bool shutdown = false;
1398 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001399 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001400 if (server->shutdown()) shutdown = true;
1401 }
1402 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1403
1404 ASSERT_TRUE(joinEnds->wait(2s))
1405 << "After server->shutdown() returns true, join() did not stop after 2s";
1406}
1407
Frederick Mayledc07cf82022-05-26 20:30:12 +00001408INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1409 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1410 ::testing::ValuesIn(testVersions())),
1411 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001412
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001413class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001414public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001415 // Only parameterized only server version because `RpcSession` is bypassed
1416 // in the client half of the tests.
1417 using Param =
1418 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001419 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001420
1421 // A server that handles client socket connections.
1422 class Server {
1423 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001424 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1425
Yifan Hong1deca4b2021-09-10 16:16:44 -07001426 explicit Server() {}
1427 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001428 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001429 [[nodiscard]] AssertionResult setUp(
1430 const Param& param,
1431 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001432 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001433 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Steven Morelandca3f6382023-05-11 23:23:26 +00001434 if (!rpcServer->setProtocolVersion(serverVersion)) {
1435 return AssertionFailure() << "Invalid protocol version: " << serverVersion;
1436 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001437 switch (socketType) {
1438 case SocketType::PRECONNECTED: {
1439 return AssertionFailure() << "Not supported by this test";
1440 } break;
1441 case SocketType::UNIX: {
1442 auto addr = allocateSocketAddress();
1443 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1444 if (status != OK) {
1445 return AssertionFailure()
1446 << "setupUnixDomainServer: " << statusToString(status);
1447 }
1448 mConnectToServer = [addr] {
1449 return connectTo(UnixSocketAddress(addr.c_str()));
1450 };
1451 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001452 case SocketType::UNIX_BOOTSTRAP: {
1453 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1454 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1455 return AssertionFailure() << "Socketpair() failed";
1456 }
1457 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1458 std::move(bootstrapFdServer));
1459 if (status != OK) {
1460 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1461 << statusToString(status);
1462 }
1463 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1464 mAcceptConnection = &Server::recvmsgServerConnection;
1465 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1466 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001467 case SocketType::UNIX_RAW: {
1468 auto addr = allocateSocketAddress();
1469 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1470 if (status != OK) {
1471 return AssertionFailure()
1472 << "setupRawSocketServer: " << statusToString(status);
1473 }
1474 mConnectToServer = [addr] {
1475 return connectTo(UnixSocketAddress(addr.c_str()));
1476 };
1477 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001478 case SocketType::VSOCK: {
1479 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001480 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001481 if (status != OK) {
1482 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1483 }
1484 mConnectToServer = [port] {
1485 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1486 };
1487 } break;
1488 case SocketType::INET: {
1489 unsigned int port;
1490 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1491 if (status != OK) {
1492 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1493 }
1494 mConnectToServer = [port] {
1495 const char* addr = kLocalInetAddress;
1496 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1497 if (aiStart == nullptr) return base::unique_fd{};
1498 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1499 auto fd = connectTo(
1500 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1501 if (fd.ok()) return fd;
1502 }
1503 ALOGE("None of the socket address resolved for %s:%u can be connected",
1504 addr, port);
1505 return base::unique_fd{};
1506 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001507 } break;
1508 case SocketType::TIPC: {
1509 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1510 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001511 }
1512 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001513 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00001514 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001515 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1516 mSetup = true;
1517 return AssertionSuccess();
1518 }
1519 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1520 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1521 return mCertVerifier;
1522 }
1523 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1524 void start() {
1525 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1526 mThread = std::make_unique<std::thread>(&Server::run, this);
1527 }
David Brazdil21c887c2022-09-23 12:25:18 +01001528
1529 base::unique_fd acceptServerConnection() {
1530 return base::unique_fd(TEMP_FAILURE_RETRY(
1531 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1532 }
1533
1534 base::unique_fd recvmsgServerConnection() {
1535 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1536 int buf;
1537 iovec iov{&buf, sizeof(buf)};
1538
1539 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1540 int savedErrno = errno;
1541 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1542 }
1543 if (fds.size() != 1) {
1544 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1545 }
1546 return std::move(std::get<base::unique_fd>(fds[0]));
1547 }
1548
Yifan Hong1deca4b2021-09-10 16:16:44 -07001549 void run() {
1550 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1551
1552 std::vector<std::thread> threads;
1553 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001554 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001555 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1556 }
1557
1558 for (auto& thread : threads) thread.join();
1559 }
1560 void handleOne(android::base::unique_fd acceptedFd) {
1561 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001562 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001563 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001564 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001565 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001566 }
Yifan Honge07d2732021-09-13 21:59:14 -07001567 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001568 shutdown();
1569 join();
1570 }
1571 void shutdown() { mFdTrigger->trigger(); }
1572
1573 void setPostConnect(
1574 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1575 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001576 }
1577
1578 private:
1579 std::unique_ptr<std::thread> mThread;
1580 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001581 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001582 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001583 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001584 std::unique_ptr<RpcTransportCtx> mCtx;
1585 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1586 std::make_shared<RpcCertificateVerifierSimple>();
1587 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001588 // The function invoked after connection and handshake. By default, it is
1589 // |defaultPostConnect| that sends |kMessage| to the client.
1590 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1591 Server::defaultPostConnect;
1592
1593 void join() {
1594 if (mThread != nullptr) {
1595 mThread->join();
1596 mThread = nullptr;
1597 }
1598 }
1599
1600 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1601 FdTrigger* fdTrigger) {
1602 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001603 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001604 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001605 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001606 if (status != OK) return AssertionFailure() << statusToString(status);
1607 return AssertionSuccess();
1608 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001609 };
1610
1611 class Client {
1612 public:
1613 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1614 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001615 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001616 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1617 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001618 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001619 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001620 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1621 return AssertionSuccess();
1622 }
1623 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1624 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1625 return mCertVerifier;
1626 }
Yifan Hong67519322021-09-13 18:51:16 -07001627 // connect() and do handshake
1628 bool setUpTransport() {
1629 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001630 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001631 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1632 return mClientTransport != nullptr;
1633 }
1634 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1635 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1636 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001637 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001638 status_t readStatus =
1639 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001640 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001641 if (readStatus != OK) {
1642 return AssertionFailure() << statusToString(readStatus);
1643 }
1644 if (readMessage != expectedMessage) {
1645 return AssertionFailure()
1646 << "Expected " << expectedMessage << ", actual " << readMessage;
1647 }
1648 return AssertionSuccess();
1649 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001650 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001651 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001652 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1653 return;
1654 }
1655 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001656 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001657 }
1658
Pawan49d74cb2022-08-03 21:19:11 +00001659 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1660
Yifan Hong1deca4b2021-09-10 16:16:44 -07001661 private:
1662 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001663 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001664 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1665 std::unique_ptr<RpcTransportCtx> mCtx;
1666 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1667 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001668 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001669 };
1670
1671 // Make A trust B.
1672 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001673 static status_t trust(RpcSecurity rpcSecurity,
1674 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1675 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001676 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001677 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1678 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1679 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001680 }
1681
1682 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001683};
1684
1685class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1686public:
1687 using Server = RpcTransportTestUtils::Server;
1688 using Client = RpcTransportTestUtils::Client;
1689 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001690 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001691 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001692 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001693 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001694 return ret;
1695 }
1696 static std::vector<ParamType> getRpcTranportTestParams() {
1697 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001698 for (auto serverVersion : testVersions()) {
1699 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1700 for (auto rpcSecurity : RpcSecurityValues()) {
1701 switch (rpcSecurity) {
1702 case RpcSecurity::RAW: {
1703 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1704 } break;
1705 case RpcSecurity::TLS: {
1706 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1707 serverVersion);
1708 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1709 serverVersion);
1710 } break;
1711 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001712 }
1713 }
1714 }
1715 return ret;
1716 }
1717 template <typename A, typename B>
1718 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001719 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1720 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001721 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1722 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001723 void SetUp() override {
1724 if constexpr (!kEnableRpcThreads) {
1725 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1726 }
1727 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001728};
1729
1730TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001731 auto server = std::make_unique<Server>();
1732 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001733
1734 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001735 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001736
1737 ASSERT_EQ(OK, trust(&client, server));
1738 ASSERT_EQ(OK, trust(server, &client));
1739
1740 server->start();
1741 client.run();
1742}
1743
1744TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001745 auto server = std::make_unique<Server>();
1746 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001747
1748 std::vector<Client> clients;
1749 for (int i = 0; i < 2; i++) {
1750 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001751 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001752 ASSERT_EQ(OK, trust(&client, server));
1753 ASSERT_EQ(OK, trust(server, &client));
1754 }
1755
1756 server->start();
1757 for (auto& client : clients) client.run();
1758}
1759
1760TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001761 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1762 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001763
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001764 auto untrustedServer = std::make_unique<Server>();
1765 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001766
1767 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001768 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001769
1770 ASSERT_EQ(OK, trust(untrustedServer, &client));
1771
1772 untrustedServer->start();
1773
1774 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1775 // the client can't verify the server's identity.
1776 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1777 client.run(handshakeOk);
1778}
1779TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001780 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1781 (void)serverVersion;
1782
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001783 auto validServer = std::make_unique<Server>();
1784 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001785
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001786 auto maliciousServer = std::make_unique<Server>();
1787 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001788
1789 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001790 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001791
1792 ASSERT_EQ(OK, trust(&client, validServer));
1793 ASSERT_EQ(OK, trust(validServer, &client));
1794 ASSERT_EQ(OK, trust(maliciousServer, &client));
1795
1796 maliciousServer->start();
1797
1798 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1799 // the client can't verify the server's identity.
1800 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1801 client.run(handshakeOk);
1802}
1803
1804TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001805 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1806 (void)serverVersion;
1807
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001808 auto server = std::make_unique<Server>();
1809 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001810
1811 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001812 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001813
1814 ASSERT_EQ(OK, trust(&client, server));
1815
1816 server->start();
1817
1818 // For TLS, Client should be able to verify server's identity, so client should see
1819 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1820 // identity and should drop the connection, so client shouldn't be able to read anything.
1821 bool readOk = rpcSecurity != RpcSecurity::TLS;
1822 client.run(true, readOk);
1823}
1824
1825TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001826 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1827 (void)serverVersion;
1828
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001829 auto server = std::make_unique<Server>();
1830 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001831
1832 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001833 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001834 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001835 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001836
1837 ASSERT_EQ(OK, trust(&validClient, server));
1838 ASSERT_EQ(OK, trust(&maliciousClient, server));
1839
1840 server->start();
1841
1842 // See UntrustedClient.
1843 bool readOk = rpcSecurity != RpcSecurity::TLS;
1844 maliciousClient.run(true, readOk);
1845}
1846
Yifan Hong67519322021-09-13 18:51:16 -07001847TEST_P(RpcTransportTest, Trigger) {
1848 std::string msg2 = ", world!";
1849 std::mutex writeMutex;
1850 std::condition_variable writeCv;
1851 bool shouldContinueWriting = false;
1852 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001853 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001854 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001855 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1856 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001857 if (status != OK) return AssertionFailure() << statusToString(status);
1858
1859 {
1860 std::unique_lock<std::mutex> lock(writeMutex);
1861 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1862 return AssertionFailure() << "write barrier not cleared in time!";
1863 }
1864 }
1865
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001866 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001867 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1868 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001869 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001870 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001871 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001872 << statusToString(status);
1873 return AssertionSuccess();
1874 };
1875
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001876 auto server = std::make_unique<Server>();
1877 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001878
1879 // Set up client
1880 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001881 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001882
1883 // Exchange keys
1884 ASSERT_EQ(OK, trust(&client, server));
1885 ASSERT_EQ(OK, trust(server, &client));
1886
1887 server->setPostConnect(serverPostConnect);
1888
Yifan Hong67519322021-09-13 18:51:16 -07001889 server->start();
1890 // connect() to server and do handshake
1891 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001892 // read the first message. This ensures that server has finished handshake and start handling
1893 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001894 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001895 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1896 // write is on an FdTrigger that has been shut down.
1897 server->shutdown();
1898 // Continues server thread to write the second message.
1899 {
Yifan Hong22211f82021-09-14 12:32:25 -07001900 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001901 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001902 }
Yifan Hong22211f82021-09-14 12:32:25 -07001903 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001904 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001905 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001906 // On the client side, second read fails with DEAD_OBJECT
1907 ASSERT_FALSE(client.readMessage(msg2));
1908}
1909
Pawan49d74cb2022-08-03 21:19:11 +00001910TEST_P(RpcTransportTest, CheckWaitingForRead) {
1911 std::mutex readMutex;
1912 std::condition_variable readCv;
1913 bool shouldContinueReading = false;
1914 // Server will write data on transport once its started
1915 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1916 std::string message(RpcTransportTestUtils::kMessage);
1917 iovec messageIov{message.data(), message.size()};
1918 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1919 std::nullopt, nullptr);
1920 if (status != OK) return AssertionFailure() << statusToString(status);
1921
1922 {
1923 std::unique_lock<std::mutex> lock(readMutex);
1924 shouldContinueReading = true;
1925 lock.unlock();
1926 readCv.notify_all();
1927 }
1928 return AssertionSuccess();
1929 };
1930
1931 // Setup Server and client
1932 auto server = std::make_unique<Server>();
1933 ASSERT_TRUE(server->setUp(GetParam()));
1934
1935 Client client(server->getConnectToServerFn());
1936 ASSERT_TRUE(client.setUp(GetParam()));
1937
1938 ASSERT_EQ(OK, trust(&client, server));
1939 ASSERT_EQ(OK, trust(server, &client));
1940 server->setPostConnect(serverPostConnect);
1941
1942 server->start();
1943 ASSERT_TRUE(client.setUpTransport());
1944 {
1945 // Wait till server writes data
1946 std::unique_lock<std::mutex> lock(readMutex);
1947 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1948 }
1949
1950 // Since there is no read polling here, we will get polling count 0
1951 ASSERT_FALSE(client.isTransportWaiting());
1952 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1953 // Thread should increment polling count, read and decrement polling count
1954 // Again, polling count should be zero here
1955 ASSERT_FALSE(client.isTransportWaiting());
1956
1957 server->shutdown();
1958}
1959
Yifan Hong1deca4b2021-09-10 16:16:44 -07001960INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001961 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001962 RpcTransportTest::PrintParamInfo);
1963
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001964class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001965 : public testing::TestWithParam<
1966 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001967public:
1968 template <typename A, typename B>
1969 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001970 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1971 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001972 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1973 }
1974 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001975 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1976 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1977 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001978 };
1979};
1980
1981TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001982 if constexpr (!kEnableRpcThreads) {
1983 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1984 }
1985
Frederick Mayledc07cf82022-05-26 20:30:12 +00001986 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001987
1988 std::vector<uint8_t> pkeyData, certData;
1989 {
1990 auto pkey = makeKeyPairForSelfSignedCert();
1991 ASSERT_NE(nullptr, pkey);
1992 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1993 ASSERT_NE(nullptr, cert);
1994 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1995 certData = serializeCertificate(cert.get(), certificateFormat);
1996 }
1997
1998 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1999 auto desCert = deserializeCertificate(certData, certificateFormat);
2000 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002001 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2002 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002003
2004 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2005 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2006
2007 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2008 ASSERT_TRUE(client.setUp(utilsParam));
2009
2010 ASSERT_EQ(OK, trust(&client, server));
2011 ASSERT_EQ(OK, trust(server, &client));
2012
2013 server->start();
2014 client.run();
2015}
2016
2017INSTANTIATE_TEST_CASE_P(
2018 BinderRpc, RpcTransportTlsKeyTest,
2019 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2020 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002021 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2022 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002023 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00002024#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002025
Steven Morelandc1635952021-04-01 16:20:47 +00002026} // namespace android
2027
2028int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002029 ::testing::InitGoogleTest(&argc, argv);
2030 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002031
Steven Moreland5553ac42020-11-11 02:14:45 +00002032 return RUN_ALL_TESTS();
2033}