blob: 87c84ba6e7c709892cc94469ac9866f1b58bb564 [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 Homescu68a55612022-08-02 01:25:15 +000031#ifdef __ANDROID_VENDOR__
32#include <binder/RpcTransportTipcAndroid.h>
33#include <trusty/tipc.h>
34#endif // __ANDROID_VENDOR__
35
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 Homescu68a55612022-08-02 01:25:15 +000053#ifdef __ANDROID_VENDOR__
54constexpr 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
David Brazdil21c887c2022-09-23 12:25:18 +0100217static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
218 base::unique_fd sockClient, sockServer;
219 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
220 int savedErrno = errno;
221 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
222 }
223
224 int zero = 0;
225 iovec iov{&zero, sizeof(zero)};
226 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
227 fds.emplace_back(std::move(sockServer));
228
229 if (sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
230 int savedErrno = errno;
231 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
232 }
233 return std::move(sockClient);
234}
235
Andrei Homescu96834632022-10-14 00:49:49 +0000236std::string BinderRpc::PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
237 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
238 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
239 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
240 if (singleThreaded) {
241 ret += "_single_threaded";
Steven Moreland5602a1a2023-03-06 19:25:46 +0000242 } else {
243 ret += "_multi_threaded";
Andrei Homescu96834632022-10-14 00:49:49 +0000244 }
245 if (noKernel) {
246 ret += "_no_kernel";
Steven Moreland5602a1a2023-03-06 19:25:46 +0000247 } else {
248 ret += "_with_kernel";
Andrei Homescu96834632022-10-14 00:49:49 +0000249 }
250 return ret;
251}
Andrei Homescu2a298012022-06-15 01:08:54 +0000252
Andrei Homescu96834632022-10-14 00:49:49 +0000253// This creates a new process serving an interface on a certain number of
254// threads.
255std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
256 const BinderRpcOptions& options) {
257 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000258
Steven Moreland67f85902023-03-15 01:13:49 +0000259 if (options.numIncomingConnectionsBySession.size() != 0) {
260 CHECK_EQ(options.numIncomingConnectionsBySession.size(), options.numSessions);
261 }
262
Andrei Homescu96834632022-10-14 00:49:49 +0000263 SocketType socketType = std::get<0>(GetParam());
264 RpcSecurity rpcSecurity = std::get<1>(GetParam());
265 uint32_t clientVersion = std::get<2>(GetParam());
266 uint32_t serverVersion = std::get<3>(GetParam());
267 bool singleThreaded = std::get<4>(GetParam());
268 bool noKernel = std::get<5>(GetParam());
269
270 std::string path = android::base::GetExecutableDirectory();
271 auto servicePath = android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
272 singleThreaded ? "_single_threaded" : "",
273 noKernel ? "_no_kernel" : "");
274
Alice Wang1ef010b2022-11-14 09:09:25 +0000275 base::unique_fd bootstrapClientFd, socketFd;
276
Alice Wang893a9912022-10-24 10:44:09 +0000277 auto addr = allocateSocketAddress();
278 // Initializes the socket before the fork/exec.
279 if (socketType == SocketType::UNIX_RAW) {
280 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000281 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
282 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
283 // This is because we cannot pass ParcelFileDescriptor over a pipe.
284 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
285 int savedErrno = errno;
286 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
287 }
Alice Wang893a9912022-10-24 10:44:09 +0000288 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000289
Andrei Homescu96834632022-10-14 00:49:49 +0000290 auto ret = std::make_unique<LinuxProcessSession>(
291 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000292 if (socketType == SocketType::TIPC) {
293 // Trusty has a single persistent service
294 return;
295 }
296
Andrei Homescu96834632022-10-14 00:49:49 +0000297 auto writeFd = std::to_string(writeEnd.get());
298 auto readFd = std::to_string(readEnd.get());
299 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
300 NULL);
301 }));
302
303 BinderRpcTestServerConfig serverConfig;
304 serverConfig.numThreads = options.numThreads;
305 serverConfig.socketType = static_cast<int32_t>(socketType);
306 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
307 serverConfig.serverVersion = serverVersion;
308 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000309 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000310 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000311 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
312 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
313 static_cast<int32_t>(mode));
314 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000315 if (socketType != SocketType::TIPC) {
316 writeToFd(ret->host.writeEnd(), serverConfig);
317 }
Andrei Homescu96834632022-10-14 00:49:49 +0000318
319 std::vector<sp<RpcSession>> sessions;
320 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
321 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000322 std::unique_ptr<RpcTransportCtxFactory> factory;
323 if (socketType == SocketType::TIPC) {
324#ifdef __ANDROID_VENDOR__
325 factory = RpcTransportCtxFactoryTipcAndroid::make();
326#else
327 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
328#endif
329 } else {
330 factory = newFactory(rpcSecurity, certVerifier);
331 }
332 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100333 }
334
Andrei Homescu68a55612022-08-02 01:25:15 +0000335 BinderRpcTestServerInfo serverInfo;
336 if (socketType != SocketType::TIPC) {
337 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
338 BinderRpcTestClientInfo clientInfo;
339 for (const auto& session : sessions) {
340 auto& parcelableCert = clientInfo.certs.emplace_back();
341 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
342 }
343 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000344
Andrei Homescu68a55612022-08-02 01:25:15 +0000345 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
346 if (socketType == SocketType::INET) {
347 CHECK_NE(0, serverInfo.port);
348 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000349
Andrei Homescu68a55612022-08-02 01:25:15 +0000350 if (rpcSecurity == RpcSecurity::TLS) {
351 const auto& serverCert = serverInfo.cert.data;
352 CHECK_EQ(OK,
353 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
354 serverCert));
355 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700356 }
357
Andrei Homescu96834632022-10-14 00:49:49 +0000358 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000359
Steven Moreland67f85902023-03-15 01:13:49 +0000360 for (size_t i = 0; i < sessions.size(); i++) {
361 const auto& session = sessions.at(i);
362
363 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
364 ? options.numIncomingConnectionsBySession.at(i)
365 : 0;
366
Andrei Homescu96834632022-10-14 00:49:49 +0000367 CHECK(session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000368 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000369 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000370 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000371
Andrei Homescu96834632022-10-14 00:49:49 +0000372 switch (socketType) {
373 case SocketType::PRECONNECTED:
374 status = session->setupPreconnectedClient({}, [=]() {
375 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
376 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000377 break;
Alice Wang893a9912022-10-24 10:44:09 +0000378 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000379 case SocketType::UNIX:
380 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
381 break;
382 case SocketType::UNIX_BOOTSTRAP:
383 status = session->setupUnixDomainSocketBootstrapClient(
384 base::unique_fd(dup(bootstrapClientFd.get())));
385 break;
386 case SocketType::VSOCK:
387 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
388 break;
389 case SocketType::INET:
390 status = session->setupInetClient("127.0.0.1", serverInfo.port);
391 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000392 case SocketType::TIPC:
393 status = session->setupPreconnectedClient({}, [=]() {
394#ifdef __ANDROID_VENDOR__
395 auto port = trustyIpcPort(serverVersion);
396 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
397 return tipcFd >= 0 ? android::base::unique_fd(tipcFd)
398 : android::base::unique_fd();
399#else
400 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
401 return android::base::unique_fd();
402#endif
403 });
404 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000405 default:
406 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000407 }
Andrei Homescu96834632022-10-14 00:49:49 +0000408 if (options.allowConnectFailure && status != OK) {
409 ret->sessions.clear();
410 break;
411 }
412 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
413 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000414 }
Andrei Homescu96834632022-10-14 00:49:49 +0000415 return ret;
416}
Steven Morelandc1635952021-04-01 16:20:47 +0000417
Andrei Homescua858b0e2022-08-01 23:43:09 +0000418TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
419 if (clientOrServerSingleThreaded()) {
420 GTEST_SKIP() << "This test requires multiple threads";
421 }
422
Steven Moreland5553ac42020-11-11 02:14:45 +0000423 constexpr size_t kNumThreads = 10;
424
Steven Moreland4313d7e2021-07-15 23:41:22 +0000425 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000426
427 EXPECT_OK(proc.rootIface->lock());
428
429 // block all but one thread taking locks
430 std::vector<std::thread> ts;
431 for (size_t i = 0; i < kNumThreads - 1; i++) {
432 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
433 }
434
Steven Morelandd6d816f2022-12-23 01:37:17 +0000435 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000436
437 // other calls still work
438 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
439
Steven Morelandd6d816f2022-12-23 01:37:17 +0000440 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000441 size_t epochMsBefore = epochMillis();
442 // after this, we should never see a response within this time
443 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
444
445 // this call should be blocked for blockTimeMs
446 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
447
448 size_t epochMsAfter = epochMillis();
449 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
450
451 for (auto& t : ts) t.join();
452}
453
Steven Moreland27f620a2023-03-06 19:44:36 +0000454static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000455 size_t epochMsBefore = epochMillis();
456
457 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700458 for (size_t i = 0; i < numCalls; i++) {
459 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000460 }
461
462 for (auto& t : ts) t.join();
463
464 size_t epochMsAfter = epochMillis();
465
Yifan Hong1f44f982021-10-08 17:16:47 -0700466 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000467
468 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700469 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
470}
471
Andrei Homescua858b0e2022-08-01 23:43:09 +0000472TEST_P(BinderRpc, ThreadPoolOverSaturated) {
473 if (clientOrServerSingleThreaded()) {
474 GTEST_SKIP() << "This test requires multiple threads";
475 }
476
Yifan Hong1f44f982021-10-08 17:16:47 -0700477 constexpr size_t kNumThreads = 10;
478 constexpr size_t kNumCalls = kNumThreads + 3;
479 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland27f620a2023-03-06 19:44:36 +0000480 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 250 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700481}
482
Andrei Homescua858b0e2022-08-01 23:43:09 +0000483TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
484 if (clientOrServerSingleThreaded()) {
485 GTEST_SKIP() << "This test requires multiple threads";
486 }
487
Yifan Hong1f44f982021-10-08 17:16:47 -0700488 constexpr size_t kNumThreads = 20;
489 constexpr size_t kNumOutgoingConnections = 10;
490 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
491 auto proc = createRpcTestSocketServerProcess(
492 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland27f620a2023-03-06 19:44:36 +0000493 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 250 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000494}
495
Andrei Homescua858b0e2022-08-01 23:43:09 +0000496TEST_P(BinderRpc, ThreadingStressTest) {
497 if (clientOrServerSingleThreaded()) {
498 GTEST_SKIP() << "This test requires multiple threads";
499 }
500
Steven Moreland27f620a2023-03-06 19:44:36 +0000501 constexpr size_t kNumClientThreads = 5;
502 constexpr size_t kNumServerThreads = 5;
503 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000504
Steven Moreland4313d7e2021-07-15 23:41:22 +0000505 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000506
507 std::vector<std::thread> threads;
508 for (size_t i = 0; i < kNumClientThreads; i++) {
509 threads.push_back(std::thread([&] {
510 for (size_t j = 0; j < kNumCalls; j++) {
511 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000512 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000513 EXPECT_EQ(proc.rootBinder, out);
514 }
515 }));
516 }
517
518 for (auto& t : threads) t.join();
519}
520
Steven Moreland925ba0a2021-09-17 18:06:32 -0700521static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
522 std::vector<std::thread> threads;
523 for (size_t i = 0; i < threadCount; i++) {
524 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
525 }
526 for (auto& t : threads) t.join();
527}
528
Andrei Homescua858b0e2022-08-01 23:43:09 +0000529TEST_P(BinderRpc, OnewayStressTest) {
530 if (clientOrServerSingleThreaded()) {
531 GTEST_SKIP() << "This test requires multiple threads";
532 }
533
Steven Morelandc6046982021-04-20 00:49:42 +0000534 constexpr size_t kNumClientThreads = 10;
535 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700536 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000537
Steven Moreland4313d7e2021-07-15 23:41:22 +0000538 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000539
540 std::vector<std::thread> threads;
541 for (size_t i = 0; i < kNumClientThreads; i++) {
542 threads.push_back(std::thread([&] {
543 for (size_t j = 0; j < kNumCalls; j++) {
544 EXPECT_OK(proc.rootIface->sendString("a"));
545 }
Steven Morelandc6046982021-04-20 00:49:42 +0000546 }));
547 }
548
549 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700550
551 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000552}
553
Frederick Mayleb0221d12022-10-03 23:10:53 +0000554TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
555 if (!supportsFdTransport()) {
556 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
557 }
558 if (clientOrServerSingleThreaded()) {
559 GTEST_SKIP() << "This test requires multiple threads";
560 }
561
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000562 constexpr size_t kNumServerThreads = 3;
563
Frederick Mayleb0221d12022-10-03 23:10:53 +0000564 // This test forces a oneway transaction to be queued by issuing two
565 // `blockingSendFdOneway` calls, then drains the queue by issuing two
566 // `blockingRecvFd` calls.
567 //
568 // For more details about the queuing semantics see
569 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
570
571 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000572 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000573 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
574 .serverSupportedFileDescriptorTransportModes =
575 {RpcSession::FileDescriptorTransportMode::UNIX},
576 });
577
578 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
579 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
580 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
581 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
582
583 android::os::ParcelFileDescriptor fdA;
584 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
585 std::string result;
586 CHECK(android::base::ReadFdToString(fdA.get(), &result));
587 EXPECT_EQ(result, "a");
588
589 android::os::ParcelFileDescriptor fdB;
590 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
591 CHECK(android::base::ReadFdToString(fdB.get(), &result));
592 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000593
594 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000595}
596
Andrei Homescua858b0e2022-08-01 23:43:09 +0000597TEST_P(BinderRpc, OnewayCallQueueing) {
598 if (clientOrServerSingleThreaded()) {
599 GTEST_SKIP() << "This test requires multiple threads";
600 }
601
Steven Moreland5553ac42020-11-11 02:14:45 +0000602 constexpr size_t kNumSleeps = 10;
603 constexpr size_t kNumExtraServerThreads = 4;
604 constexpr size_t kSleepMs = 50;
605
606 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000607 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000608
609 EXPECT_OK(proc.rootIface->lock());
610
Steven Moreland1c678802021-09-17 16:48:47 -0700611 size_t epochMsBefore = epochMillis();
612
613 // all these *Async commands should be queued on the server sequentially,
614 // even though there are multiple threads.
615 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000616 proc.rootIface->sleepMsAsync(kSleepMs);
617 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000618 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
619
Steven Moreland1c678802021-09-17 16:48:47 -0700620 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000621 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700622
Steven Moreland5553ac42020-11-11 02:14:45 +0000623 size_t epochMsAfter = epochMillis();
624
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000625 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000626
Steven Moreland925ba0a2021-09-17 18:06:32 -0700627 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000628}
629
Andrei Homescua858b0e2022-08-01 23:43:09 +0000630TEST_P(BinderRpc, OnewayCallExhaustion) {
631 if (clientOrServerSingleThreaded()) {
632 GTEST_SKIP() << "This test requires multiple threads";
633 }
634
Steven Morelandd45be622021-06-04 02:19:37 +0000635 constexpr size_t kNumClients = 2;
636 constexpr size_t kTooLongMs = 1000;
637
Steven Moreland4313d7e2021-07-15 23:41:22 +0000638 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000639
640 // Build up oneway calls on the second session to make sure it terminates
641 // and shuts down. The first session should be unaffected (proc destructor
642 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000643 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000644
645 std::vector<std::thread> threads;
646 for (size_t i = 0; i < kNumClients; i++) {
647 // one of these threads will get stuck queueing a transaction once the
648 // socket fills up, the other will be able to fill up transactions on
649 // this object
650 threads.push_back(std::thread([&] {
651 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
652 }
653 }));
654 }
655 for (auto& t : threads) t.join();
656
657 Status status = iface->sleepMsAsync(kTooLongMs);
658 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
659
Steven Moreland798e0d12021-07-14 23:19:25 +0000660 // now that it has died, wait for the remote session to shutdown
661 std::vector<int32_t> remoteCounts;
662 do {
663 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
664 } while (remoteCounts.size() == kNumClients);
665
Steven Morelandd45be622021-06-04 02:19:37 +0000666 // the second session should be shutdown in the other process by the time we
667 // are able to join above (it'll only be hung up once it finishes processing
668 // any pending commands). We need to erase this session from the record
669 // here, so that the destructor for our session won't check that this
670 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000671 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000672}
673
Steven Moreland67f85902023-03-15 01:13:49 +0000674TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
675 if (clientOrServerSingleThreaded()) {
676 GTEST_SKIP() << "This test requires multiple threads";
677 }
678
679 // session 0 - will check for leaks in destrutor of proc
680 // session 1 - we want to make sure it gets deleted when we drop all references to it
681 auto proc = createRpcTestSocketServerProcess(
682 {.numThreads = 1, .numIncomingConnectionsBySession = {0, 1}, .numSessions = 2});
683
684 wp<RpcSession> session = proc.proc->sessions.at(1).session;
685
686 // remove all references to the second session
687 proc.proc->sessions.at(1).root = nullptr;
688 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
689
690 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
691 // to drain commands.
692 for (size_t i = 0; i < 100; i++) {
693 usleep(10 * 1000);
694 if (session.promote() == nullptr) break;
695 }
696
697 EXPECT_EQ(nullptr, session.promote());
698}
699
Devin Moore66d5b7a2022-07-07 21:42:10 +0000700TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000701 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000702 GTEST_SKIP() << "This test requires multiple threads";
703 }
704 class MyDeathRec : public IBinder::DeathRecipient {
705 public:
706 void binderDied(const wp<IBinder>& /* who */) override {
707 dead = true;
708 mCv.notify_one();
709 }
710 std::mutex mMtx;
711 std::condition_variable mCv;
712 bool dead = false;
713 };
714
715 // Death recipient needs to have an incoming connection to be called
716 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000717 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000718
719 auto dr = sp<MyDeathRec>::make();
720 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
721
722 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
723 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
724 }
725
726 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000727 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000728
729 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000730 // can't do this before checking the death recipient by calling
731 // forceShutdown earlier, because shutdownAndWait will also trigger
732 // a death recipient, but if we had a way to wait for the service
733 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000734 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000735 proc.expectAlreadyShutdown = true;
736}
737
738TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000739 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000740 GTEST_SKIP() << "This test requires multiple threads";
741 }
742 class MyDeathRec : public IBinder::DeathRecipient {
743 public:
744 void binderDied(const wp<IBinder>& /* who */) override {
745 dead = true;
746 mCv.notify_one();
747 }
748 std::mutex mMtx;
749 std::condition_variable mCv;
750 bool dead = false;
751 };
752
753 // Death recipient needs to have an incoming connection to be called
754 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000755 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000756
757 auto dr = sp<MyDeathRec>::make();
758 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
759
760 // Explicitly calling shutDownAndWait will cause the death recipients
761 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000762 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000763
764 std::unique_lock<std::mutex> lock(dr->mMtx);
765 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000766 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000767 }
768 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
769
Andrei Homescu96834632022-10-14 00:49:49 +0000770 proc.proc->terminate();
771 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000772 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
773 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
774 });
775 proc.expectAlreadyShutdown = true;
776}
777
Steven Moreland5ec743f2023-01-18 01:02:06 +0000778TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000779 if (socketType() == SocketType::TIPC) {
780 // This should work, but Trusty takes too long to restart the service
781 GTEST_SKIP() << "Service death test not supported on Trusty";
782 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000783 class MyDeathRec : public IBinder::DeathRecipient {
784 public:
785 void binderDied(const wp<IBinder>& /* who */) override {}
786 };
787
Steven Moreland67f85902023-03-15 01:13:49 +0000788 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000789
790 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000791 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000792}
793
794TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000795 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000796 GTEST_SKIP() << "This test requires multiple threads";
797 }
798 class MyDeathRec : public IBinder::DeathRecipient {
799 public:
800 void binderDied(const wp<IBinder>& /* who */) override {
801 GTEST_FAIL() << "This should not be called after unlinkToDeath";
802 }
803 };
804
805 // Death recipient needs to have an incoming connection to be called
806 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000807 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000808
809 auto dr = sp<MyDeathRec>::make();
810 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
811 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
812
Steven Moreland67f85902023-03-15 01:13:49 +0000813 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000814}
815
Steven Morelandc1635952021-04-01 16:20:47 +0000816TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000817 if (socketType() == SocketType::TIPC) {
818 // This should work, but Trusty takes too long to restart the service
819 GTEST_SKIP() << "Service death test not supported on Trusty";
820 }
821
Steven Moreland5553ac42020-11-11 02:14:45 +0000822 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000823 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000824
825 // make sure there is some state during crash
826 // 1. we hold their binder
827 sp<IBinderRpcSession> session;
828 EXPECT_OK(proc.rootIface->openSession("happy", &session));
829 // 2. they hold our binder
830 sp<IBinder> binder = new BBinder();
831 EXPECT_OK(proc.rootIface->holdBinder(binder));
832
833 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
834 << "Do death cleanup: " << doDeathCleanup;
835
Andrei Homescu96834632022-10-14 00:49:49 +0000836 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000837 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
838 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
839 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000840 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000841 }
842}
843
Steven Morelandd7302072021-05-15 01:32:04 +0000844TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000845 // This test only works if the current process shared the internal state of
846 // ProcessState with the service across the call to fork(). Both the static
847 // libraries and libbinder.so have their own separate copies of all the
848 // globals, so the test only works when the test client and service both use
849 // libbinder.so (when using static libraries, even a client and service
850 // using the same kind of static library should have separate copies of the
851 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000852 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000853 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
854 "at build time.";
855 }
856
Steven Moreland4313d7e2021-07-15 23:41:22 +0000857 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000858
Andrei Homescu2a298012022-06-15 01:08:54 +0000859 // we can't allocate IPCThreadState so actually the first time should
860 // succeed :(
861 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000862
863 // second time! we catch the error :)
864 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
865
Andrei Homescu96834632022-10-14 00:49:49 +0000866 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000867 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
868 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
869 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000870 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000871}
872
Frederick Mayle69a0c992022-05-26 20:38:39 +0000873TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000874 if (socketType() == SocketType::TIPC) {
875 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
876 }
877
Frederick Mayle69a0c992022-05-26 20:38:39 +0000878 auto proc = createRpcTestSocketServerProcess({
879 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
880 .serverSupportedFileDescriptorTransportModes =
881 {RpcSession::FileDescriptorTransportMode::UNIX},
882 .allowConnectFailure = true,
883 });
Andrei Homescu96834632022-10-14 00:49:49 +0000884 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
885 proc.proc->terminate();
886 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000887 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
888 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
889 });
890 proc.expectAlreadyShutdown = true;
891}
892
893TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000894 if (socketType() == SocketType::TIPC) {
895 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
896 }
897
Frederick Mayle69a0c992022-05-26 20:38:39 +0000898 auto proc = createRpcTestSocketServerProcess({
899 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
900 .serverSupportedFileDescriptorTransportModes =
901 {RpcSession::FileDescriptorTransportMode::NONE},
902 .allowConnectFailure = true,
903 });
Andrei Homescu96834632022-10-14 00:49:49 +0000904 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
905 proc.proc->terminate();
906 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000907 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
908 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
909 });
910 proc.expectAlreadyShutdown = true;
911}
912
913TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000914 if (socketType() == SocketType::TIPC) {
915 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
916 }
917
Frederick Mayle69a0c992022-05-26 20:38:39 +0000918 auto proc = createRpcTestSocketServerProcess({
919 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
920 .serverSupportedFileDescriptorTransportModes =
921 {RpcSession::FileDescriptorTransportMode::NONE,
922 RpcSession::FileDescriptorTransportMode::UNIX},
923 });
924
925 android::os::ParcelFileDescriptor out;
926 auto status = proc.rootIface->echoAsFile("hello", &out);
927 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
928}
929
930TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000931 if (socketType() == SocketType::TIPC) {
932 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
933 }
934
Frederick Mayle69a0c992022-05-26 20:38:39 +0000935 auto proc = createRpcTestSocketServerProcess({
936 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
937 .serverSupportedFileDescriptorTransportModes =
938 {RpcSession::FileDescriptorTransportMode::UNIX},
939 });
940
941 android::os::ParcelFileDescriptor out;
942 auto status = proc.rootIface->echoAsFile("hello", &out);
943 if (!supportsFdTransport()) {
944 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
945 return;
946 }
947 ASSERT_TRUE(status.isOk()) << status;
948
949 std::string result;
950 CHECK(android::base::ReadFdToString(out.get(), &result));
951 EXPECT_EQ(result, "hello");
952}
953
954TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000955 if (socketType() == SocketType::TIPC) {
956 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
957 }
958
Frederick Mayle69a0c992022-05-26 20:38:39 +0000959 auto proc = createRpcTestSocketServerProcess({
960 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
961 .serverSupportedFileDescriptorTransportModes =
962 {RpcSession::FileDescriptorTransportMode::UNIX},
963 });
964
965 std::vector<android::os::ParcelFileDescriptor> files;
966 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
967 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
968 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
969 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
970
971 android::os::ParcelFileDescriptor out;
972 auto status = proc.rootIface->concatFiles(files, &out);
973 if (!supportsFdTransport()) {
974 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
975 return;
976 }
977 ASSERT_TRUE(status.isOk()) << status;
978
979 std::string result;
980 CHECK(android::base::ReadFdToString(out.get(), &result));
981 EXPECT_EQ(result, "123abcd");
982}
983
984TEST_P(BinderRpc, SendMaxFiles) {
985 if (!supportsFdTransport()) {
986 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
987 }
988
989 auto proc = createRpcTestSocketServerProcess({
990 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
991 .serverSupportedFileDescriptorTransportModes =
992 {RpcSession::FileDescriptorTransportMode::UNIX},
993 });
994
995 std::vector<android::os::ParcelFileDescriptor> files;
996 for (int i = 0; i < 253; i++) {
997 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
998 }
999
1000 android::os::ParcelFileDescriptor out;
1001 auto status = proc.rootIface->concatFiles(files, &out);
1002 ASSERT_TRUE(status.isOk()) << status;
1003
1004 std::string result;
1005 CHECK(android::base::ReadFdToString(out.get(), &result));
1006 EXPECT_EQ(result, std::string(253, 'a'));
1007}
1008
1009TEST_P(BinderRpc, SendTooManyFiles) {
1010 if (!supportsFdTransport()) {
1011 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1012 }
1013
1014 auto proc = createRpcTestSocketServerProcess({
1015 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1016 .serverSupportedFileDescriptorTransportModes =
1017 {RpcSession::FileDescriptorTransportMode::UNIX},
1018 });
1019
1020 std::vector<android::os::ParcelFileDescriptor> files;
1021 for (int i = 0; i < 254; i++) {
1022 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1023 }
1024
1025 android::os::ParcelFileDescriptor out;
1026 auto status = proc.rootIface->concatFiles(files, &out);
1027 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1028}
1029
Andrei Homescufc221502022-10-08 03:51:17 +00001030TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001031 if (socketType() == SocketType::TIPC) {
1032 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1033 }
1034
Andrei Homescufc221502022-10-08 03:51:17 +00001035 auto proc = createRpcTestSocketServerProcess({
1036 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1037 .serverSupportedFileDescriptorTransportModes =
1038 {RpcSession::FileDescriptorTransportMode::UNIX},
1039 });
1040
1041 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1042 ASSERT_NE(badFd, -1);
1043
1044 // Close the file descriptor so it becomes invalid for dup
1045 close(badFd);
1046
1047 Parcel p1;
1048 p1.markForBinder(proc.rootBinder);
1049 p1.writeInt32(3);
1050 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1051
1052 Parcel pRaw;
1053 pRaw.markForBinder(proc.rootBinder);
1054 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1055
1056 pRaw.setDataPosition(0);
1057 EXPECT_EQ(3, pRaw.readInt32());
1058 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1059}
1060
Andrei Homescu68a55612022-08-02 01:25:15 +00001061#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001062TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001063 if constexpr (!kEnableSharedLibs) {
1064 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1065 }
1066
Steven Moreland4313d7e2021-07-15 23:41:22 +00001067 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001068
1069 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1070 ASSERT_NE(binder, nullptr);
1071
1072 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1073}
1074
1075TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001076 if constexpr (!kEnableSharedLibs) {
1077 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1078 }
1079
Steven Moreland4313d7e2021-07-15 23:41:22 +00001080 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001081
1082 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1083 ASSERT_NE(binder, nullptr);
1084
1085 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1086 ASSERT_NE(ndkBinder, nullptr);
1087
1088 std::string out;
1089 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1090 ASSERT_TRUE(status.isOk()) << status.getDescription();
1091 ASSERT_EQ("aoeuaoeu", out);
1092}
Andrei Homescu68a55612022-08-02 01:25:15 +00001093#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001094
Steven Moreland5553ac42020-11-11 02:14:45 +00001095ssize_t countFds() {
1096 DIR* dir = opendir("/proc/self/fd/");
1097 if (dir == nullptr) return -1;
1098 ssize_t ret = 0;
1099 dirent* ent;
1100 while ((ent = readdir(dir)) != nullptr) ret++;
1101 closedir(dir);
1102 return ret;
1103}
1104
Andrei Homescua858b0e2022-08-01 23:43:09 +00001105TEST_P(BinderRpc, Fds) {
1106 if (serverSingleThreaded()) {
1107 GTEST_SKIP() << "This test requires multiple threads";
1108 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001109 if (socketType() == SocketType::TIPC) {
1110 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1111 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001112
Steven Moreland5553ac42020-11-11 02:14:45 +00001113 ssize_t beforeFds = countFds();
1114 ASSERT_GE(beforeFds, 0);
1115 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001116 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001117 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1118 }
1119 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1120}
1121
Steven Morelandda573042021-06-12 01:13:45 +00001122static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001123 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001124 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001125
Andrei Homescu992a4052022-06-28 21:26:18 +00001126 android::base::unique_fd serverFd(
1127 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1128 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1129
1130 sockaddr_vm serverAddr{
1131 .svm_family = AF_VSOCK,
1132 .svm_port = vsockPort,
1133 .svm_cid = VMADDR_CID_ANY,
1134 };
1135 int ret = TEMP_FAILURE_RETRY(
1136 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1137 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1138 strerror(errno));
1139
1140 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1141 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1142 strerror(errno));
1143
1144 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1145 // to see if the kernel supports it. It's safe to use a blocking
1146 // connect because vsock sockets have a 2 second connection timeout,
1147 // and they return ETIMEDOUT after that.
1148 android::base::unique_fd connectFd(
1149 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1150 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1151 strerror(errno));
1152
1153 bool success = false;
1154 sockaddr_vm connectAddr{
1155 .svm_family = AF_VSOCK,
1156 .svm_port = vsockPort,
1157 .svm_cid = VMADDR_CID_LOCAL,
1158 };
1159 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1160 sizeof(connectAddr)));
1161 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1162 android::base::unique_fd acceptFd;
1163 while (true) {
1164 pollfd pfd[]{
1165 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1166 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1167 };
1168 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1169 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1170
1171 if (pfd[0].revents & POLLIN) {
1172 sockaddr_vm acceptAddr;
1173 socklen_t acceptAddrLen = sizeof(acceptAddr);
1174 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1175 reinterpret_cast<sockaddr*>(&acceptAddr),
1176 &acceptAddrLen, SOCK_CLOEXEC));
1177 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1178 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1179 "Truncated address");
1180
1181 // Store the fd in acceptFd so we keep the connection alive
1182 // while polling connectFd
1183 acceptFd.reset(ret);
1184 }
1185
1186 if (pfd[1].revents & POLLOUT) {
1187 // Connect either succeeded or timed out
1188 int connectErrno;
1189 socklen_t connectErrnoLen = sizeof(connectErrno);
1190 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1191 &connectErrnoLen);
1192 LOG_ALWAYS_FATAL_IF(ret == -1,
1193 "Could not getsockopt() after connect() "
1194 "on non-blocking socket: %s.",
1195 strerror(errno));
1196
1197 // We're done, this is all we wanted
1198 success = connectErrno == 0;
1199 break;
1200 }
1201 }
1202 } else {
1203 success = ret == 0;
1204 }
1205
1206 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1207
1208 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001209}
1210
Yifan Hong1deca4b2021-09-10 16:16:44 -07001211static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001212 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1213 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001214
1215 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001216
1217 static bool hasVsockLoopback = testSupportVsockLoopback();
1218
1219 if (hasVsockLoopback) {
1220 ret.push_back(SocketType::VSOCK);
1221 }
1222
1223 return ret;
1224}
1225
Andrei Homescu68a55612022-08-02 01:25:15 +00001226static std::vector<SocketType> testTipcSocketTypes() {
1227#ifdef __ANDROID_VENDOR__
1228 auto port = trustyIpcPort(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1229 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
1230 if (tipcFd >= 0) {
1231 close(tipcFd);
1232 return {SocketType::TIPC};
1233 }
1234#endif // __ANDROID_VENDOR__
1235
1236 // TIPC is not supported on this device, most likely
1237 // because /dev/trusty-ipc-dev0 is missing
1238 return {};
1239}
1240
Yifan Hong702115c2021-06-24 15:39:18 -07001241INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1242 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001243 ::testing::ValuesIn(RpcSecurityValues()),
1244 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001245 ::testing::ValuesIn(testVersions()),
1246 ::testing::Values(false, true),
1247 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001248 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001249
Andrei Homescu68a55612022-08-02 01:25:15 +00001250INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc,
1251 ::testing::Combine(::testing::ValuesIn(testTipcSocketTypes()),
1252 ::testing::Values(RpcSecurity::RAW),
1253 ::testing::ValuesIn(testVersions()),
1254 ::testing::ValuesIn(testVersions()),
1255 ::testing::Values(true), ::testing::Values(true)),
1256 BinderRpc::PrintParamInfo);
1257
Yifan Hong702115c2021-06-24 15:39:18 -07001258class BinderRpcServerRootObject
1259 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001260
1261TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1262 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1263 auto setRootObject = [](bool isStrong) -> SetFn {
1264 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1265 };
1266
Yifan Hong702115c2021-06-24 15:39:18 -07001267 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1268 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001269 auto binder1 = sp<BBinder>::make();
1270 IBinder* binderRaw1 = binder1.get();
1271 setRootObject(isStrong1)(server.get(), binder1);
1272 EXPECT_EQ(binderRaw1, server->getRootObject());
1273 binder1.clear();
1274 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1275
1276 auto binder2 = sp<BBinder>::make();
1277 IBinder* binderRaw2 = binder2.get();
1278 setRootObject(isStrong2)(server.get(), binder2);
1279 EXPECT_EQ(binderRaw2, server->getRootObject());
1280 binder2.clear();
1281 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1282}
1283
1284INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001285 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1286 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001287
Yifan Hong1a235852021-05-13 16:07:47 -07001288class OneOffSignal {
1289public:
1290 // If notify() was previously called, or is called within |duration|, return true; else false.
1291 template <typename R, typename P>
1292 bool wait(std::chrono::duration<R, P> duration) {
1293 std::unique_lock<std::mutex> lock(mMutex);
1294 return mCv.wait_for(lock, duration, [this] { return mValue; });
1295 }
1296 void notify() {
1297 std::unique_lock<std::mutex> lock(mMutex);
1298 mValue = true;
1299 lock.unlock();
1300 mCv.notify_all();
1301 }
1302
1303private:
1304 std::mutex mMutex;
1305 std::condition_variable mCv;
1306 bool mValue = false;
1307};
1308
Yifan Hong194acf22021-06-29 18:44:56 -07001309TEST(BinderRpc, Java) {
1310#if !defined(__ANDROID__)
1311 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1312 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1313 "to binderHostDeviceTest. Hence, just disable this test on host.";
1314#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001315 if constexpr (!kEnableKernelIpc) {
1316 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1317 "at build time.";
1318 }
1319
Yifan Hong194acf22021-06-29 18:44:56 -07001320 sp<IServiceManager> sm = defaultServiceManager();
1321 ASSERT_NE(nullptr, sm);
1322 // Any Java service with non-empty getInterfaceDescriptor() would do.
1323 // Let's pick batteryproperties.
1324 auto binder = sm->checkService(String16("batteryproperties"));
1325 ASSERT_NE(nullptr, binder);
1326 auto descriptor = binder->getInterfaceDescriptor();
1327 ASSERT_GE(descriptor.size(), 0);
1328 ASSERT_EQ(OK, binder->pingBinder());
1329
1330 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001331 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001332 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001333 auto socket = rpcServer->releaseServer();
1334
1335 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001336 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1337
Yifan Honge3caaf22022-01-12 14:46:56 -08001338 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1339 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001340 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001341 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1342 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001343 << statusToString(setRpcClientDebugStatus);
1344 GTEST_SKIP();
1345 }
1346
1347 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001348
1349 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001350 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001351 auto rpcBinder = rpcSession->getRootObject();
1352 ASSERT_NE(nullptr, rpcBinder);
1353
1354 ASSERT_EQ(OK, rpcBinder->pingBinder());
1355
1356 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1357 << "getInterfaceDescriptor should not crash system_server";
1358 ASSERT_EQ(OK, rpcBinder->pingBinder());
1359}
1360
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001361class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1362public:
1363 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1364 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1365 std::to_string(std::get<1>(info.param));
1366 }
1367};
1368
1369TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1370 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1371 int sinkFd = sink.get();
1372 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1373 server->setProtocolVersion(std::get<1>(GetParam()));
1374 ASSERT_FALSE(server->hasServer());
1375 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1376 ASSERT_TRUE(server->hasServer());
1377 base::unique_fd retrieved = server->releaseServer();
1378 ASSERT_FALSE(server->hasServer());
1379 ASSERT_EQ(sinkFd, retrieved.get());
1380}
1381
1382TEST_P(BinderRpcServerOnly, Shutdown) {
1383 if constexpr (!kEnableRpcThreads) {
1384 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1385 }
1386
1387 auto addr = allocateSocketAddress();
1388 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1389 server->setProtocolVersion(std::get<1>(GetParam()));
1390 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1391 auto joinEnds = std::make_shared<OneOffSignal>();
1392
1393 // If things are broken and the thread never stops, don't block other tests. Because the thread
1394 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1395 // shared pointers are passed.
1396 std::thread([server, joinEnds] {
1397 server->join();
1398 joinEnds->notify();
1399 }).detach();
1400
1401 bool shutdown = false;
1402 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001403 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001404 if (server->shutdown()) shutdown = true;
1405 }
1406 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1407
1408 ASSERT_TRUE(joinEnds->wait(2s))
1409 << "After server->shutdown() returns true, join() did not stop after 2s";
1410}
1411
Frederick Mayledc07cf82022-05-26 20:30:12 +00001412INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1413 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1414 ::testing::ValuesIn(testVersions())),
1415 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001416
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001417class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001418public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001419 // Only parameterized only server version because `RpcSession` is bypassed
1420 // in the client half of the tests.
1421 using Param =
1422 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001423 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001424
1425 // A server that handles client socket connections.
1426 class Server {
1427 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001428 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1429
Yifan Hong1deca4b2021-09-10 16:16:44 -07001430 explicit Server() {}
1431 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001432 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001433 [[nodiscard]] AssertionResult setUp(
1434 const Param& param,
1435 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001436 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001437 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001438 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001439 switch (socketType) {
1440 case SocketType::PRECONNECTED: {
1441 return AssertionFailure() << "Not supported by this test";
1442 } break;
1443 case SocketType::UNIX: {
1444 auto addr = allocateSocketAddress();
1445 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1446 if (status != OK) {
1447 return AssertionFailure()
1448 << "setupUnixDomainServer: " << statusToString(status);
1449 }
1450 mConnectToServer = [addr] {
1451 return connectTo(UnixSocketAddress(addr.c_str()));
1452 };
1453 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001454 case SocketType::UNIX_BOOTSTRAP: {
1455 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1456 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1457 return AssertionFailure() << "Socketpair() failed";
1458 }
1459 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1460 std::move(bootstrapFdServer));
1461 if (status != OK) {
1462 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1463 << statusToString(status);
1464 }
1465 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1466 mAcceptConnection = &Server::recvmsgServerConnection;
1467 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1468 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001469 case SocketType::UNIX_RAW: {
1470 auto addr = allocateSocketAddress();
1471 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1472 if (status != OK) {
1473 return AssertionFailure()
1474 << "setupRawSocketServer: " << statusToString(status);
1475 }
1476 mConnectToServer = [addr] {
1477 return connectTo(UnixSocketAddress(addr.c_str()));
1478 };
1479 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001480 case SocketType::VSOCK: {
1481 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001482 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001483 if (status != OK) {
1484 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1485 }
1486 mConnectToServer = [port] {
1487 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1488 };
1489 } break;
1490 case SocketType::INET: {
1491 unsigned int port;
1492 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1493 if (status != OK) {
1494 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1495 }
1496 mConnectToServer = [port] {
1497 const char* addr = kLocalInetAddress;
1498 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1499 if (aiStart == nullptr) return base::unique_fd{};
1500 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1501 auto fd = connectTo(
1502 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1503 if (fd.ok()) return fd;
1504 }
1505 ALOGE("None of the socket address resolved for %s:%u can be connected",
1506 addr, port);
1507 return base::unique_fd{};
1508 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001509 } break;
1510 case SocketType::TIPC: {
1511 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1512 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001513 }
1514 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001515 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001516 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001517 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1518 mSetup = true;
1519 return AssertionSuccess();
1520 }
1521 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1522 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1523 return mCertVerifier;
1524 }
1525 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1526 void start() {
1527 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1528 mThread = std::make_unique<std::thread>(&Server::run, this);
1529 }
David Brazdil21c887c2022-09-23 12:25:18 +01001530
1531 base::unique_fd acceptServerConnection() {
1532 return base::unique_fd(TEMP_FAILURE_RETRY(
1533 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1534 }
1535
1536 base::unique_fd recvmsgServerConnection() {
1537 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1538 int buf;
1539 iovec iov{&buf, sizeof(buf)};
1540
1541 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1542 int savedErrno = errno;
1543 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1544 }
1545 if (fds.size() != 1) {
1546 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1547 }
1548 return std::move(std::get<base::unique_fd>(fds[0]));
1549 }
1550
Yifan Hong1deca4b2021-09-10 16:16:44 -07001551 void run() {
1552 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1553
1554 std::vector<std::thread> threads;
1555 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001556 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001557 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1558 }
1559
1560 for (auto& thread : threads) thread.join();
1561 }
1562 void handleOne(android::base::unique_fd acceptedFd) {
1563 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001564 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001565 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001566 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001567 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001568 }
Yifan Honge07d2732021-09-13 21:59:14 -07001569 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001570 shutdown();
1571 join();
1572 }
1573 void shutdown() { mFdTrigger->trigger(); }
1574
1575 void setPostConnect(
1576 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1577 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001578 }
1579
1580 private:
1581 std::unique_ptr<std::thread> mThread;
1582 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001583 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001584 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001585 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001586 std::unique_ptr<RpcTransportCtx> mCtx;
1587 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1588 std::make_shared<RpcCertificateVerifierSimple>();
1589 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001590 // The function invoked after connection and handshake. By default, it is
1591 // |defaultPostConnect| that sends |kMessage| to the client.
1592 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1593 Server::defaultPostConnect;
1594
1595 void join() {
1596 if (mThread != nullptr) {
1597 mThread->join();
1598 mThread = nullptr;
1599 }
1600 }
1601
1602 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1603 FdTrigger* fdTrigger) {
1604 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001605 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001606 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001607 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001608 if (status != OK) return AssertionFailure() << statusToString(status);
1609 return AssertionSuccess();
1610 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001611 };
1612
1613 class Client {
1614 public:
1615 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1616 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001617 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001618 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1619 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001620 mFdTrigger = FdTrigger::make();
1621 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1622 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1623 return AssertionSuccess();
1624 }
1625 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1626 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1627 return mCertVerifier;
1628 }
Yifan Hong67519322021-09-13 18:51:16 -07001629 // connect() and do handshake
1630 bool setUpTransport() {
1631 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001632 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001633 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1634 return mClientTransport != nullptr;
1635 }
1636 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1637 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1638 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001639 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001640 status_t readStatus =
1641 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001642 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001643 if (readStatus != OK) {
1644 return AssertionFailure() << statusToString(readStatus);
1645 }
1646 if (readMessage != expectedMessage) {
1647 return AssertionFailure()
1648 << "Expected " << expectedMessage << ", actual " << readMessage;
1649 }
1650 return AssertionSuccess();
1651 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001652 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001653 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001654 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1655 return;
1656 }
1657 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001658 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001659 }
1660
Pawan49d74cb2022-08-03 21:19:11 +00001661 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1662
Yifan Hong1deca4b2021-09-10 16:16:44 -07001663 private:
1664 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001665 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001666 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1667 std::unique_ptr<RpcTransportCtx> mCtx;
1668 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1669 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001670 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001671 };
1672
1673 // Make A trust B.
1674 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001675 static status_t trust(RpcSecurity rpcSecurity,
1676 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1677 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001678 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001679 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1680 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1681 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001682 }
1683
1684 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001685};
1686
1687class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1688public:
1689 using Server = RpcTransportTestUtils::Server;
1690 using Client = RpcTransportTestUtils::Client;
1691 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001692 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001693 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1694 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001695 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001696 return ret;
1697 }
1698 static std::vector<ParamType> getRpcTranportTestParams() {
1699 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001700 for (auto serverVersion : testVersions()) {
1701 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1702 for (auto rpcSecurity : RpcSecurityValues()) {
1703 switch (rpcSecurity) {
1704 case RpcSecurity::RAW: {
1705 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1706 } break;
1707 case RpcSecurity::TLS: {
1708 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1709 serverVersion);
1710 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1711 serverVersion);
1712 } break;
1713 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001714 }
1715 }
1716 }
1717 return ret;
1718 }
1719 template <typename A, typename B>
1720 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001721 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1722 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001723 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1724 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001725 void SetUp() override {
1726 if constexpr (!kEnableRpcThreads) {
1727 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1728 }
1729 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001730};
1731
1732TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001733 auto server = std::make_unique<Server>();
1734 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001735
1736 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001737 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001738
1739 ASSERT_EQ(OK, trust(&client, server));
1740 ASSERT_EQ(OK, trust(server, &client));
1741
1742 server->start();
1743 client.run();
1744}
1745
1746TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001747 auto server = std::make_unique<Server>();
1748 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001749
1750 std::vector<Client> clients;
1751 for (int i = 0; i < 2; i++) {
1752 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001753 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001754 ASSERT_EQ(OK, trust(&client, server));
1755 ASSERT_EQ(OK, trust(server, &client));
1756 }
1757
1758 server->start();
1759 for (auto& client : clients) client.run();
1760}
1761
1762TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001763 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1764 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001765
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001766 auto untrustedServer = std::make_unique<Server>();
1767 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001768
1769 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001770 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001771
1772 ASSERT_EQ(OK, trust(untrustedServer, &client));
1773
1774 untrustedServer->start();
1775
1776 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1777 // the client can't verify the server's identity.
1778 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1779 client.run(handshakeOk);
1780}
1781TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001782 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1783 (void)serverVersion;
1784
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001785 auto validServer = std::make_unique<Server>();
1786 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001787
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001788 auto maliciousServer = std::make_unique<Server>();
1789 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001790
1791 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001792 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001793
1794 ASSERT_EQ(OK, trust(&client, validServer));
1795 ASSERT_EQ(OK, trust(validServer, &client));
1796 ASSERT_EQ(OK, trust(maliciousServer, &client));
1797
1798 maliciousServer->start();
1799
1800 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1801 // the client can't verify the server's identity.
1802 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1803 client.run(handshakeOk);
1804}
1805
1806TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001807 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1808 (void)serverVersion;
1809
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001810 auto server = std::make_unique<Server>();
1811 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001812
1813 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001814 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001815
1816 ASSERT_EQ(OK, trust(&client, server));
1817
1818 server->start();
1819
1820 // For TLS, Client should be able to verify server's identity, so client should see
1821 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1822 // identity and should drop the connection, so client shouldn't be able to read anything.
1823 bool readOk = rpcSecurity != RpcSecurity::TLS;
1824 client.run(true, readOk);
1825}
1826
1827TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001828 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1829 (void)serverVersion;
1830
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001831 auto server = std::make_unique<Server>();
1832 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001833
1834 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001835 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001836 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001837 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001838
1839 ASSERT_EQ(OK, trust(&validClient, server));
1840 ASSERT_EQ(OK, trust(&maliciousClient, server));
1841
1842 server->start();
1843
1844 // See UntrustedClient.
1845 bool readOk = rpcSecurity != RpcSecurity::TLS;
1846 maliciousClient.run(true, readOk);
1847}
1848
Yifan Hong67519322021-09-13 18:51:16 -07001849TEST_P(RpcTransportTest, Trigger) {
1850 std::string msg2 = ", world!";
1851 std::mutex writeMutex;
1852 std::condition_variable writeCv;
1853 bool shouldContinueWriting = false;
1854 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001855 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001856 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001857 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1858 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001859 if (status != OK) return AssertionFailure() << statusToString(status);
1860
1861 {
1862 std::unique_lock<std::mutex> lock(writeMutex);
1863 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1864 return AssertionFailure() << "write barrier not cleared in time!";
1865 }
1866 }
1867
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001868 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001869 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1870 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001871 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001872 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001873 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001874 << statusToString(status);
1875 return AssertionSuccess();
1876 };
1877
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001878 auto server = std::make_unique<Server>();
1879 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001880
1881 // Set up client
1882 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001883 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001884
1885 // Exchange keys
1886 ASSERT_EQ(OK, trust(&client, server));
1887 ASSERT_EQ(OK, trust(server, &client));
1888
1889 server->setPostConnect(serverPostConnect);
1890
Yifan Hong67519322021-09-13 18:51:16 -07001891 server->start();
1892 // connect() to server and do handshake
1893 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001894 // read the first message. This ensures that server has finished handshake and start handling
1895 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001896 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001897 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1898 // write is on an FdTrigger that has been shut down.
1899 server->shutdown();
1900 // Continues server thread to write the second message.
1901 {
Yifan Hong22211f82021-09-14 12:32:25 -07001902 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001903 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001904 }
Yifan Hong22211f82021-09-14 12:32:25 -07001905 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001906 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001907 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001908 // On the client side, second read fails with DEAD_OBJECT
1909 ASSERT_FALSE(client.readMessage(msg2));
1910}
1911
Pawan49d74cb2022-08-03 21:19:11 +00001912TEST_P(RpcTransportTest, CheckWaitingForRead) {
1913 std::mutex readMutex;
1914 std::condition_variable readCv;
1915 bool shouldContinueReading = false;
1916 // Server will write data on transport once its started
1917 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1918 std::string message(RpcTransportTestUtils::kMessage);
1919 iovec messageIov{message.data(), message.size()};
1920 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1921 std::nullopt, nullptr);
1922 if (status != OK) return AssertionFailure() << statusToString(status);
1923
1924 {
1925 std::unique_lock<std::mutex> lock(readMutex);
1926 shouldContinueReading = true;
1927 lock.unlock();
1928 readCv.notify_all();
1929 }
1930 return AssertionSuccess();
1931 };
1932
1933 // Setup Server and client
1934 auto server = std::make_unique<Server>();
1935 ASSERT_TRUE(server->setUp(GetParam()));
1936
1937 Client client(server->getConnectToServerFn());
1938 ASSERT_TRUE(client.setUp(GetParam()));
1939
1940 ASSERT_EQ(OK, trust(&client, server));
1941 ASSERT_EQ(OK, trust(server, &client));
1942 server->setPostConnect(serverPostConnect);
1943
1944 server->start();
1945 ASSERT_TRUE(client.setUpTransport());
1946 {
1947 // Wait till server writes data
1948 std::unique_lock<std::mutex> lock(readMutex);
1949 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1950 }
1951
1952 // Since there is no read polling here, we will get polling count 0
1953 ASSERT_FALSE(client.isTransportWaiting());
1954 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1955 // Thread should increment polling count, read and decrement polling count
1956 // Again, polling count should be zero here
1957 ASSERT_FALSE(client.isTransportWaiting());
1958
1959 server->shutdown();
1960}
1961
Yifan Hong1deca4b2021-09-10 16:16:44 -07001962INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001963 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001964 RpcTransportTest::PrintParamInfo);
1965
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001966class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001967 : public testing::TestWithParam<
1968 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001969public:
1970 template <typename A, typename B>
1971 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001972 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1973 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001974 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1975 }
1976 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001977 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1978 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1979 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001980 };
1981};
1982
1983TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001984 if constexpr (!kEnableRpcThreads) {
1985 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1986 }
1987
Frederick Mayledc07cf82022-05-26 20:30:12 +00001988 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001989
1990 std::vector<uint8_t> pkeyData, certData;
1991 {
1992 auto pkey = makeKeyPairForSelfSignedCert();
1993 ASSERT_NE(nullptr, pkey);
1994 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1995 ASSERT_NE(nullptr, cert);
1996 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1997 certData = serializeCertificate(cert.get(), certificateFormat);
1998 }
1999
2000 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2001 auto desCert = deserializeCertificate(certData, certificateFormat);
2002 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002003 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2004 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002005
2006 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2007 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2008
2009 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2010 ASSERT_TRUE(client.setUp(utilsParam));
2011
2012 ASSERT_EQ(OK, trust(&client, server));
2013 ASSERT_EQ(OK, trust(server, &client));
2014
2015 server->start();
2016 client.run();
2017}
2018
2019INSTANTIATE_TEST_CASE_P(
2020 BinderRpc, RpcTransportTlsKeyTest,
2021 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2022 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002023 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2024 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002025 RpcTransportTlsKeyTest::PrintParamInfo);
2026
Steven Morelandc1635952021-04-01 16:20:47 +00002027} // namespace android
2028
2029int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002030 ::testing::InitGoogleTest(&argc, argv);
2031 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002032
Steven Moreland5553ac42020-11-11 02:14:45 +00002033 return RUN_ALL_TESTS();
2034}