blob: 5d5b5303d3f4bd8586777b06dad5991fbe829d9b [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
Frederick Maylea12b0962022-06-25 01:13:22 +000017#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000018#include <gtest/gtest.h>
19
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 Homescu2a298012022-06-15 01:08:54 +000031#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000032#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000033
Yifan Hong1a235852021-05-13 16:07:47 -070034using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070035using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070036using testing::AssertionFailure;
37using testing::AssertionResult;
38using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070039
Steven Moreland5553ac42020-11-11 02:14:45 +000040namespace android {
41
Andrei Homescu12106de2022-04-27 04:42:21 +000042#ifdef BINDER_TEST_NO_SHARED_LIBS
43constexpr bool kEnableSharedLibs = false;
44#else
45constexpr bool kEnableSharedLibs = true;
46#endif
47
Steven Morelandbf57bce2021-07-26 15:26:12 -070048static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
49 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Frederick Mayle69a0c992022-05-26 20:38:39 +000050
Steven Moreland1fda67b2021-04-02 18:35:50 +000051TEST(BinderRpcParcel, EntireParcelFormatted) {
52 Parcel p;
53 p.writeInt32(3);
54
Devin Moore66d5b7a2022-07-07 21:42:10 +000055 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "format must be set before data is written");
Steven Moreland1fda67b2021-04-02 18:35:50 +000056}
57
Steven Morelandbf57bce2021-07-26 15:26:12 -070058TEST(BinderRpc, CannotUseNextWireVersion) {
59 auto session = RpcSession::make();
60 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
61 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
62 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
63 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
64}
65
66TEST(BinderRpc, CanUseExperimentalWireVersion) {
67 auto session = RpcSession::make();
68 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
69}
70
Frederick Maylea12b0962022-06-25 01:13:22 +000071static std::string WaitStatusToString(int wstatus) {
72 if (WIFEXITED(wstatus)) {
73 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
74 }
75 if (WIFSIGNALED(wstatus)) {
76 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
77 }
78 return base::StringPrintf("unexpected state %d", wstatus);
79}
80
Steven Moreland276d8df2022-09-28 23:56:39 +000081static void debugBacktrace(pid_t pid) {
82 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
83 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
84}
85
Steven Moreland5553ac42020-11-11 02:14:45 +000086class Process {
87public:
Andrei Homescu96834632022-10-14 00:49:49 +000088 Process(Process&& other)
89 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
90 mReadEnd(std::move(other.mReadEnd)),
91 mWriteEnd(std::move(other.mWriteEnd)) {
92 // The default move constructor doesn't clear mPid after moving it,
93 // which we need to do because the destructor checks for mPid!=0
94 mPid = other.mPid;
95 other.mPid = 0;
96 }
Yifan Hong1deca4b2021-09-10 16:16:44 -070097 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
98 android::base::borrowed_fd /* readEnd */)>& f) {
99 android::base::unique_fd childWriteEnd;
100 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +0000101 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
102 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000103 if (0 == (mPid = fork())) {
104 // racey: assume parent doesn't crash before this is set
105 prctl(PR_SET_PDEATHSIG, SIGHUP);
106
Yifan Hong1deca4b2021-09-10 16:16:44 -0700107 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000108
109 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000110 }
111 }
112 ~Process() {
113 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000114 int wstatus;
115 waitpid(mPid, &wstatus, 0);
116 if (mCustomExitStatusCheck) {
117 mCustomExitStatusCheck(wstatus);
118 } else {
119 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
120 << "server process failed: " << WaitStatusToString(wstatus);
121 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000122 }
123 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700124 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700125 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000126
Frederick Maylea12b0962022-06-25 01:13:22 +0000127 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
128 mCustomExitStatusCheck = std::move(f);
129 }
130
Frederick Mayle69a0c992022-05-26 20:38:39 +0000131 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
132 void terminate() { kill(mPid, SIGTERM); }
133
Steven Moreland276d8df2022-09-28 23:56:39 +0000134 pid_t getPid() { return mPid; }
135
Steven Moreland5553ac42020-11-11 02:14:45 +0000136private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000137 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000138 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700139 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700140 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000141};
142
143static std::string allocateSocketAddress() {
144 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000145 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700146 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
147 unlink(ret.c_str());
148 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000149};
150
Steven Morelandda573042021-06-12 01:13:45 +0000151static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000152 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000153 return vsockPort++;
154}
155
Andrei Homescu96834632022-10-14 00:49:49 +0000156// Destructors need to be defined, even if pure virtual
157ProcessSession::~ProcessSession() {}
158
159class LinuxProcessSession : public ProcessSession {
160public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000161 // reference to process hosting a socket server
162 Process host;
163
Andrei Homescu96834632022-10-14 00:49:49 +0000164 LinuxProcessSession(LinuxProcessSession&&) = default;
165 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
166 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000167 for (auto& session : sessions) {
168 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000169 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000170
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000171 for (auto& info : sessions) {
172 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000173
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000174 EXPECT_NE(nullptr, session);
175 EXPECT_NE(nullptr, session->state());
176 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000177
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000178 wp<RpcSession> weakSession = session;
179 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000180
Steven Moreland57042712022-10-04 23:56:45 +0000181 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
182 // the object should not actually be promotable. By looping, we distinguish a race here
183 // from a bug causing the object to not be promotable.
184 for (size_t i = 0; i < 3; i++) {
185 sp<RpcSession> strongSession = weakSession.promote();
186 EXPECT_EQ(nullptr, strongSession)
187 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
188 "Leaked sess: ")
189 << strongSession->getStrongCount() << " checked time " << i;
190
191 if (strongSession != nullptr) {
192 sleep(1);
193 }
194 }
Steven Moreland736664b2021-05-01 04:27:25 +0000195 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000196 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000197
Andrei Homescu96834632022-10-14 00:49:49 +0000198 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
199 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000200 }
Andrei Homescu96834632022-10-14 00:49:49 +0000201
202 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000203};
204
Yifan Hong1deca4b2021-09-10 16:16:44 -0700205static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700206 base::unique_fd serverFd(
207 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
208 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700209 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
210 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700211
212 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
213 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700214 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
215 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700216 }
217 return serverFd;
218}
219
David Brazdil21c887c2022-09-23 12:25:18 +0100220static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
221 base::unique_fd sockClient, sockServer;
222 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
223 int savedErrno = errno;
224 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
225 }
226
227 int zero = 0;
228 iovec iov{&zero, sizeof(zero)};
229 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
230 fds.emplace_back(std::move(sockServer));
231
232 if (sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
233 int savedErrno = errno;
234 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
235 }
236 return std::move(sockClient);
237}
238
Andrei Homescu96834632022-10-14 00:49:49 +0000239std::string BinderRpc::PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
240 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
241 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
242 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
243 if (singleThreaded) {
244 ret += "_single_threaded";
245 }
246 if (noKernel) {
247 ret += "_no_kernel";
248 }
249 return ret;
250}
Andrei Homescu2a298012022-06-15 01:08:54 +0000251
Andrei Homescu96834632022-10-14 00:49:49 +0000252// This creates a new process serving an interface on a certain number of
253// threads.
254std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
255 const BinderRpcOptions& options) {
256 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000257
Andrei Homescu96834632022-10-14 00:49:49 +0000258 SocketType socketType = std::get<0>(GetParam());
259 RpcSecurity rpcSecurity = std::get<1>(GetParam());
260 uint32_t clientVersion = std::get<2>(GetParam());
261 uint32_t serverVersion = std::get<3>(GetParam());
262 bool singleThreaded = std::get<4>(GetParam());
263 bool noKernel = std::get<5>(GetParam());
264
265 std::string path = android::base::GetExecutableDirectory();
266 auto servicePath = android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
267 singleThreaded ? "_single_threaded" : "",
268 noKernel ? "_no_kernel" : "");
269
270 base::unique_fd bootstrapClientFd, bootstrapServerFd;
271 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
272 // This is because we cannot pass ParcelFileDescriptor over a pipe.
273 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &bootstrapServerFd)) {
274 int savedErrno = errno;
275 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
Andrei Homescua858b0e2022-08-01 23:43:09 +0000276 }
277
Andrei Homescu96834632022-10-14 00:49:49 +0000278 auto ret = std::make_unique<LinuxProcessSession>(
279 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
280 auto writeFd = std::to_string(writeEnd.get());
281 auto readFd = std::to_string(readEnd.get());
282 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
283 NULL);
284 }));
285
286 BinderRpcTestServerConfig serverConfig;
287 serverConfig.numThreads = options.numThreads;
288 serverConfig.socketType = static_cast<int32_t>(socketType);
289 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
290 serverConfig.serverVersion = serverVersion;
291 serverConfig.vsockPort = allocateVsockPort();
292 serverConfig.addr = allocateSocketAddress();
293 serverConfig.unixBootstrapFd = bootstrapServerFd.get();
294 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
295 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
296 static_cast<int32_t>(mode));
297 }
298 writeToFd(ret->host.writeEnd(), serverConfig);
299
300 std::vector<sp<RpcSession>> sessions;
301 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
302 for (size_t i = 0; i < options.numSessions; i++) {
303 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
David Brazdil21c887c2022-09-23 12:25:18 +0100304 }
305
Andrei Homescu96834632022-10-14 00:49:49 +0000306 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
307 BinderRpcTestClientInfo clientInfo;
308 for (const auto& session : sessions) {
309 auto& parcelableCert = clientInfo.certs.emplace_back();
310 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
311 }
312 writeToFd(ret->host.writeEnd(), clientInfo);
313
314 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
315 if (socketType == SocketType::INET) {
316 CHECK_NE(0, serverInfo.port);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000317 }
318
Andrei Homescu96834632022-10-14 00:49:49 +0000319 if (rpcSecurity == RpcSecurity::TLS) {
320 const auto& serverCert = serverInfo.cert.data;
321 CHECK_EQ(OK,
322 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700323 }
324
Andrei Homescu96834632022-10-14 00:49:49 +0000325 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000326
Andrei Homescu96834632022-10-14 00:49:49 +0000327 for (const auto& session : sessions) {
328 CHECK(session->setProtocolVersion(clientVersion));
329 session->setMaxIncomingThreads(options.numIncomingConnections);
330 session->setMaxOutgoingThreads(options.numOutgoingConnections);
331 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000332
Andrei Homescu96834632022-10-14 00:49:49 +0000333 switch (socketType) {
334 case SocketType::PRECONNECTED:
335 status = session->setupPreconnectedClient({}, [=]() {
336 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
337 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000338 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000339 case SocketType::UNIX:
340 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
341 break;
342 case SocketType::UNIX_BOOTSTRAP:
343 status = session->setupUnixDomainSocketBootstrapClient(
344 base::unique_fd(dup(bootstrapClientFd.get())));
345 break;
346 case SocketType::VSOCK:
347 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
348 break;
349 case SocketType::INET:
350 status = session->setupInetClient("127.0.0.1", serverInfo.port);
351 break;
352 default:
353 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000354 }
Andrei Homescu96834632022-10-14 00:49:49 +0000355 if (options.allowConnectFailure && status != OK) {
356 ret->sessions.clear();
357 break;
358 }
359 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
360 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000361 }
Andrei Homescu96834632022-10-14 00:49:49 +0000362 return ret;
363}
Steven Morelandc1635952021-04-01 16:20:47 +0000364
Steven Morelandc1635952021-04-01 16:20:47 +0000365TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000366 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000367 ASSERT_NE(proc.rootBinder, nullptr);
368 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
369}
370
Steven Moreland4cf688f2021-03-31 01:48:58 +0000371TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000372 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000373 ASSERT_NE(proc.rootBinder, nullptr);
374 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
375}
376
Andrei Homescua858b0e2022-08-01 23:43:09 +0000377TEST_P(BinderRpc, MultipleSessions) {
378 if (serverSingleThreaded()) {
379 // Tests with multiple sessions require a multi-threaded service,
380 // but work fine on a single-threaded client
381 GTEST_SKIP() << "This test requires a multi-threaded service";
382 }
383
Steven Moreland4313d7e2021-07-15 23:41:22 +0000384 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Andrei Homescu96834632022-10-14 00:49:49 +0000385 for (auto session : proc.proc->sessions) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000386 ASSERT_NE(nullptr, session.root);
387 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000388 }
389}
390
Andrei Homescua858b0e2022-08-01 23:43:09 +0000391TEST_P(BinderRpc, SeparateRootObject) {
392 if (serverSingleThreaded()) {
393 GTEST_SKIP() << "This test requires a multi-threaded service";
394 }
395
Steven Moreland51c44a92021-10-14 16:50:35 -0700396 SocketType type = std::get<0>(GetParam());
David Brazdil21c887c2022-09-23 12:25:18 +0100397 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX ||
398 type == SocketType::UNIX_BOOTSTRAP) {
Steven Moreland51c44a92021-10-14 16:50:35 -0700399 // we can't get port numbers for unix sockets
400 return;
401 }
402
403 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
404
405 int port1 = 0;
406 EXPECT_OK(proc.rootIface->getClientPort(&port1));
407
Andrei Homescu96834632022-10-14 00:49:49 +0000408 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Moreland51c44a92021-10-14 16:50:35 -0700409 int port2;
410 EXPECT_OK(rootIface2->getClientPort(&port2));
411
412 // we should have a different IBinderRpcTest object created for each
413 // session, because we use setPerSessionRootObject
414 EXPECT_NE(port1, port2);
415}
416
Steven Morelandc1635952021-04-01 16:20:47 +0000417TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000418 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000419 Parcel data;
420 Parcel reply;
421 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
422}
423
Steven Moreland67753c32021-04-02 18:45:19 +0000424TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700425 auto proc1 = createRpcTestSocketServerProcess({});
426 auto proc2 = createRpcTestSocketServerProcess({});
427
428 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000429
430 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700431 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000432 p1.writeInt32(3);
433
Frederick Maylea4ed5672022-06-17 22:03:38 +0000434 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700435 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
436
Steven Moreland67753c32021-04-02 18:45:19 +0000437 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700438 p2.markForBinder(proc2.rootBinder);
439 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000440
441 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
442 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
443}
444
Steven Morelandc1635952021-04-01 16:20:47 +0000445TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000446 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000447 Parcel data;
448 data.markForBinder(proc.rootBinder);
449 Parcel reply;
450 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
451}
452
Steven Morelandc1635952021-04-01 16:20:47 +0000453TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000454 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000455 EXPECT_OK(proc.rootIface->sendString("asdf"));
456}
457
Steven Morelandc1635952021-04-01 16:20:47 +0000458TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000459 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000460 std::string doubled;
461 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
462 EXPECT_EQ("cool cool ", doubled);
463}
464
Steven Morelandc1635952021-04-01 16:20:47 +0000465TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000466 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000467 std::string single = std::string(1024, 'a');
468 std::string doubled;
469 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
470 EXPECT_EQ(single + single, doubled);
471}
472
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000473TEST_P(BinderRpc, InvalidNullBinderReturn) {
474 auto proc = createRpcTestSocketServerProcess({});
475
476 sp<IBinder> outBinder;
477 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
478}
479
Steven Morelandc1635952021-04-01 16:20:47 +0000480TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000481 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000482
483 int32_t pingResult;
484 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
485 EXPECT_EQ(OK, pingResult);
486
487 EXPECT_EQ(0, MyBinderRpcSession::gNum);
488}
489
Steven Morelandc1635952021-04-01 16:20:47 +0000490TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000491 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000492
493 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
494 sp<IBinder> outBinder;
495 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
496 EXPECT_EQ(inBinder, outBinder);
497
498 wp<IBinder> weak = inBinder;
499 inBinder = nullptr;
500 outBinder = nullptr;
501
502 // Force reading a reply, to process any pending dec refs from the other
503 // process (the other process will process dec refs there before processing
504 // the ping here).
505 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
506
507 EXPECT_EQ(nullptr, weak.promote());
508
509 EXPECT_EQ(0, MyBinderRpcSession::gNum);
510}
511
Steven Morelandc1635952021-04-01 16:20:47 +0000512TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000513 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000514
515 sp<IBinderRpcSession> session;
516 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
517
518 sp<IBinder> inBinder = IInterface::asBinder(session);
519 sp<IBinder> outBinder;
520 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
521 EXPECT_EQ(inBinder, outBinder);
522
523 wp<IBinder> weak = inBinder;
524 session = nullptr;
525 inBinder = nullptr;
526 outBinder = nullptr;
527
528 // Force reading a reply, to process any pending dec refs from the other
529 // process (the other process will process dec refs there before processing
530 // the ping here).
531 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
532
533 EXPECT_EQ(nullptr, weak.promote());
534}
535
Steven Morelandc1635952021-04-01 16:20:47 +0000536TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000537 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000538
539 sp<IBinder> outBinder;
540 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
541 EXPECT_EQ(nullptr, outBinder);
542}
543
Steven Morelandc1635952021-04-01 16:20:47 +0000544TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000545 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000546
547 IBinder* ptr = nullptr;
548 {
549 sp<IBinder> binder = new BBinder();
550 ptr = binder.get();
551 EXPECT_OK(proc.rootIface->holdBinder(binder));
552 }
553
554 sp<IBinder> held;
555 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
556
557 EXPECT_EQ(held.get(), ptr);
558
559 // stop holding binder, because we test to make sure references are cleaned
560 // up
561 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
562 // and flush ref counts
563 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
564}
565
566// START TESTS FOR LIMITATIONS OF SOCKET BINDER
567// These are behavioral differences form regular binder, where certain usecases
568// aren't supported.
569
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000570TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000571 auto proc1 = createRpcTestSocketServerProcess({});
572 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000573
574 sp<IBinder> outBinder;
575 EXPECT_EQ(INVALID_OPERATION,
576 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
577}
578
Andrei Homescua858b0e2022-08-01 23:43:09 +0000579TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
580 if (serverSingleThreaded()) {
581 GTEST_SKIP() << "This test requires a multi-threaded service";
582 }
583
Steven Moreland4313d7e2021-07-15 23:41:22 +0000584 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000585
586 sp<IBinder> outBinder;
587 EXPECT_EQ(INVALID_OPERATION,
Andrei Homescu96834632022-10-14 00:49:49 +0000588 proc.rootIface->repeatBinder(proc.proc->sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000589 .transactionError());
590}
591
Steven Morelandc1635952021-04-01 16:20:47 +0000592TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000593 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000594 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
595 "at build time.";
596 }
597
Steven Moreland4313d7e2021-07-15 23:41:22 +0000598 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000599
600 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
601 sp<IBinder> outBinder;
602 EXPECT_EQ(INVALID_OPERATION,
603 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
604}
605
Steven Morelandc1635952021-04-01 16:20:47 +0000606TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000607 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000608 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
609 "at build time.";
610 }
611
Steven Moreland4313d7e2021-07-15 23:41:22 +0000612 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000613
614 // for historical reasons, IServiceManager interface only returns the
615 // exception code
616 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
617 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
618}
619
620// END TESTS FOR LIMITATIONS OF SOCKET BINDER
621
Steven Morelandc1635952021-04-01 16:20:47 +0000622TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000623 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000624
625 sp<IBinder> outBinder;
626 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
627 EXPECT_EQ(proc.rootBinder, outBinder);
628}
629
Steven Morelandc1635952021-04-01 16:20:47 +0000630TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000631 auto proc = createRpcTestSocketServerProcess({
632 // Enable FD support because it uses more stack space and so represents
633 // something closer to a worst case scenario.
634 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
635 .serverSupportedFileDescriptorTransportModes =
636 {RpcSession::FileDescriptorTransportMode::UNIX},
637 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000638
639 auto nastyNester = sp<MyBinderRpcTest>::make();
640 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
641
642 wp<IBinder> weak = nastyNester;
643 nastyNester = nullptr;
644 EXPECT_EQ(nullptr, weak.promote());
645}
646
Steven Morelandc1635952021-04-01 16:20:47 +0000647TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000648 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000649
650 sp<IBinder> a;
651 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
652
653 sp<IBinder> b;
654 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
655
656 EXPECT_EQ(a, b);
657}
658
Steven Morelandc1635952021-04-01 16:20:47 +0000659TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000660 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000661
662 sp<IBinder> a;
663 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
664 wp<IBinder> weak = a;
665 a = nullptr;
666
667 sp<IBinder> b;
668 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
669
670 // this is the wrong behavior, since BpBinder
671 // doesn't implement onIncStrongAttempted
672 // but make sure there is no crash
673 EXPECT_EQ(nullptr, weak.promote());
674
675 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
676
677 // In order to fix this:
678 // - need to have incStrongAttempted reflected across IPC boundary (wait for
679 // response to promote - round trip...)
680 // - sendOnLastWeakRef, to delete entries out of RpcState table
681 EXPECT_EQ(b, weak.promote());
682}
683
684#define expectSessions(expected, iface) \
685 do { \
686 int session; \
687 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
688 EXPECT_EQ(expected, session); \
689 } while (false)
690
Steven Morelandc1635952021-04-01 16:20:47 +0000691TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000692 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000693
694 sp<IBinderRpcSession> session;
695 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
696 std::string out;
697 EXPECT_OK(session->getName(&out));
698 EXPECT_EQ("aoeu", out);
699
700 expectSessions(1, proc.rootIface);
701 session = nullptr;
702 expectSessions(0, proc.rootIface);
703}
704
Steven Morelandc1635952021-04-01 16:20:47 +0000705TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000706 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000707
708 std::vector<sp<IBinderRpcSession>> sessions;
709
710 for (size_t i = 0; i < 15; i++) {
711 expectSessions(i, proc.rootIface);
712 sp<IBinderRpcSession> session;
713 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
714 sessions.push_back(session);
715 }
716 expectSessions(sessions.size(), proc.rootIface);
717 for (size_t i = 0; i < sessions.size(); i++) {
718 std::string out;
719 EXPECT_OK(sessions.at(i)->getName(&out));
720 EXPECT_EQ(std::to_string(i), out);
721 }
722 expectSessions(sessions.size(), proc.rootIface);
723
724 while (!sessions.empty()) {
725 sessions.pop_back();
726 expectSessions(sessions.size(), proc.rootIface);
727 }
728 expectSessions(0, proc.rootIface);
729}
730
731size_t epochMillis() {
732 using std::chrono::duration_cast;
733 using std::chrono::milliseconds;
734 using std::chrono::seconds;
735 using std::chrono::system_clock;
736 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
737}
738
Andrei Homescua858b0e2022-08-01 23:43:09 +0000739TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
740 if (clientOrServerSingleThreaded()) {
741 GTEST_SKIP() << "This test requires multiple threads";
742 }
743
Steven Moreland5553ac42020-11-11 02:14:45 +0000744 constexpr size_t kNumThreads = 10;
745
Steven Moreland4313d7e2021-07-15 23:41:22 +0000746 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000747
748 EXPECT_OK(proc.rootIface->lock());
749
750 // block all but one thread taking locks
751 std::vector<std::thread> ts;
752 for (size_t i = 0; i < kNumThreads - 1; i++) {
753 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
754 }
755
Steven Morelanddd231e22022-09-08 19:47:49 +0000756 usleep(10000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000757
758 // other calls still work
759 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
760
Steven Morelanddd231e22022-09-08 19:47:49 +0000761 constexpr size_t blockTimeMs = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000762 size_t epochMsBefore = epochMillis();
763 // after this, we should never see a response within this time
764 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
765
766 // this call should be blocked for blockTimeMs
767 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
768
769 size_t epochMsAfter = epochMillis();
770 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
771
772 for (auto& t : ts) t.join();
773}
774
Andrei Homescu96834632022-10-14 00:49:49 +0000775static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
776 size_t sleepMs = 500) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000777 size_t epochMsBefore = epochMillis();
778
779 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700780 for (size_t i = 0; i < numCalls; i++) {
781 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000782 }
783
784 for (auto& t : ts) t.join();
785
786 size_t epochMsAfter = epochMillis();
787
Yifan Hong1f44f982021-10-08 17:16:47 -0700788 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000789
790 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700791 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
792}
793
Andrei Homescua858b0e2022-08-01 23:43:09 +0000794TEST_P(BinderRpc, ThreadPoolOverSaturated) {
795 if (clientOrServerSingleThreaded()) {
796 GTEST_SKIP() << "This test requires multiple threads";
797 }
798
Yifan Hong1f44f982021-10-08 17:16:47 -0700799 constexpr size_t kNumThreads = 10;
800 constexpr size_t kNumCalls = kNumThreads + 3;
801 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
802 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
803}
804
Andrei Homescua858b0e2022-08-01 23:43:09 +0000805TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
806 if (clientOrServerSingleThreaded()) {
807 GTEST_SKIP() << "This test requires multiple threads";
808 }
809
Yifan Hong1f44f982021-10-08 17:16:47 -0700810 constexpr size_t kNumThreads = 20;
811 constexpr size_t kNumOutgoingConnections = 10;
812 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
813 auto proc = createRpcTestSocketServerProcess(
814 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
815 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000816}
817
Andrei Homescua858b0e2022-08-01 23:43:09 +0000818TEST_P(BinderRpc, ThreadingStressTest) {
819 if (clientOrServerSingleThreaded()) {
820 GTEST_SKIP() << "This test requires multiple threads";
821 }
822
Steven Moreland5553ac42020-11-11 02:14:45 +0000823 constexpr size_t kNumClientThreads = 10;
824 constexpr size_t kNumServerThreads = 10;
825 constexpr size_t kNumCalls = 100;
826
Steven Moreland4313d7e2021-07-15 23:41:22 +0000827 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000828
829 std::vector<std::thread> threads;
830 for (size_t i = 0; i < kNumClientThreads; i++) {
831 threads.push_back(std::thread([&] {
832 for (size_t j = 0; j < kNumCalls; j++) {
833 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000834 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000835 EXPECT_EQ(proc.rootBinder, out);
836 }
837 }));
838 }
839
840 for (auto& t : threads) t.join();
841}
842
Steven Moreland925ba0a2021-09-17 18:06:32 -0700843static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
844 std::vector<std::thread> threads;
845 for (size_t i = 0; i < threadCount; i++) {
846 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
847 }
848 for (auto& t : threads) t.join();
849}
850
Andrei Homescua858b0e2022-08-01 23:43:09 +0000851TEST_P(BinderRpc, OnewayStressTest) {
852 if (clientOrServerSingleThreaded()) {
853 GTEST_SKIP() << "This test requires multiple threads";
854 }
855
Steven Morelandc6046982021-04-20 00:49:42 +0000856 constexpr size_t kNumClientThreads = 10;
857 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700858 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000859
Steven Moreland4313d7e2021-07-15 23:41:22 +0000860 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000861
862 std::vector<std::thread> threads;
863 for (size_t i = 0; i < kNumClientThreads; i++) {
864 threads.push_back(std::thread([&] {
865 for (size_t j = 0; j < kNumCalls; j++) {
866 EXPECT_OK(proc.rootIface->sendString("a"));
867 }
Steven Morelandc6046982021-04-20 00:49:42 +0000868 }));
869 }
870
871 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700872
873 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000874}
875
Steven Morelandc1635952021-04-01 16:20:47 +0000876TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000877 constexpr size_t kReallyLongTimeMs = 100;
878 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
879
Steven Moreland4313d7e2021-07-15 23:41:22 +0000880 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000881
882 size_t epochMsBefore = epochMillis();
883
884 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
885
886 size_t epochMsAfter = epochMillis();
887 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
888}
889
Frederick Mayleb0221d12022-10-03 23:10:53 +0000890TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
891 if (!supportsFdTransport()) {
892 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
893 }
894 if (clientOrServerSingleThreaded()) {
895 GTEST_SKIP() << "This test requires multiple threads";
896 }
897
898 // This test forces a oneway transaction to be queued by issuing two
899 // `blockingSendFdOneway` calls, then drains the queue by issuing two
900 // `blockingRecvFd` calls.
901 //
902 // For more details about the queuing semantics see
903 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
904
905 auto proc = createRpcTestSocketServerProcess({
906 .numThreads = 3,
907 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
908 .serverSupportedFileDescriptorTransportModes =
909 {RpcSession::FileDescriptorTransportMode::UNIX},
910 });
911
912 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
913 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
914 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
915 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
916
917 android::os::ParcelFileDescriptor fdA;
918 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
919 std::string result;
920 CHECK(android::base::ReadFdToString(fdA.get(), &result));
921 EXPECT_EQ(result, "a");
922
923 android::os::ParcelFileDescriptor fdB;
924 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
925 CHECK(android::base::ReadFdToString(fdB.get(), &result));
926 EXPECT_EQ(result, "b");
927}
928
Andrei Homescua858b0e2022-08-01 23:43:09 +0000929TEST_P(BinderRpc, OnewayCallQueueing) {
930 if (clientOrServerSingleThreaded()) {
931 GTEST_SKIP() << "This test requires multiple threads";
932 }
933
Steven Moreland5553ac42020-11-11 02:14:45 +0000934 constexpr size_t kNumSleeps = 10;
935 constexpr size_t kNumExtraServerThreads = 4;
936 constexpr size_t kSleepMs = 50;
937
938 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000939 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000940
941 EXPECT_OK(proc.rootIface->lock());
942
Steven Moreland1c678802021-09-17 16:48:47 -0700943 size_t epochMsBefore = epochMillis();
944
945 // all these *Async commands should be queued on the server sequentially,
946 // even though there are multiple threads.
947 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000948 proc.rootIface->sleepMsAsync(kSleepMs);
949 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000950 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
951
Steven Moreland1c678802021-09-17 16:48:47 -0700952 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000953 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700954
Steven Moreland5553ac42020-11-11 02:14:45 +0000955 size_t epochMsAfter = epochMillis();
956
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000957 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000958
Steven Moreland925ba0a2021-09-17 18:06:32 -0700959 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000960}
961
Andrei Homescua858b0e2022-08-01 23:43:09 +0000962TEST_P(BinderRpc, OnewayCallExhaustion) {
963 if (clientOrServerSingleThreaded()) {
964 GTEST_SKIP() << "This test requires multiple threads";
965 }
966
Steven Morelandd45be622021-06-04 02:19:37 +0000967 constexpr size_t kNumClients = 2;
968 constexpr size_t kTooLongMs = 1000;
969
Steven Moreland4313d7e2021-07-15 23:41:22 +0000970 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000971
972 // Build up oneway calls on the second session to make sure it terminates
973 // and shuts down. The first session should be unaffected (proc destructor
974 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000975 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000976
977 std::vector<std::thread> threads;
978 for (size_t i = 0; i < kNumClients; i++) {
979 // one of these threads will get stuck queueing a transaction once the
980 // socket fills up, the other will be able to fill up transactions on
981 // this object
982 threads.push_back(std::thread([&] {
983 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
984 }
985 }));
986 }
987 for (auto& t : threads) t.join();
988
989 Status status = iface->sleepMsAsync(kTooLongMs);
990 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
991
Steven Moreland798e0d12021-07-14 23:19:25 +0000992 // now that it has died, wait for the remote session to shutdown
993 std::vector<int32_t> remoteCounts;
994 do {
995 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
996 } while (remoteCounts.size() == kNumClients);
997
Steven Morelandd45be622021-06-04 02:19:37 +0000998 // the second session should be shutdown in the other process by the time we
999 // are able to join above (it'll only be hung up once it finishes processing
1000 // any pending commands). We need to erase this session from the record
1001 // here, so that the destructor for our session won't check that this
1002 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +00001003 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +00001004}
1005
Steven Moreland659416d2021-05-11 00:47:50 +00001006TEST_P(BinderRpc, Callbacks) {
1007 const static std::string kTestString = "good afternoon!";
1008
Steven Morelandc7d40132021-06-10 03:42:11 +00001009 for (bool callIsOneway : {true, false}) {
1010 for (bool callbackIsOneway : {true, false}) {
1011 for (bool delayed : {true, false}) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001012 if (clientOrServerSingleThreaded() &&
1013 (callIsOneway || callbackIsOneway || delayed)) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001014 // we have no incoming connections to receive the callback
1015 continue;
1016 }
1017
Andrei Homescua858b0e2022-08-01 23:43:09 +00001018 size_t numIncomingConnections = clientOrServerSingleThreaded() ? 0 : 1;
Steven Moreland4313d7e2021-07-15 23:41:22 +00001019 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +00001020 {.numThreads = 1,
1021 .numSessions = 1,
Andrei Homescu2a298012022-06-15 01:08:54 +00001022 .numIncomingConnections = numIncomingConnections});
Steven Morelandc7d40132021-06-10 03:42:11 +00001023 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001024
Steven Morelandc7d40132021-06-10 03:42:11 +00001025 if (callIsOneway) {
1026 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1027 kTestString));
1028 } else {
1029 EXPECT_OK(
1030 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1031 }
Steven Moreland659416d2021-05-11 00:47:50 +00001032
Steven Moreland03ecce62022-05-13 23:22:05 +00001033 // if both transactions are synchronous and the response is sent back on the
1034 // same thread, everything should have happened in a nested call. Otherwise,
1035 // the callback will be processed on another thread.
1036 if (callIsOneway || callbackIsOneway || delayed) {
1037 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001038 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001039 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1040 }
Steven Moreland659416d2021-05-11 00:47:50 +00001041
Steven Morelandc7d40132021-06-10 03:42:11 +00001042 EXPECT_EQ(cb->mValues.size(), 1)
1043 << "callIsOneway: " << callIsOneway
1044 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1045 if (cb->mValues.empty()) continue;
1046 EXPECT_EQ(cb->mValues.at(0), kTestString)
1047 << "callIsOneway: " << callIsOneway
1048 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001049
Steven Morelandc7d40132021-06-10 03:42:11 +00001050 // since we are severing the connection, we need to go ahead and
1051 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001052 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1053 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1054 }
Steven Moreland659416d2021-05-11 00:47:50 +00001055
Steven Moreland1b304292021-07-15 22:59:34 +00001056 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001057 // need to manually shut it down
Andrei Homescu96834632022-10-14 00:49:49 +00001058 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Steven Morelandc7d40132021-06-10 03:42:11 +00001059 proc.expectAlreadyShutdown = true;
1060 }
Steven Moreland659416d2021-05-11 00:47:50 +00001061 }
1062 }
1063}
1064
Devin Moore66d5b7a2022-07-07 21:42:10 +00001065TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001066 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001067 GTEST_SKIP() << "This test requires multiple threads";
1068 }
1069 class MyDeathRec : public IBinder::DeathRecipient {
1070 public:
1071 void binderDied(const wp<IBinder>& /* who */) override {
1072 dead = true;
1073 mCv.notify_one();
1074 }
1075 std::mutex mMtx;
1076 std::condition_variable mCv;
1077 bool dead = false;
1078 };
1079
1080 // Death recipient needs to have an incoming connection to be called
1081 auto proc = createRpcTestSocketServerProcess(
1082 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1083
1084 auto dr = sp<MyDeathRec>::make();
1085 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1086
1087 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1088 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1089 }
1090
1091 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +00001092 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001093
1094 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +00001095 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001096 proc.expectAlreadyShutdown = true;
1097}
1098
1099TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001100 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001101 GTEST_SKIP() << "This test requires multiple threads";
1102 }
1103 class MyDeathRec : public IBinder::DeathRecipient {
1104 public:
1105 void binderDied(const wp<IBinder>& /* who */) override {
1106 dead = true;
1107 mCv.notify_one();
1108 }
1109 std::mutex mMtx;
1110 std::condition_variable mCv;
1111 bool dead = false;
1112 };
1113
1114 // Death recipient needs to have an incoming connection to be called
1115 auto proc = createRpcTestSocketServerProcess(
1116 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1117
1118 auto dr = sp<MyDeathRec>::make();
1119 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1120
1121 // Explicitly calling shutDownAndWait will cause the death recipients
1122 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +00001123 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001124
1125 std::unique_lock<std::mutex> lock(dr->mMtx);
1126 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001127 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001128 }
1129 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1130
Andrei Homescu96834632022-10-14 00:49:49 +00001131 proc.proc->terminate();
1132 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001133 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1134 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1135 });
1136 proc.expectAlreadyShutdown = true;
1137}
1138
1139TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1140 class MyDeathRec : public IBinder::DeathRecipient {
1141 public:
1142 void binderDied(const wp<IBinder>& /* who */) override {}
1143 };
1144
1145 auto proc = createRpcTestSocketServerProcess(
1146 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1147
1148 auto dr = sp<MyDeathRec>::make();
1149 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1150 "Cannot register a DeathRecipient without any incoming connections.");
1151}
1152
1153TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001154 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001155 GTEST_SKIP() << "This test requires multiple threads";
1156 }
1157 class MyDeathRec : public IBinder::DeathRecipient {
1158 public:
1159 void binderDied(const wp<IBinder>& /* who */) override {
1160 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1161 }
1162 };
1163
1164 // Death recipient needs to have an incoming connection to be called
1165 auto proc = createRpcTestSocketServerProcess(
1166 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1167
1168 auto dr = sp<MyDeathRec>::make();
1169 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1170 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1171
1172 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1173 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1174 }
1175
1176 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +00001177 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001178 proc.expectAlreadyShutdown = true;
1179}
1180
Steven Moreland195edb82021-06-08 02:44:39 +00001181TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001182 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001183 auto cb = sp<MyBinderRpcCallback>::make();
1184
1185 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1186 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1187}
1188
Steven Morelandc1635952021-04-01 16:20:47 +00001189TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001190 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001191 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001192
1193 // make sure there is some state during crash
1194 // 1. we hold their binder
1195 sp<IBinderRpcSession> session;
1196 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1197 // 2. they hold our binder
1198 sp<IBinder> binder = new BBinder();
1199 EXPECT_OK(proc.rootIface->holdBinder(binder));
1200
1201 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1202 << "Do death cleanup: " << doDeathCleanup;
1203
Andrei Homescu96834632022-10-14 00:49:49 +00001204 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +00001205 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1206 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1207 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001208 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001209 }
1210}
1211
Steven Morelandd7302072021-05-15 01:32:04 +00001212TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001213 // This test only works if the current process shared the internal state of
1214 // ProcessState with the service across the call to fork(). Both the static
1215 // libraries and libbinder.so have their own separate copies of all the
1216 // globals, so the test only works when the test client and service both use
1217 // libbinder.so (when using static libraries, even a client and service
1218 // using the same kind of static library should have separate copies of the
1219 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +00001220 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001221 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1222 "at build time.";
1223 }
1224
Steven Moreland4313d7e2021-07-15 23:41:22 +00001225 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001226
Andrei Homescu2a298012022-06-15 01:08:54 +00001227 // we can't allocate IPCThreadState so actually the first time should
1228 // succeed :(
1229 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001230
1231 // second time! we catch the error :)
1232 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1233
Andrei Homescu96834632022-10-14 00:49:49 +00001234 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +00001235 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1236 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1237 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001238 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001239}
1240
Frederick Mayle69a0c992022-05-26 20:38:39 +00001241TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1242 auto proc = createRpcTestSocketServerProcess({
1243 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1244 .serverSupportedFileDescriptorTransportModes =
1245 {RpcSession::FileDescriptorTransportMode::UNIX},
1246 .allowConnectFailure = true,
1247 });
Andrei Homescu96834632022-10-14 00:49:49 +00001248 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
1249 proc.proc->terminate();
1250 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +00001251 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1252 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1253 });
1254 proc.expectAlreadyShutdown = true;
1255}
1256
1257TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1258 auto proc = createRpcTestSocketServerProcess({
1259 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1260 .serverSupportedFileDescriptorTransportModes =
1261 {RpcSession::FileDescriptorTransportMode::NONE},
1262 .allowConnectFailure = true,
1263 });
Andrei Homescu96834632022-10-14 00:49:49 +00001264 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
1265 proc.proc->terminate();
1266 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +00001267 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1268 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1269 });
1270 proc.expectAlreadyShutdown = true;
1271}
1272
1273TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1274 auto proc = createRpcTestSocketServerProcess({
1275 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1276 .serverSupportedFileDescriptorTransportModes =
1277 {RpcSession::FileDescriptorTransportMode::NONE,
1278 RpcSession::FileDescriptorTransportMode::UNIX},
1279 });
1280
1281 android::os::ParcelFileDescriptor out;
1282 auto status = proc.rootIface->echoAsFile("hello", &out);
1283 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1284}
1285
1286TEST_P(BinderRpc, ReceiveFile) {
1287 auto proc = createRpcTestSocketServerProcess({
1288 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1289 .serverSupportedFileDescriptorTransportModes =
1290 {RpcSession::FileDescriptorTransportMode::UNIX},
1291 });
1292
1293 android::os::ParcelFileDescriptor out;
1294 auto status = proc.rootIface->echoAsFile("hello", &out);
1295 if (!supportsFdTransport()) {
1296 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1297 return;
1298 }
1299 ASSERT_TRUE(status.isOk()) << status;
1300
1301 std::string result;
1302 CHECK(android::base::ReadFdToString(out.get(), &result));
1303 EXPECT_EQ(result, "hello");
1304}
1305
1306TEST_P(BinderRpc, SendFiles) {
1307 auto proc = createRpcTestSocketServerProcess({
1308 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1309 .serverSupportedFileDescriptorTransportModes =
1310 {RpcSession::FileDescriptorTransportMode::UNIX},
1311 });
1312
1313 std::vector<android::os::ParcelFileDescriptor> files;
1314 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1315 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1316 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1317 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1318
1319 android::os::ParcelFileDescriptor out;
1320 auto status = proc.rootIface->concatFiles(files, &out);
1321 if (!supportsFdTransport()) {
1322 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1323 return;
1324 }
1325 ASSERT_TRUE(status.isOk()) << status;
1326
1327 std::string result;
1328 CHECK(android::base::ReadFdToString(out.get(), &result));
1329 EXPECT_EQ(result, "123abcd");
1330}
1331
1332TEST_P(BinderRpc, SendMaxFiles) {
1333 if (!supportsFdTransport()) {
1334 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1335 }
1336
1337 auto proc = createRpcTestSocketServerProcess({
1338 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1339 .serverSupportedFileDescriptorTransportModes =
1340 {RpcSession::FileDescriptorTransportMode::UNIX},
1341 });
1342
1343 std::vector<android::os::ParcelFileDescriptor> files;
1344 for (int i = 0; i < 253; i++) {
1345 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1346 }
1347
1348 android::os::ParcelFileDescriptor out;
1349 auto status = proc.rootIface->concatFiles(files, &out);
1350 ASSERT_TRUE(status.isOk()) << status;
1351
1352 std::string result;
1353 CHECK(android::base::ReadFdToString(out.get(), &result));
1354 EXPECT_EQ(result, std::string(253, 'a'));
1355}
1356
1357TEST_P(BinderRpc, SendTooManyFiles) {
1358 if (!supportsFdTransport()) {
1359 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1360 }
1361
1362 auto proc = createRpcTestSocketServerProcess({
1363 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1364 .serverSupportedFileDescriptorTransportModes =
1365 {RpcSession::FileDescriptorTransportMode::UNIX},
1366 });
1367
1368 std::vector<android::os::ParcelFileDescriptor> files;
1369 for (int i = 0; i < 254; i++) {
1370 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1371 }
1372
1373 android::os::ParcelFileDescriptor out;
1374 auto status = proc.rootIface->concatFiles(files, &out);
1375 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1376}
1377
Steven Moreland37aff182021-03-26 02:04:16 +00001378TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001379 if constexpr (!kEnableSharedLibs) {
1380 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1381 }
1382
Steven Moreland4313d7e2021-07-15 23:41:22 +00001383 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001384
1385 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1386 ASSERT_NE(binder, nullptr);
1387
1388 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1389}
1390
1391TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001392 if constexpr (!kEnableSharedLibs) {
1393 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1394 }
1395
Steven Moreland4313d7e2021-07-15 23:41:22 +00001396 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001397
1398 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1399 ASSERT_NE(binder, nullptr);
1400
1401 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1402 ASSERT_NE(ndkBinder, nullptr);
1403
1404 std::string out;
1405 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1406 ASSERT_TRUE(status.isOk()) << status.getDescription();
1407 ASSERT_EQ("aoeuaoeu", out);
1408}
1409
Steven Moreland5553ac42020-11-11 02:14:45 +00001410ssize_t countFds() {
1411 DIR* dir = opendir("/proc/self/fd/");
1412 if (dir == nullptr) return -1;
1413 ssize_t ret = 0;
1414 dirent* ent;
1415 while ((ent = readdir(dir)) != nullptr) ret++;
1416 closedir(dir);
1417 return ret;
1418}
1419
Andrei Homescua858b0e2022-08-01 23:43:09 +00001420TEST_P(BinderRpc, Fds) {
1421 if (serverSingleThreaded()) {
1422 GTEST_SKIP() << "This test requires multiple threads";
1423 }
1424
Steven Moreland5553ac42020-11-11 02:14:45 +00001425 ssize_t beforeFds = countFds();
1426 ASSERT_GE(beforeFds, 0);
1427 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001428 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001429 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1430 }
1431 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1432}
1433
Devin Moore800b2252021-10-15 16:22:57 +00001434TEST_P(BinderRpc, AidlDelegatorTest) {
1435 auto proc = createRpcTestSocketServerProcess({});
1436 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1437 ASSERT_NE(nullptr, myDelegator);
1438
1439 std::string doubled;
1440 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1441 EXPECT_EQ("cool cool ", doubled);
1442}
1443
Steven Morelandda573042021-06-12 01:13:45 +00001444static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001445 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001446 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001447
Andrei Homescu992a4052022-06-28 21:26:18 +00001448 android::base::unique_fd serverFd(
1449 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1450 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1451
1452 sockaddr_vm serverAddr{
1453 .svm_family = AF_VSOCK,
1454 .svm_port = vsockPort,
1455 .svm_cid = VMADDR_CID_ANY,
1456 };
1457 int ret = TEMP_FAILURE_RETRY(
1458 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1459 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1460 strerror(errno));
1461
1462 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1463 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1464 strerror(errno));
1465
1466 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1467 // to see if the kernel supports it. It's safe to use a blocking
1468 // connect because vsock sockets have a 2 second connection timeout,
1469 // and they return ETIMEDOUT after that.
1470 android::base::unique_fd connectFd(
1471 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1472 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1473 strerror(errno));
1474
1475 bool success = false;
1476 sockaddr_vm connectAddr{
1477 .svm_family = AF_VSOCK,
1478 .svm_port = vsockPort,
1479 .svm_cid = VMADDR_CID_LOCAL,
1480 };
1481 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1482 sizeof(connectAddr)));
1483 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1484 android::base::unique_fd acceptFd;
1485 while (true) {
1486 pollfd pfd[]{
1487 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1488 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1489 };
1490 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1491 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1492
1493 if (pfd[0].revents & POLLIN) {
1494 sockaddr_vm acceptAddr;
1495 socklen_t acceptAddrLen = sizeof(acceptAddr);
1496 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1497 reinterpret_cast<sockaddr*>(&acceptAddr),
1498 &acceptAddrLen, SOCK_CLOEXEC));
1499 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1500 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1501 "Truncated address");
1502
1503 // Store the fd in acceptFd so we keep the connection alive
1504 // while polling connectFd
1505 acceptFd.reset(ret);
1506 }
1507
1508 if (pfd[1].revents & POLLOUT) {
1509 // Connect either succeeded or timed out
1510 int connectErrno;
1511 socklen_t connectErrnoLen = sizeof(connectErrno);
1512 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1513 &connectErrnoLen);
1514 LOG_ALWAYS_FATAL_IF(ret == -1,
1515 "Could not getsockopt() after connect() "
1516 "on non-blocking socket: %s.",
1517 strerror(errno));
1518
1519 // We're done, this is all we wanted
1520 success = connectErrno == 0;
1521 break;
1522 }
1523 }
1524 } else {
1525 success = ret == 0;
1526 }
1527
1528 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1529
1530 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001531}
1532
Yifan Hong1deca4b2021-09-10 16:16:44 -07001533static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
David Brazdil21c887c2022-09-23 12:25:18 +01001534 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001535
1536 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001537
1538 static bool hasVsockLoopback = testSupportVsockLoopback();
1539
1540 if (hasVsockLoopback) {
1541 ret.push_back(SocketType::VSOCK);
1542 }
1543
1544 return ret;
1545}
1546
Frederick Mayledc07cf82022-05-26 20:30:12 +00001547static std::vector<uint32_t> testVersions() {
1548 std::vector<uint32_t> versions;
1549 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1550 versions.push_back(i);
1551 }
1552 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1553 return versions;
1554}
1555
Yifan Hong702115c2021-06-24 15:39:18 -07001556INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1557 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001558 ::testing::ValuesIn(RpcSecurityValues()),
1559 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001560 ::testing::ValuesIn(testVersions()),
1561 ::testing::Values(false, true),
1562 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001563 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001564
Yifan Hong702115c2021-06-24 15:39:18 -07001565class BinderRpcServerRootObject
1566 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001567
1568TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1569 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1570 auto setRootObject = [](bool isStrong) -> SetFn {
1571 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1572 };
1573
Yifan Hong702115c2021-06-24 15:39:18 -07001574 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1575 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001576 auto binder1 = sp<BBinder>::make();
1577 IBinder* binderRaw1 = binder1.get();
1578 setRootObject(isStrong1)(server.get(), binder1);
1579 EXPECT_EQ(binderRaw1, server->getRootObject());
1580 binder1.clear();
1581 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1582
1583 auto binder2 = sp<BBinder>::make();
1584 IBinder* binderRaw2 = binder2.get();
1585 setRootObject(isStrong2)(server.get(), binder2);
1586 EXPECT_EQ(binderRaw2, server->getRootObject());
1587 binder2.clear();
1588 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1589}
1590
1591INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001592 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1593 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001594
Yifan Hong1a235852021-05-13 16:07:47 -07001595class OneOffSignal {
1596public:
1597 // If notify() was previously called, or is called within |duration|, return true; else false.
1598 template <typename R, typename P>
1599 bool wait(std::chrono::duration<R, P> duration) {
1600 std::unique_lock<std::mutex> lock(mMutex);
1601 return mCv.wait_for(lock, duration, [this] { return mValue; });
1602 }
1603 void notify() {
1604 std::unique_lock<std::mutex> lock(mMutex);
1605 mValue = true;
1606 lock.unlock();
1607 mCv.notify_all();
1608 }
1609
1610private:
1611 std::mutex mMutex;
1612 std::condition_variable mCv;
1613 bool mValue = false;
1614};
1615
Yifan Hong194acf22021-06-29 18:44:56 -07001616TEST(BinderRpc, Java) {
1617#if !defined(__ANDROID__)
1618 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1619 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1620 "to binderHostDeviceTest. Hence, just disable this test on host.";
1621#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001622 if constexpr (!kEnableKernelIpc) {
1623 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1624 "at build time.";
1625 }
1626
Yifan Hong194acf22021-06-29 18:44:56 -07001627 sp<IServiceManager> sm = defaultServiceManager();
1628 ASSERT_NE(nullptr, sm);
1629 // Any Java service with non-empty getInterfaceDescriptor() would do.
1630 // Let's pick batteryproperties.
1631 auto binder = sm->checkService(String16("batteryproperties"));
1632 ASSERT_NE(nullptr, binder);
1633 auto descriptor = binder->getInterfaceDescriptor();
1634 ASSERT_GE(descriptor.size(), 0);
1635 ASSERT_EQ(OK, binder->pingBinder());
1636
1637 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001638 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001639 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001640 auto socket = rpcServer->releaseServer();
1641
1642 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001643 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1644
Yifan Honge3caaf22022-01-12 14:46:56 -08001645 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1646 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001647 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001648 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1649 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001650 << statusToString(setRpcClientDebugStatus);
1651 GTEST_SKIP();
1652 }
1653
1654 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001655
1656 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001657 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001658 auto rpcBinder = rpcSession->getRootObject();
1659 ASSERT_NE(nullptr, rpcBinder);
1660
1661 ASSERT_EQ(OK, rpcBinder->pingBinder());
1662
1663 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1664 << "getInterfaceDescriptor should not crash system_server";
1665 ASSERT_EQ(OK, rpcBinder->pingBinder());
1666}
1667
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001668class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1669public:
1670 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1671 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1672 std::to_string(std::get<1>(info.param));
1673 }
1674};
1675
1676TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1677 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1678 int sinkFd = sink.get();
1679 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1680 server->setProtocolVersion(std::get<1>(GetParam()));
1681 ASSERT_FALSE(server->hasServer());
1682 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1683 ASSERT_TRUE(server->hasServer());
1684 base::unique_fd retrieved = server->releaseServer();
1685 ASSERT_FALSE(server->hasServer());
1686 ASSERT_EQ(sinkFd, retrieved.get());
1687}
1688
1689TEST_P(BinderRpcServerOnly, Shutdown) {
1690 if constexpr (!kEnableRpcThreads) {
1691 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1692 }
1693
1694 auto addr = allocateSocketAddress();
1695 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1696 server->setProtocolVersion(std::get<1>(GetParam()));
1697 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1698 auto joinEnds = std::make_shared<OneOffSignal>();
1699
1700 // If things are broken and the thread never stops, don't block other tests. Because the thread
1701 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1702 // shared pointers are passed.
1703 std::thread([server, joinEnds] {
1704 server->join();
1705 joinEnds->notify();
1706 }).detach();
1707
1708 bool shutdown = false;
1709 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001710 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001711 if (server->shutdown()) shutdown = true;
1712 }
1713 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1714
1715 ASSERT_TRUE(joinEnds->wait(2s))
1716 << "After server->shutdown() returns true, join() did not stop after 2s";
1717}
1718
Frederick Mayledc07cf82022-05-26 20:30:12 +00001719INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1720 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1721 ::testing::ValuesIn(testVersions())),
1722 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001723
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001724class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001725public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001726 // Only parameterized only server version because `RpcSession` is bypassed
1727 // in the client half of the tests.
1728 using Param =
1729 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001730 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001731
1732 // A server that handles client socket connections.
1733 class Server {
1734 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001735 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1736
Yifan Hong1deca4b2021-09-10 16:16:44 -07001737 explicit Server() {}
1738 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001739 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001740 [[nodiscard]] AssertionResult setUp(
1741 const Param& param,
1742 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001743 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001744 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001745 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001746 switch (socketType) {
1747 case SocketType::PRECONNECTED: {
1748 return AssertionFailure() << "Not supported by this test";
1749 } break;
1750 case SocketType::UNIX: {
1751 auto addr = allocateSocketAddress();
1752 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1753 if (status != OK) {
1754 return AssertionFailure()
1755 << "setupUnixDomainServer: " << statusToString(status);
1756 }
1757 mConnectToServer = [addr] {
1758 return connectTo(UnixSocketAddress(addr.c_str()));
1759 };
1760 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001761 case SocketType::UNIX_BOOTSTRAP: {
1762 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1763 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1764 return AssertionFailure() << "Socketpair() failed";
1765 }
1766 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1767 std::move(bootstrapFdServer));
1768 if (status != OK) {
1769 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1770 << statusToString(status);
1771 }
1772 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1773 mAcceptConnection = &Server::recvmsgServerConnection;
1774 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1775 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001776 case SocketType::VSOCK: {
1777 auto port = allocateVsockPort();
1778 auto status = rpcServer->setupVsockServer(port);
1779 if (status != OK) {
1780 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1781 }
1782 mConnectToServer = [port] {
1783 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1784 };
1785 } break;
1786 case SocketType::INET: {
1787 unsigned int port;
1788 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1789 if (status != OK) {
1790 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1791 }
1792 mConnectToServer = [port] {
1793 const char* addr = kLocalInetAddress;
1794 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1795 if (aiStart == nullptr) return base::unique_fd{};
1796 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1797 auto fd = connectTo(
1798 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1799 if (fd.ok()) return fd;
1800 }
1801 ALOGE("None of the socket address resolved for %s:%u can be connected",
1802 addr, port);
1803 return base::unique_fd{};
1804 };
1805 }
1806 }
1807 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001808 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001809 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001810 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1811 mSetup = true;
1812 return AssertionSuccess();
1813 }
1814 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1815 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1816 return mCertVerifier;
1817 }
1818 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1819 void start() {
1820 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1821 mThread = std::make_unique<std::thread>(&Server::run, this);
1822 }
David Brazdil21c887c2022-09-23 12:25:18 +01001823
1824 base::unique_fd acceptServerConnection() {
1825 return base::unique_fd(TEMP_FAILURE_RETRY(
1826 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1827 }
1828
1829 base::unique_fd recvmsgServerConnection() {
1830 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1831 int buf;
1832 iovec iov{&buf, sizeof(buf)};
1833
1834 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1835 int savedErrno = errno;
1836 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1837 }
1838 if (fds.size() != 1) {
1839 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1840 }
1841 return std::move(std::get<base::unique_fd>(fds[0]));
1842 }
1843
Yifan Hong1deca4b2021-09-10 16:16:44 -07001844 void run() {
1845 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1846
1847 std::vector<std::thread> threads;
1848 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001849 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001850 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1851 }
1852
1853 for (auto& thread : threads) thread.join();
1854 }
1855 void handleOne(android::base::unique_fd acceptedFd) {
1856 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001857 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001858 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001859 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001860 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001861 }
Yifan Honge07d2732021-09-13 21:59:14 -07001862 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001863 shutdown();
1864 join();
1865 }
1866 void shutdown() { mFdTrigger->trigger(); }
1867
1868 void setPostConnect(
1869 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1870 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001871 }
1872
1873 private:
1874 std::unique_ptr<std::thread> mThread;
1875 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001876 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001877 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001878 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001879 std::unique_ptr<RpcTransportCtx> mCtx;
1880 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1881 std::make_shared<RpcCertificateVerifierSimple>();
1882 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001883 // The function invoked after connection and handshake. By default, it is
1884 // |defaultPostConnect| that sends |kMessage| to the client.
1885 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1886 Server::defaultPostConnect;
1887
1888 void join() {
1889 if (mThread != nullptr) {
1890 mThread->join();
1891 mThread = nullptr;
1892 }
1893 }
1894
1895 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1896 FdTrigger* fdTrigger) {
1897 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001898 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001899 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001900 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001901 if (status != OK) return AssertionFailure() << statusToString(status);
1902 return AssertionSuccess();
1903 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001904 };
1905
1906 class Client {
1907 public:
1908 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1909 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001910 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001911 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1912 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001913 mFdTrigger = FdTrigger::make();
1914 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1915 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1916 return AssertionSuccess();
1917 }
1918 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1919 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1920 return mCertVerifier;
1921 }
Yifan Hong67519322021-09-13 18:51:16 -07001922 // connect() and do handshake
1923 bool setUpTransport() {
1924 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001925 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001926 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1927 return mClientTransport != nullptr;
1928 }
1929 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1930 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1931 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001932 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001933 status_t readStatus =
1934 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001935 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001936 if (readStatus != OK) {
1937 return AssertionFailure() << statusToString(readStatus);
1938 }
1939 if (readMessage != expectedMessage) {
1940 return AssertionFailure()
1941 << "Expected " << expectedMessage << ", actual " << readMessage;
1942 }
1943 return AssertionSuccess();
1944 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001945 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001946 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001947 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1948 return;
1949 }
1950 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001951 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001952 }
1953
Pawan49d74cb2022-08-03 21:19:11 +00001954 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1955
Yifan Hong1deca4b2021-09-10 16:16:44 -07001956 private:
1957 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001958 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001959 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1960 std::unique_ptr<RpcTransportCtx> mCtx;
1961 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1962 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001963 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001964 };
1965
1966 // Make A trust B.
1967 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001968 static status_t trust(RpcSecurity rpcSecurity,
1969 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1970 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001971 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001972 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1973 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1974 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001975 }
1976
1977 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001978};
1979
1980class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1981public:
1982 using Server = RpcTransportTestUtils::Server;
1983 using Client = RpcTransportTestUtils::Client;
1984 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001985 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001986 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1987 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001988 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001989 return ret;
1990 }
1991 static std::vector<ParamType> getRpcTranportTestParams() {
1992 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001993 for (auto serverVersion : testVersions()) {
1994 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1995 for (auto rpcSecurity : RpcSecurityValues()) {
1996 switch (rpcSecurity) {
1997 case RpcSecurity::RAW: {
1998 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1999 } break;
2000 case RpcSecurity::TLS: {
2001 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
2002 serverVersion);
2003 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
2004 serverVersion);
2005 } break;
2006 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002007 }
2008 }
2009 }
2010 return ret;
2011 }
2012 template <typename A, typename B>
2013 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002014 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2015 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002016 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
2017 }
Andrei Homescu12106de2022-04-27 04:42:21 +00002018 void SetUp() override {
2019 if constexpr (!kEnableRpcThreads) {
2020 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2021 }
2022 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002023};
2024
2025TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002026 auto server = std::make_unique<Server>();
2027 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002028
2029 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002030 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002031
2032 ASSERT_EQ(OK, trust(&client, server));
2033 ASSERT_EQ(OK, trust(server, &client));
2034
2035 server->start();
2036 client.run();
2037}
2038
2039TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002040 auto server = std::make_unique<Server>();
2041 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002042
2043 std::vector<Client> clients;
2044 for (int i = 0; i < 2; i++) {
2045 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002046 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002047 ASSERT_EQ(OK, trust(&client, server));
2048 ASSERT_EQ(OK, trust(server, &client));
2049 }
2050
2051 server->start();
2052 for (auto& client : clients) client.run();
2053}
2054
2055TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002056 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2057 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002058
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002059 auto untrustedServer = std::make_unique<Server>();
2060 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002061
2062 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002063 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002064
2065 ASSERT_EQ(OK, trust(untrustedServer, &client));
2066
2067 untrustedServer->start();
2068
2069 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2070 // the client can't verify the server's identity.
2071 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2072 client.run(handshakeOk);
2073}
2074TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002075 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2076 (void)serverVersion;
2077
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002078 auto validServer = std::make_unique<Server>();
2079 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002080
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002081 auto maliciousServer = std::make_unique<Server>();
2082 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002083
2084 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002085 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002086
2087 ASSERT_EQ(OK, trust(&client, validServer));
2088 ASSERT_EQ(OK, trust(validServer, &client));
2089 ASSERT_EQ(OK, trust(maliciousServer, &client));
2090
2091 maliciousServer->start();
2092
2093 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2094 // the client can't verify the server's identity.
2095 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2096 client.run(handshakeOk);
2097}
2098
2099TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002100 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2101 (void)serverVersion;
2102
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002103 auto server = std::make_unique<Server>();
2104 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002105
2106 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002107 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002108
2109 ASSERT_EQ(OK, trust(&client, server));
2110
2111 server->start();
2112
2113 // For TLS, Client should be able to verify server's identity, so client should see
2114 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2115 // identity and should drop the connection, so client shouldn't be able to read anything.
2116 bool readOk = rpcSecurity != RpcSecurity::TLS;
2117 client.run(true, readOk);
2118}
2119
2120TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002121 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2122 (void)serverVersion;
2123
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002124 auto server = std::make_unique<Server>();
2125 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002126
2127 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002128 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002129 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002130 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002131
2132 ASSERT_EQ(OK, trust(&validClient, server));
2133 ASSERT_EQ(OK, trust(&maliciousClient, server));
2134
2135 server->start();
2136
2137 // See UntrustedClient.
2138 bool readOk = rpcSecurity != RpcSecurity::TLS;
2139 maliciousClient.run(true, readOk);
2140}
2141
Yifan Hong67519322021-09-13 18:51:16 -07002142TEST_P(RpcTransportTest, Trigger) {
2143 std::string msg2 = ", world!";
2144 std::mutex writeMutex;
2145 std::condition_variable writeCv;
2146 bool shouldContinueWriting = false;
2147 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002148 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002149 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002150 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2151 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002152 if (status != OK) return AssertionFailure() << statusToString(status);
2153
2154 {
2155 std::unique_lock<std::mutex> lock(writeMutex);
2156 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2157 return AssertionFailure() << "write barrier not cleared in time!";
2158 }
2159 }
2160
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002161 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002162 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2163 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002164 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002165 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002166 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002167 << statusToString(status);
2168 return AssertionSuccess();
2169 };
2170
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002171 auto server = std::make_unique<Server>();
2172 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002173
2174 // Set up client
2175 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002176 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002177
2178 // Exchange keys
2179 ASSERT_EQ(OK, trust(&client, server));
2180 ASSERT_EQ(OK, trust(server, &client));
2181
2182 server->setPostConnect(serverPostConnect);
2183
Yifan Hong67519322021-09-13 18:51:16 -07002184 server->start();
2185 // connect() to server and do handshake
2186 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002187 // read the first message. This ensures that server has finished handshake and start handling
2188 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002189 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002190 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2191 // write is on an FdTrigger that has been shut down.
2192 server->shutdown();
2193 // Continues server thread to write the second message.
2194 {
Yifan Hong22211f82021-09-14 12:32:25 -07002195 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002196 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002197 }
Yifan Hong22211f82021-09-14 12:32:25 -07002198 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002199 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002200 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002201 // On the client side, second read fails with DEAD_OBJECT
2202 ASSERT_FALSE(client.readMessage(msg2));
2203}
2204
Pawan49d74cb2022-08-03 21:19:11 +00002205TEST_P(RpcTransportTest, CheckWaitingForRead) {
2206 std::mutex readMutex;
2207 std::condition_variable readCv;
2208 bool shouldContinueReading = false;
2209 // Server will write data on transport once its started
2210 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
2211 std::string message(RpcTransportTestUtils::kMessage);
2212 iovec messageIov{message.data(), message.size()};
2213 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2214 std::nullopt, nullptr);
2215 if (status != OK) return AssertionFailure() << statusToString(status);
2216
2217 {
2218 std::unique_lock<std::mutex> lock(readMutex);
2219 shouldContinueReading = true;
2220 lock.unlock();
2221 readCv.notify_all();
2222 }
2223 return AssertionSuccess();
2224 };
2225
2226 // Setup Server and client
2227 auto server = std::make_unique<Server>();
2228 ASSERT_TRUE(server->setUp(GetParam()));
2229
2230 Client client(server->getConnectToServerFn());
2231 ASSERT_TRUE(client.setUp(GetParam()));
2232
2233 ASSERT_EQ(OK, trust(&client, server));
2234 ASSERT_EQ(OK, trust(server, &client));
2235 server->setPostConnect(serverPostConnect);
2236
2237 server->start();
2238 ASSERT_TRUE(client.setUpTransport());
2239 {
2240 // Wait till server writes data
2241 std::unique_lock<std::mutex> lock(readMutex);
2242 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2243 }
2244
2245 // Since there is no read polling here, we will get polling count 0
2246 ASSERT_FALSE(client.isTransportWaiting());
2247 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2248 // Thread should increment polling count, read and decrement polling count
2249 // Again, polling count should be zero here
2250 ASSERT_FALSE(client.isTransportWaiting());
2251
2252 server->shutdown();
2253}
2254
Yifan Hong1deca4b2021-09-10 16:16:44 -07002255INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002256 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002257 RpcTransportTest::PrintParamInfo);
2258
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002259class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002260 : public testing::TestWithParam<
2261 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002262public:
2263 template <typename A, typename B>
2264 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002265 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2266 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002267 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2268 }
2269 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002270 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2271 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2272 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002273 };
2274};
2275
2276TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002277 if constexpr (!kEnableRpcThreads) {
2278 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2279 }
2280
Frederick Mayledc07cf82022-05-26 20:30:12 +00002281 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002282
2283 std::vector<uint8_t> pkeyData, certData;
2284 {
2285 auto pkey = makeKeyPairForSelfSignedCert();
2286 ASSERT_NE(nullptr, pkey);
2287 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2288 ASSERT_NE(nullptr, cert);
2289 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2290 certData = serializeCertificate(cert.get(), certificateFormat);
2291 }
2292
2293 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2294 auto desCert = deserializeCertificate(certData, certificateFormat);
2295 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002296 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2297 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002298
2299 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2300 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2301
2302 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2303 ASSERT_TRUE(client.setUp(utilsParam));
2304
2305 ASSERT_EQ(OK, trust(&client, server));
2306 ASSERT_EQ(OK, trust(server, &client));
2307
2308 server->start();
2309 client.run();
2310}
2311
2312INSTANTIATE_TEST_CASE_P(
2313 BinderRpc, RpcTransportTlsKeyTest,
2314 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2315 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002316 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2317 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002318 RpcTransportTlsKeyTest::PrintParamInfo);
2319
Steven Morelandc1635952021-04-01 16:20:47 +00002320} // namespace android
2321
2322int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002323 ::testing::InitGoogleTest(&argc, argv);
2324 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002325
Steven Moreland5553ac42020-11-11 02:14:45 +00002326 return RUN_ALL_TESTS();
2327}