blob: 84c93ddc303530ba56ac738b078ac6909941e3ca [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andrei Homescu9d8adb12022-08-02 04:38:30 +000017#include <aidl/IBinderRpcTest.h>
Frederick Maylea12b0962022-06-25 01:13:22 +000018#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000019
Steven Morelandc1635952021-04-01 16:20:47 +000020#include <chrono>
21#include <cstdlib>
22#include <iostream>
23#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000024#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000025
Andrei Homescu2a298012022-06-15 01:08:54 +000026#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070027#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000029#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000030
Andrei Homescu68a55612022-08-02 01:25:15 +000031#ifdef __ANDROID_VENDOR__
32#include <binder/RpcTransportTipcAndroid.h>
33#include <trusty/tipc.h>
34#endif // __ANDROID_VENDOR__
35
Andrei Homescu2a298012022-06-15 01:08:54 +000036#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000037#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000038
Yifan Hong1a235852021-05-13 16:07:47 -070039using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070040using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070041using testing::AssertionFailure;
42using testing::AssertionResult;
43using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070044
Steven Moreland5553ac42020-11-11 02:14:45 +000045namespace android {
46
Andrei Homescu12106de2022-04-27 04:42:21 +000047#ifdef BINDER_TEST_NO_SHARED_LIBS
48constexpr bool kEnableSharedLibs = false;
49#else
50constexpr bool kEnableSharedLibs = true;
51#endif
52
Andrei Homescu68a55612022-08-02 01:25:15 +000053#ifdef __ANDROID_VENDOR__
54constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
55#endif
56
Frederick Maylea12b0962022-06-25 01:13:22 +000057static std::string WaitStatusToString(int wstatus) {
58 if (WIFEXITED(wstatus)) {
59 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
60 }
61 if (WIFSIGNALED(wstatus)) {
62 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
63 }
64 return base::StringPrintf("unexpected state %d", wstatus);
65}
66
Steven Moreland276d8df2022-09-28 23:56:39 +000067static void debugBacktrace(pid_t pid) {
68 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
69 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
70}
71
Steven Moreland5553ac42020-11-11 02:14:45 +000072class Process {
73public:
Andrei Homescu96834632022-10-14 00:49:49 +000074 Process(Process&& other)
75 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
76 mReadEnd(std::move(other.mReadEnd)),
77 mWriteEnd(std::move(other.mWriteEnd)) {
78 // The default move constructor doesn't clear mPid after moving it,
79 // which we need to do because the destructor checks for mPid!=0
80 mPid = other.mPid;
81 other.mPid = 0;
82 }
Yifan Hong1deca4b2021-09-10 16:16:44 -070083 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
84 android::base::borrowed_fd /* readEnd */)>& f) {
85 android::base::unique_fd childWriteEnd;
86 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +000087 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
88 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +000089 if (0 == (mPid = fork())) {
90 // racey: assume parent doesn't crash before this is set
91 prctl(PR_SET_PDEATHSIG, SIGHUP);
92
Yifan Hong1deca4b2021-09-10 16:16:44 -070093 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +000094
95 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +000096 }
97 }
98 ~Process() {
99 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000100 int wstatus;
101 waitpid(mPid, &wstatus, 0);
102 if (mCustomExitStatusCheck) {
103 mCustomExitStatusCheck(wstatus);
104 } else {
105 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
106 << "server process failed: " << WaitStatusToString(wstatus);
107 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000108 }
109 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700110 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700111 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000112
Frederick Maylea12b0962022-06-25 01:13:22 +0000113 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
114 mCustomExitStatusCheck = std::move(f);
115 }
116
Frederick Mayle69a0c992022-05-26 20:38:39 +0000117 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
118 void terminate() { kill(mPid, SIGTERM); }
119
Steven Moreland276d8df2022-09-28 23:56:39 +0000120 pid_t getPid() { return mPid; }
121
Steven Moreland5553ac42020-11-11 02:14:45 +0000122private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000123 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000124 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700125 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700126 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000127};
128
129static std::string allocateSocketAddress() {
130 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000131 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700132 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
133 unlink(ret.c_str());
134 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000135};
136
Steven Morelandda573042021-06-12 01:13:45 +0000137static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000138 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000139 return vsockPort++;
140}
141
Alice Wang893a9912022-10-24 10:44:09 +0000142static base::unique_fd initUnixSocket(std::string addr) {
143 auto socket_addr = UnixSocketAddress(addr.c_str());
144 base::unique_fd fd(
145 TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
146 CHECK(fd.ok());
147 CHECK_EQ(0, TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize())));
148 return fd;
149}
150
Andrei Homescu96834632022-10-14 00:49:49 +0000151// Destructors need to be defined, even if pure virtual
152ProcessSession::~ProcessSession() {}
153
154class LinuxProcessSession : public ProcessSession {
155public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000156 // reference to process hosting a socket server
157 Process host;
158
Andrei Homescu96834632022-10-14 00:49:49 +0000159 LinuxProcessSession(LinuxProcessSession&&) = default;
160 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
161 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000162 for (auto& session : sessions) {
163 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000164 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000165
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000166 for (auto& info : sessions) {
167 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000168
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000169 EXPECT_NE(nullptr, session);
170 EXPECT_NE(nullptr, session->state());
171 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000172
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000173 wp<RpcSession> weakSession = session;
174 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000175
Steven Moreland57042712022-10-04 23:56:45 +0000176 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
177 // the object should not actually be promotable. By looping, we distinguish a race here
178 // from a bug causing the object to not be promotable.
179 for (size_t i = 0; i < 3; i++) {
180 sp<RpcSession> strongSession = weakSession.promote();
181 EXPECT_EQ(nullptr, strongSession)
182 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
183 "Leaked sess: ")
184 << strongSession->getStrongCount() << " checked time " << i;
185
186 if (strongSession != nullptr) {
187 sleep(1);
188 }
189 }
Steven Moreland736664b2021-05-01 04:27:25 +0000190 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000191 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000192
Andrei Homescu96834632022-10-14 00:49:49 +0000193 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
194 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000195 }
Andrei Homescu96834632022-10-14 00:49:49 +0000196
197 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000198};
199
Yifan Hong1deca4b2021-09-10 16:16:44 -0700200static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700201 base::unique_fd serverFd(
202 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
203 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700204 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
205 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700206
207 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
208 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700209 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
210 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700211 }
212 return serverFd;
213}
214
David Brazdil21c887c2022-09-23 12:25:18 +0100215static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
216 base::unique_fd sockClient, sockServer;
217 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
218 int savedErrno = errno;
219 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
220 }
221
222 int zero = 0;
223 iovec iov{&zero, sizeof(zero)};
224 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
225 fds.emplace_back(std::move(sockServer));
226
227 if (sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
228 int savedErrno = errno;
229 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
230 }
231 return std::move(sockClient);
232}
233
Andrei Homescu96834632022-10-14 00:49:49 +0000234std::string BinderRpc::PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
235 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
236 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
237 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
238 if (singleThreaded) {
239 ret += "_single_threaded";
240 }
241 if (noKernel) {
242 ret += "_no_kernel";
243 }
244 return ret;
245}
Andrei Homescu2a298012022-06-15 01:08:54 +0000246
Andrei Homescu96834632022-10-14 00:49:49 +0000247// This creates a new process serving an interface on a certain number of
248// threads.
249std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
250 const BinderRpcOptions& options) {
251 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000252
Andrei Homescu96834632022-10-14 00:49:49 +0000253 SocketType socketType = std::get<0>(GetParam());
254 RpcSecurity rpcSecurity = std::get<1>(GetParam());
255 uint32_t clientVersion = std::get<2>(GetParam());
256 uint32_t serverVersion = std::get<3>(GetParam());
257 bool singleThreaded = std::get<4>(GetParam());
258 bool noKernel = std::get<5>(GetParam());
259
260 std::string path = android::base::GetExecutableDirectory();
261 auto servicePath = android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
262 singleThreaded ? "_single_threaded" : "",
263 noKernel ? "_no_kernel" : "");
264
Alice Wang1ef010b2022-11-14 09:09:25 +0000265 base::unique_fd bootstrapClientFd, socketFd;
266
Alice Wang893a9912022-10-24 10:44:09 +0000267 auto addr = allocateSocketAddress();
268 // Initializes the socket before the fork/exec.
269 if (socketType == SocketType::UNIX_RAW) {
270 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000271 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
272 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
273 // This is because we cannot pass ParcelFileDescriptor over a pipe.
274 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
275 int savedErrno = errno;
276 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
277 }
Alice Wang893a9912022-10-24 10:44:09 +0000278 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000279
Andrei Homescu96834632022-10-14 00:49:49 +0000280 auto ret = std::make_unique<LinuxProcessSession>(
281 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000282 if (socketType == SocketType::TIPC) {
283 // Trusty has a single persistent service
284 return;
285 }
286
Andrei Homescu96834632022-10-14 00:49:49 +0000287 auto writeFd = std::to_string(writeEnd.get());
288 auto readFd = std::to_string(readEnd.get());
289 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
290 NULL);
291 }));
292
293 BinderRpcTestServerConfig serverConfig;
294 serverConfig.numThreads = options.numThreads;
295 serverConfig.socketType = static_cast<int32_t>(socketType);
296 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
297 serverConfig.serverVersion = serverVersion;
298 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000299 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000300 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000301 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
302 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
303 static_cast<int32_t>(mode));
304 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000305 if (socketType != SocketType::TIPC) {
306 writeToFd(ret->host.writeEnd(), serverConfig);
307 }
Andrei Homescu96834632022-10-14 00:49:49 +0000308
309 std::vector<sp<RpcSession>> sessions;
310 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
311 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000312 std::unique_ptr<RpcTransportCtxFactory> factory;
313 if (socketType == SocketType::TIPC) {
314#ifdef __ANDROID_VENDOR__
315 factory = RpcTransportCtxFactoryTipcAndroid::make();
316#else
317 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
318#endif
319 } else {
320 factory = newFactory(rpcSecurity, certVerifier);
321 }
322 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100323 }
324
Andrei Homescu68a55612022-08-02 01:25:15 +0000325 BinderRpcTestServerInfo serverInfo;
326 if (socketType != SocketType::TIPC) {
327 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
328 BinderRpcTestClientInfo clientInfo;
329 for (const auto& session : sessions) {
330 auto& parcelableCert = clientInfo.certs.emplace_back();
331 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
332 }
333 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000334
Andrei Homescu68a55612022-08-02 01:25:15 +0000335 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
336 if (socketType == SocketType::INET) {
337 CHECK_NE(0, serverInfo.port);
338 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000339
Andrei Homescu68a55612022-08-02 01:25:15 +0000340 if (rpcSecurity == RpcSecurity::TLS) {
341 const auto& serverCert = serverInfo.cert.data;
342 CHECK_EQ(OK,
343 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
344 serverCert));
345 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700346 }
347
Andrei Homescu96834632022-10-14 00:49:49 +0000348 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000349
Andrei Homescu96834632022-10-14 00:49:49 +0000350 for (const auto& session : sessions) {
351 CHECK(session->setProtocolVersion(clientVersion));
352 session->setMaxIncomingThreads(options.numIncomingConnections);
353 session->setMaxOutgoingThreads(options.numOutgoingConnections);
354 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000355
Andrei Homescu96834632022-10-14 00:49:49 +0000356 switch (socketType) {
357 case SocketType::PRECONNECTED:
358 status = session->setupPreconnectedClient({}, [=]() {
359 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
360 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000361 break;
Alice Wang893a9912022-10-24 10:44:09 +0000362 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000363 case SocketType::UNIX:
364 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
365 break;
366 case SocketType::UNIX_BOOTSTRAP:
367 status = session->setupUnixDomainSocketBootstrapClient(
368 base::unique_fd(dup(bootstrapClientFd.get())));
369 break;
370 case SocketType::VSOCK:
371 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
372 break;
373 case SocketType::INET:
374 status = session->setupInetClient("127.0.0.1", serverInfo.port);
375 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000376 case SocketType::TIPC:
377 status = session->setupPreconnectedClient({}, [=]() {
378#ifdef __ANDROID_VENDOR__
379 auto port = trustyIpcPort(serverVersion);
380 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
381 return tipcFd >= 0 ? android::base::unique_fd(tipcFd)
382 : android::base::unique_fd();
383#else
384 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
385 return android::base::unique_fd();
386#endif
387 });
388 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000389 default:
390 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000391 }
Andrei Homescu96834632022-10-14 00:49:49 +0000392 if (options.allowConnectFailure && status != OK) {
393 ret->sessions.clear();
394 break;
395 }
396 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
397 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000398 }
Andrei Homescu96834632022-10-14 00:49:49 +0000399 return ret;
400}
Steven Morelandc1635952021-04-01 16:20:47 +0000401
Andrei Homescua858b0e2022-08-01 23:43:09 +0000402TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
403 if (clientOrServerSingleThreaded()) {
404 GTEST_SKIP() << "This test requires multiple threads";
405 }
406
Steven Moreland5553ac42020-11-11 02:14:45 +0000407 constexpr size_t kNumThreads = 10;
408
Steven Moreland4313d7e2021-07-15 23:41:22 +0000409 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000410
411 EXPECT_OK(proc.rootIface->lock());
412
413 // block all but one thread taking locks
414 std::vector<std::thread> ts;
415 for (size_t i = 0; i < kNumThreads - 1; i++) {
416 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
417 }
418
Steven Morelandd6d816f2022-12-23 01:37:17 +0000419 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000420
421 // other calls still work
422 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
423
Steven Morelandd6d816f2022-12-23 01:37:17 +0000424 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000425 size_t epochMsBefore = epochMillis();
426 // after this, we should never see a response within this time
427 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
428
429 // this call should be blocked for blockTimeMs
430 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
431
432 size_t epochMsAfter = epochMillis();
433 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
434
435 for (auto& t : ts) t.join();
436}
437
Andrei Homescu96834632022-10-14 00:49:49 +0000438static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
439 size_t sleepMs = 500) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000440 size_t epochMsBefore = epochMillis();
441
442 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700443 for (size_t i = 0; i < numCalls; i++) {
444 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000445 }
446
447 for (auto& t : ts) t.join();
448
449 size_t epochMsAfter = epochMillis();
450
Yifan Hong1f44f982021-10-08 17:16:47 -0700451 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000452
453 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700454 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
455}
456
Andrei Homescua858b0e2022-08-01 23:43:09 +0000457TEST_P(BinderRpc, ThreadPoolOverSaturated) {
458 if (clientOrServerSingleThreaded()) {
459 GTEST_SKIP() << "This test requires multiple threads";
460 }
461
Yifan Hong1f44f982021-10-08 17:16:47 -0700462 constexpr size_t kNumThreads = 10;
463 constexpr size_t kNumCalls = kNumThreads + 3;
464 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
465 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
466}
467
Andrei Homescua858b0e2022-08-01 23:43:09 +0000468TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
469 if (clientOrServerSingleThreaded()) {
470 GTEST_SKIP() << "This test requires multiple threads";
471 }
472
Yifan Hong1f44f982021-10-08 17:16:47 -0700473 constexpr size_t kNumThreads = 20;
474 constexpr size_t kNumOutgoingConnections = 10;
475 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
476 auto proc = createRpcTestSocketServerProcess(
477 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
478 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000479}
480
Andrei Homescua858b0e2022-08-01 23:43:09 +0000481TEST_P(BinderRpc, ThreadingStressTest) {
482 if (clientOrServerSingleThreaded()) {
483 GTEST_SKIP() << "This test requires multiple threads";
484 }
485
Steven Moreland5553ac42020-11-11 02:14:45 +0000486 constexpr size_t kNumClientThreads = 10;
487 constexpr size_t kNumServerThreads = 10;
488 constexpr size_t kNumCalls = 100;
489
Steven Moreland4313d7e2021-07-15 23:41:22 +0000490 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000491
492 std::vector<std::thread> threads;
493 for (size_t i = 0; i < kNumClientThreads; i++) {
494 threads.push_back(std::thread([&] {
495 for (size_t j = 0; j < kNumCalls; j++) {
496 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000497 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000498 EXPECT_EQ(proc.rootBinder, out);
499 }
500 }));
501 }
502
503 for (auto& t : threads) t.join();
504}
505
Steven Moreland925ba0a2021-09-17 18:06:32 -0700506static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
507 std::vector<std::thread> threads;
508 for (size_t i = 0; i < threadCount; i++) {
509 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
510 }
511 for (auto& t : threads) t.join();
512}
513
Andrei Homescua858b0e2022-08-01 23:43:09 +0000514TEST_P(BinderRpc, OnewayStressTest) {
515 if (clientOrServerSingleThreaded()) {
516 GTEST_SKIP() << "This test requires multiple threads";
517 }
518
Steven Morelandc6046982021-04-20 00:49:42 +0000519 constexpr size_t kNumClientThreads = 10;
520 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700521 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000522
Steven Moreland4313d7e2021-07-15 23:41:22 +0000523 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000524
525 std::vector<std::thread> threads;
526 for (size_t i = 0; i < kNumClientThreads; i++) {
527 threads.push_back(std::thread([&] {
528 for (size_t j = 0; j < kNumCalls; j++) {
529 EXPECT_OK(proc.rootIface->sendString("a"));
530 }
Steven Morelandc6046982021-04-20 00:49:42 +0000531 }));
532 }
533
534 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700535
536 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000537}
538
Frederick Mayleb0221d12022-10-03 23:10:53 +0000539TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
540 if (!supportsFdTransport()) {
541 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
542 }
543 if (clientOrServerSingleThreaded()) {
544 GTEST_SKIP() << "This test requires multiple threads";
545 }
546
547 // This test forces a oneway transaction to be queued by issuing two
548 // `blockingSendFdOneway` calls, then drains the queue by issuing two
549 // `blockingRecvFd` calls.
550 //
551 // For more details about the queuing semantics see
552 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
553
554 auto proc = createRpcTestSocketServerProcess({
555 .numThreads = 3,
556 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
557 .serverSupportedFileDescriptorTransportModes =
558 {RpcSession::FileDescriptorTransportMode::UNIX},
559 });
560
561 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
562 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
563 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
564 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
565
566 android::os::ParcelFileDescriptor fdA;
567 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
568 std::string result;
569 CHECK(android::base::ReadFdToString(fdA.get(), &result));
570 EXPECT_EQ(result, "a");
571
572 android::os::ParcelFileDescriptor fdB;
573 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
574 CHECK(android::base::ReadFdToString(fdB.get(), &result));
575 EXPECT_EQ(result, "b");
576}
577
Andrei Homescua858b0e2022-08-01 23:43:09 +0000578TEST_P(BinderRpc, OnewayCallQueueing) {
579 if (clientOrServerSingleThreaded()) {
580 GTEST_SKIP() << "This test requires multiple threads";
581 }
582
Steven Moreland5553ac42020-11-11 02:14:45 +0000583 constexpr size_t kNumSleeps = 10;
584 constexpr size_t kNumExtraServerThreads = 4;
585 constexpr size_t kSleepMs = 50;
586
587 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000588 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000589
590 EXPECT_OK(proc.rootIface->lock());
591
Steven Moreland1c678802021-09-17 16:48:47 -0700592 size_t epochMsBefore = epochMillis();
593
594 // all these *Async commands should be queued on the server sequentially,
595 // even though there are multiple threads.
596 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000597 proc.rootIface->sleepMsAsync(kSleepMs);
598 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000599 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
600
Steven Moreland1c678802021-09-17 16:48:47 -0700601 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000602 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700603
Steven Moreland5553ac42020-11-11 02:14:45 +0000604 size_t epochMsAfter = epochMillis();
605
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000606 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000607
Steven Moreland925ba0a2021-09-17 18:06:32 -0700608 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000609}
610
Andrei Homescua858b0e2022-08-01 23:43:09 +0000611TEST_P(BinderRpc, OnewayCallExhaustion) {
612 if (clientOrServerSingleThreaded()) {
613 GTEST_SKIP() << "This test requires multiple threads";
614 }
615
Steven Morelandd45be622021-06-04 02:19:37 +0000616 constexpr size_t kNumClients = 2;
617 constexpr size_t kTooLongMs = 1000;
618
Steven Moreland4313d7e2021-07-15 23:41:22 +0000619 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000620
621 // Build up oneway calls on the second session to make sure it terminates
622 // and shuts down. The first session should be unaffected (proc destructor
623 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000624 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000625
626 std::vector<std::thread> threads;
627 for (size_t i = 0; i < kNumClients; i++) {
628 // one of these threads will get stuck queueing a transaction once the
629 // socket fills up, the other will be able to fill up transactions on
630 // this object
631 threads.push_back(std::thread([&] {
632 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
633 }
634 }));
635 }
636 for (auto& t : threads) t.join();
637
638 Status status = iface->sleepMsAsync(kTooLongMs);
639 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
640
Steven Moreland798e0d12021-07-14 23:19:25 +0000641 // now that it has died, wait for the remote session to shutdown
642 std::vector<int32_t> remoteCounts;
643 do {
644 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
645 } while (remoteCounts.size() == kNumClients);
646
Steven Morelandd45be622021-06-04 02:19:37 +0000647 // the second session should be shutdown in the other process by the time we
648 // are able to join above (it'll only be hung up once it finishes processing
649 // any pending commands). We need to erase this session from the record
650 // here, so that the destructor for our session won't check that this
651 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000652 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000653}
654
Devin Moore66d5b7a2022-07-07 21:42:10 +0000655TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000656 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000657 GTEST_SKIP() << "This test requires multiple threads";
658 }
659 class MyDeathRec : public IBinder::DeathRecipient {
660 public:
661 void binderDied(const wp<IBinder>& /* who */) override {
662 dead = true;
663 mCv.notify_one();
664 }
665 std::mutex mMtx;
666 std::condition_variable mCv;
667 bool dead = false;
668 };
669
670 // Death recipient needs to have an incoming connection to be called
671 auto proc = createRpcTestSocketServerProcess(
672 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
673
674 auto dr = sp<MyDeathRec>::make();
675 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
676
677 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
678 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
679 }
680
681 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000682 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000683
684 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000685 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000686 proc.expectAlreadyShutdown = true;
687}
688
689TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000690 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000691 GTEST_SKIP() << "This test requires multiple threads";
692 }
693 class MyDeathRec : public IBinder::DeathRecipient {
694 public:
695 void binderDied(const wp<IBinder>& /* who */) override {
696 dead = true;
697 mCv.notify_one();
698 }
699 std::mutex mMtx;
700 std::condition_variable mCv;
701 bool dead = false;
702 };
703
704 // Death recipient needs to have an incoming connection to be called
705 auto proc = createRpcTestSocketServerProcess(
706 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
707
708 auto dr = sp<MyDeathRec>::make();
709 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
710
711 // Explicitly calling shutDownAndWait will cause the death recipients
712 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000713 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000714
715 std::unique_lock<std::mutex> lock(dr->mMtx);
716 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000717 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000718 }
719 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
720
Andrei Homescu96834632022-10-14 00:49:49 +0000721 proc.proc->terminate();
722 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000723 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
724 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
725 });
726 proc.expectAlreadyShutdown = true;
727}
728
Steven Moreland5ec743f2023-01-18 01:02:06 +0000729TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000730 if (socketType() == SocketType::TIPC) {
731 // This should work, but Trusty takes too long to restart the service
732 GTEST_SKIP() << "Service death test not supported on Trusty";
733 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000734 class MyDeathRec : public IBinder::DeathRecipient {
735 public:
736 void binderDied(const wp<IBinder>& /* who */) override {}
737 };
738
739 auto proc = createRpcTestSocketServerProcess(
740 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
741
742 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000743 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000744}
745
746TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000747 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000748 GTEST_SKIP() << "This test requires multiple threads";
749 }
750 class MyDeathRec : public IBinder::DeathRecipient {
751 public:
752 void binderDied(const wp<IBinder>& /* who */) override {
753 GTEST_FAIL() << "This should not be called after unlinkToDeath";
754 }
755 };
756
757 // Death recipient needs to have an incoming connection to be called
758 auto proc = createRpcTestSocketServerProcess(
759 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
760
761 auto dr = sp<MyDeathRec>::make();
762 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
763 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
764
765 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
766 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
767 }
768
769 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000770 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000771 proc.expectAlreadyShutdown = true;
772}
773
Steven Morelandc1635952021-04-01 16:20:47 +0000774TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000775 if (socketType() == SocketType::TIPC) {
776 // This should work, but Trusty takes too long to restart the service
777 GTEST_SKIP() << "Service death test not supported on Trusty";
778 }
779
Steven Moreland5553ac42020-11-11 02:14:45 +0000780 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000781 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000782
783 // make sure there is some state during crash
784 // 1. we hold their binder
785 sp<IBinderRpcSession> session;
786 EXPECT_OK(proc.rootIface->openSession("happy", &session));
787 // 2. they hold our binder
788 sp<IBinder> binder = new BBinder();
789 EXPECT_OK(proc.rootIface->holdBinder(binder));
790
791 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
792 << "Do death cleanup: " << doDeathCleanup;
793
Andrei Homescu96834632022-10-14 00:49:49 +0000794 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000795 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
796 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
797 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000798 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000799 }
800}
801
Steven Morelandd7302072021-05-15 01:32:04 +0000802TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000803 // This test only works if the current process shared the internal state of
804 // ProcessState with the service across the call to fork(). Both the static
805 // libraries and libbinder.so have their own separate copies of all the
806 // globals, so the test only works when the test client and service both use
807 // libbinder.so (when using static libraries, even a client and service
808 // using the same kind of static library should have separate copies of the
809 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000810 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000811 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
812 "at build time.";
813 }
814
Steven Moreland4313d7e2021-07-15 23:41:22 +0000815 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000816
Andrei Homescu2a298012022-06-15 01:08:54 +0000817 // we can't allocate IPCThreadState so actually the first time should
818 // succeed :(
819 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000820
821 // second time! we catch the error :)
822 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
823
Andrei Homescu96834632022-10-14 00:49:49 +0000824 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000825 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
826 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
827 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000828 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000829}
830
Frederick Mayle69a0c992022-05-26 20:38:39 +0000831TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000832 if (socketType() == SocketType::TIPC) {
833 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
834 }
835
Frederick Mayle69a0c992022-05-26 20:38:39 +0000836 auto proc = createRpcTestSocketServerProcess({
837 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
838 .serverSupportedFileDescriptorTransportModes =
839 {RpcSession::FileDescriptorTransportMode::UNIX},
840 .allowConnectFailure = true,
841 });
Andrei Homescu96834632022-10-14 00:49:49 +0000842 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
843 proc.proc->terminate();
844 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000845 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
846 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
847 });
848 proc.expectAlreadyShutdown = true;
849}
850
851TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000852 if (socketType() == SocketType::TIPC) {
853 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
854 }
855
Frederick Mayle69a0c992022-05-26 20:38:39 +0000856 auto proc = createRpcTestSocketServerProcess({
857 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
858 .serverSupportedFileDescriptorTransportModes =
859 {RpcSession::FileDescriptorTransportMode::NONE},
860 .allowConnectFailure = true,
861 });
Andrei Homescu96834632022-10-14 00:49:49 +0000862 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
863 proc.proc->terminate();
864 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000865 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
866 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
867 });
868 proc.expectAlreadyShutdown = true;
869}
870
871TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000872 if (socketType() == SocketType::TIPC) {
873 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
874 }
875
Frederick Mayle69a0c992022-05-26 20:38:39 +0000876 auto proc = createRpcTestSocketServerProcess({
877 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
878 .serverSupportedFileDescriptorTransportModes =
879 {RpcSession::FileDescriptorTransportMode::NONE,
880 RpcSession::FileDescriptorTransportMode::UNIX},
881 });
882
883 android::os::ParcelFileDescriptor out;
884 auto status = proc.rootIface->echoAsFile("hello", &out);
885 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
886}
887
888TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000889 if (socketType() == SocketType::TIPC) {
890 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
891 }
892
Frederick Mayle69a0c992022-05-26 20:38:39 +0000893 auto proc = createRpcTestSocketServerProcess({
894 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
895 .serverSupportedFileDescriptorTransportModes =
896 {RpcSession::FileDescriptorTransportMode::UNIX},
897 });
898
899 android::os::ParcelFileDescriptor out;
900 auto status = proc.rootIface->echoAsFile("hello", &out);
901 if (!supportsFdTransport()) {
902 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
903 return;
904 }
905 ASSERT_TRUE(status.isOk()) << status;
906
907 std::string result;
908 CHECK(android::base::ReadFdToString(out.get(), &result));
909 EXPECT_EQ(result, "hello");
910}
911
912TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000913 if (socketType() == SocketType::TIPC) {
914 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
915 }
916
Frederick Mayle69a0c992022-05-26 20:38:39 +0000917 auto proc = createRpcTestSocketServerProcess({
918 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
919 .serverSupportedFileDescriptorTransportModes =
920 {RpcSession::FileDescriptorTransportMode::UNIX},
921 });
922
923 std::vector<android::os::ParcelFileDescriptor> files;
924 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
925 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
926 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
927 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
928
929 android::os::ParcelFileDescriptor out;
930 auto status = proc.rootIface->concatFiles(files, &out);
931 if (!supportsFdTransport()) {
932 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
933 return;
934 }
935 ASSERT_TRUE(status.isOk()) << status;
936
937 std::string result;
938 CHECK(android::base::ReadFdToString(out.get(), &result));
939 EXPECT_EQ(result, "123abcd");
940}
941
942TEST_P(BinderRpc, SendMaxFiles) {
943 if (!supportsFdTransport()) {
944 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
945 }
946
947 auto proc = createRpcTestSocketServerProcess({
948 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
949 .serverSupportedFileDescriptorTransportModes =
950 {RpcSession::FileDescriptorTransportMode::UNIX},
951 });
952
953 std::vector<android::os::ParcelFileDescriptor> files;
954 for (int i = 0; i < 253; i++) {
955 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
956 }
957
958 android::os::ParcelFileDescriptor out;
959 auto status = proc.rootIface->concatFiles(files, &out);
960 ASSERT_TRUE(status.isOk()) << status;
961
962 std::string result;
963 CHECK(android::base::ReadFdToString(out.get(), &result));
964 EXPECT_EQ(result, std::string(253, 'a'));
965}
966
967TEST_P(BinderRpc, SendTooManyFiles) {
968 if (!supportsFdTransport()) {
969 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
970 }
971
972 auto proc = createRpcTestSocketServerProcess({
973 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
974 .serverSupportedFileDescriptorTransportModes =
975 {RpcSession::FileDescriptorTransportMode::UNIX},
976 });
977
978 std::vector<android::os::ParcelFileDescriptor> files;
979 for (int i = 0; i < 254; i++) {
980 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
981 }
982
983 android::os::ParcelFileDescriptor out;
984 auto status = proc.rootIface->concatFiles(files, &out);
985 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
986}
987
Andrei Homescufc221502022-10-08 03:51:17 +0000988TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000989 if (socketType() == SocketType::TIPC) {
990 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
991 }
992
Andrei Homescufc221502022-10-08 03:51:17 +0000993 auto proc = createRpcTestSocketServerProcess({
994 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
995 .serverSupportedFileDescriptorTransportModes =
996 {RpcSession::FileDescriptorTransportMode::UNIX},
997 });
998
999 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1000 ASSERT_NE(badFd, -1);
1001
1002 // Close the file descriptor so it becomes invalid for dup
1003 close(badFd);
1004
1005 Parcel p1;
1006 p1.markForBinder(proc.rootBinder);
1007 p1.writeInt32(3);
1008 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1009
1010 Parcel pRaw;
1011 pRaw.markForBinder(proc.rootBinder);
1012 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1013
1014 pRaw.setDataPosition(0);
1015 EXPECT_EQ(3, pRaw.readInt32());
1016 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1017}
1018
Andrei Homescu68a55612022-08-02 01:25:15 +00001019#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001020TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001021 if constexpr (!kEnableSharedLibs) {
1022 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1023 }
1024
Steven Moreland4313d7e2021-07-15 23:41:22 +00001025 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001026
1027 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1028 ASSERT_NE(binder, nullptr);
1029
1030 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1031}
1032
1033TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001034 if constexpr (!kEnableSharedLibs) {
1035 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1036 }
1037
Steven Moreland4313d7e2021-07-15 23:41:22 +00001038 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001039
1040 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1041 ASSERT_NE(binder, nullptr);
1042
1043 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1044 ASSERT_NE(ndkBinder, nullptr);
1045
1046 std::string out;
1047 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1048 ASSERT_TRUE(status.isOk()) << status.getDescription();
1049 ASSERT_EQ("aoeuaoeu", out);
1050}
Andrei Homescu68a55612022-08-02 01:25:15 +00001051#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001052
Steven Moreland5553ac42020-11-11 02:14:45 +00001053ssize_t countFds() {
1054 DIR* dir = opendir("/proc/self/fd/");
1055 if (dir == nullptr) return -1;
1056 ssize_t ret = 0;
1057 dirent* ent;
1058 while ((ent = readdir(dir)) != nullptr) ret++;
1059 closedir(dir);
1060 return ret;
1061}
1062
Andrei Homescua858b0e2022-08-01 23:43:09 +00001063TEST_P(BinderRpc, Fds) {
1064 if (serverSingleThreaded()) {
1065 GTEST_SKIP() << "This test requires multiple threads";
1066 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001067 if (socketType() == SocketType::TIPC) {
1068 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1069 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001070
Steven Moreland5553ac42020-11-11 02:14:45 +00001071 ssize_t beforeFds = countFds();
1072 ASSERT_GE(beforeFds, 0);
1073 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001074 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001075 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1076 }
1077 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1078}
1079
Steven Morelandda573042021-06-12 01:13:45 +00001080static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001081 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001082 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001083
Andrei Homescu992a4052022-06-28 21:26:18 +00001084 android::base::unique_fd serverFd(
1085 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1086 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1087
1088 sockaddr_vm serverAddr{
1089 .svm_family = AF_VSOCK,
1090 .svm_port = vsockPort,
1091 .svm_cid = VMADDR_CID_ANY,
1092 };
1093 int ret = TEMP_FAILURE_RETRY(
1094 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1095 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1096 strerror(errno));
1097
1098 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1099 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1100 strerror(errno));
1101
1102 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1103 // to see if the kernel supports it. It's safe to use a blocking
1104 // connect because vsock sockets have a 2 second connection timeout,
1105 // and they return ETIMEDOUT after that.
1106 android::base::unique_fd connectFd(
1107 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1108 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1109 strerror(errno));
1110
1111 bool success = false;
1112 sockaddr_vm connectAddr{
1113 .svm_family = AF_VSOCK,
1114 .svm_port = vsockPort,
1115 .svm_cid = VMADDR_CID_LOCAL,
1116 };
1117 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1118 sizeof(connectAddr)));
1119 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1120 android::base::unique_fd acceptFd;
1121 while (true) {
1122 pollfd pfd[]{
1123 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1124 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1125 };
1126 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1127 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1128
1129 if (pfd[0].revents & POLLIN) {
1130 sockaddr_vm acceptAddr;
1131 socklen_t acceptAddrLen = sizeof(acceptAddr);
1132 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1133 reinterpret_cast<sockaddr*>(&acceptAddr),
1134 &acceptAddrLen, SOCK_CLOEXEC));
1135 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1136 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1137 "Truncated address");
1138
1139 // Store the fd in acceptFd so we keep the connection alive
1140 // while polling connectFd
1141 acceptFd.reset(ret);
1142 }
1143
1144 if (pfd[1].revents & POLLOUT) {
1145 // Connect either succeeded or timed out
1146 int connectErrno;
1147 socklen_t connectErrnoLen = sizeof(connectErrno);
1148 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1149 &connectErrnoLen);
1150 LOG_ALWAYS_FATAL_IF(ret == -1,
1151 "Could not getsockopt() after connect() "
1152 "on non-blocking socket: %s.",
1153 strerror(errno));
1154
1155 // We're done, this is all we wanted
1156 success = connectErrno == 0;
1157 break;
1158 }
1159 }
1160 } else {
1161 success = ret == 0;
1162 }
1163
1164 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1165
1166 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001167}
1168
Yifan Hong1deca4b2021-09-10 16:16:44 -07001169static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001170 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1171 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001172
1173 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001174
1175 static bool hasVsockLoopback = testSupportVsockLoopback();
1176
1177 if (hasVsockLoopback) {
1178 ret.push_back(SocketType::VSOCK);
1179 }
1180
1181 return ret;
1182}
1183
Andrei Homescu68a55612022-08-02 01:25:15 +00001184static std::vector<SocketType> testTipcSocketTypes() {
1185#ifdef __ANDROID_VENDOR__
1186 auto port = trustyIpcPort(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1187 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
1188 if (tipcFd >= 0) {
1189 close(tipcFd);
1190 return {SocketType::TIPC};
1191 }
1192#endif // __ANDROID_VENDOR__
1193
1194 // TIPC is not supported on this device, most likely
1195 // because /dev/trusty-ipc-dev0 is missing
1196 return {};
1197}
1198
Yifan Hong702115c2021-06-24 15:39:18 -07001199INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1200 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001201 ::testing::ValuesIn(RpcSecurityValues()),
1202 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001203 ::testing::ValuesIn(testVersions()),
1204 ::testing::Values(false, true),
1205 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001206 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001207
Andrei Homescu68a55612022-08-02 01:25:15 +00001208INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc,
1209 ::testing::Combine(::testing::ValuesIn(testTipcSocketTypes()),
1210 ::testing::Values(RpcSecurity::RAW),
1211 ::testing::ValuesIn(testVersions()),
1212 ::testing::ValuesIn(testVersions()),
1213 ::testing::Values(true), ::testing::Values(true)),
1214 BinderRpc::PrintParamInfo);
1215
Yifan Hong702115c2021-06-24 15:39:18 -07001216class BinderRpcServerRootObject
1217 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001218
1219TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1220 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1221 auto setRootObject = [](bool isStrong) -> SetFn {
1222 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1223 };
1224
Yifan Hong702115c2021-06-24 15:39:18 -07001225 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1226 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001227 auto binder1 = sp<BBinder>::make();
1228 IBinder* binderRaw1 = binder1.get();
1229 setRootObject(isStrong1)(server.get(), binder1);
1230 EXPECT_EQ(binderRaw1, server->getRootObject());
1231 binder1.clear();
1232 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1233
1234 auto binder2 = sp<BBinder>::make();
1235 IBinder* binderRaw2 = binder2.get();
1236 setRootObject(isStrong2)(server.get(), binder2);
1237 EXPECT_EQ(binderRaw2, server->getRootObject());
1238 binder2.clear();
1239 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1240}
1241
1242INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001243 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1244 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001245
Yifan Hong1a235852021-05-13 16:07:47 -07001246class OneOffSignal {
1247public:
1248 // If notify() was previously called, or is called within |duration|, return true; else false.
1249 template <typename R, typename P>
1250 bool wait(std::chrono::duration<R, P> duration) {
1251 std::unique_lock<std::mutex> lock(mMutex);
1252 return mCv.wait_for(lock, duration, [this] { return mValue; });
1253 }
1254 void notify() {
1255 std::unique_lock<std::mutex> lock(mMutex);
1256 mValue = true;
1257 lock.unlock();
1258 mCv.notify_all();
1259 }
1260
1261private:
1262 std::mutex mMutex;
1263 std::condition_variable mCv;
1264 bool mValue = false;
1265};
1266
Yifan Hong194acf22021-06-29 18:44:56 -07001267TEST(BinderRpc, Java) {
1268#if !defined(__ANDROID__)
1269 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1270 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1271 "to binderHostDeviceTest. Hence, just disable this test on host.";
1272#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001273 if constexpr (!kEnableKernelIpc) {
1274 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1275 "at build time.";
1276 }
1277
Yifan Hong194acf22021-06-29 18:44:56 -07001278 sp<IServiceManager> sm = defaultServiceManager();
1279 ASSERT_NE(nullptr, sm);
1280 // Any Java service with non-empty getInterfaceDescriptor() would do.
1281 // Let's pick batteryproperties.
1282 auto binder = sm->checkService(String16("batteryproperties"));
1283 ASSERT_NE(nullptr, binder);
1284 auto descriptor = binder->getInterfaceDescriptor();
1285 ASSERT_GE(descriptor.size(), 0);
1286 ASSERT_EQ(OK, binder->pingBinder());
1287
1288 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001289 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001290 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001291 auto socket = rpcServer->releaseServer();
1292
1293 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001294 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1295
Yifan Honge3caaf22022-01-12 14:46:56 -08001296 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1297 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001298 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001299 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1300 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001301 << statusToString(setRpcClientDebugStatus);
1302 GTEST_SKIP();
1303 }
1304
1305 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001306
1307 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001308 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001309 auto rpcBinder = rpcSession->getRootObject();
1310 ASSERT_NE(nullptr, rpcBinder);
1311
1312 ASSERT_EQ(OK, rpcBinder->pingBinder());
1313
1314 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1315 << "getInterfaceDescriptor should not crash system_server";
1316 ASSERT_EQ(OK, rpcBinder->pingBinder());
1317}
1318
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001319class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1320public:
1321 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1322 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1323 std::to_string(std::get<1>(info.param));
1324 }
1325};
1326
1327TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1328 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1329 int sinkFd = sink.get();
1330 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1331 server->setProtocolVersion(std::get<1>(GetParam()));
1332 ASSERT_FALSE(server->hasServer());
1333 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1334 ASSERT_TRUE(server->hasServer());
1335 base::unique_fd retrieved = server->releaseServer();
1336 ASSERT_FALSE(server->hasServer());
1337 ASSERT_EQ(sinkFd, retrieved.get());
1338}
1339
1340TEST_P(BinderRpcServerOnly, Shutdown) {
1341 if constexpr (!kEnableRpcThreads) {
1342 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1343 }
1344
1345 auto addr = allocateSocketAddress();
1346 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1347 server->setProtocolVersion(std::get<1>(GetParam()));
1348 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1349 auto joinEnds = std::make_shared<OneOffSignal>();
1350
1351 // If things are broken and the thread never stops, don't block other tests. Because the thread
1352 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1353 // shared pointers are passed.
1354 std::thread([server, joinEnds] {
1355 server->join();
1356 joinEnds->notify();
1357 }).detach();
1358
1359 bool shutdown = false;
1360 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001361 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001362 if (server->shutdown()) shutdown = true;
1363 }
1364 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1365
1366 ASSERT_TRUE(joinEnds->wait(2s))
1367 << "After server->shutdown() returns true, join() did not stop after 2s";
1368}
1369
Frederick Mayledc07cf82022-05-26 20:30:12 +00001370INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1371 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1372 ::testing::ValuesIn(testVersions())),
1373 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001374
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001375class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001376public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001377 // Only parameterized only server version because `RpcSession` is bypassed
1378 // in the client half of the tests.
1379 using Param =
1380 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001381 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001382
1383 // A server that handles client socket connections.
1384 class Server {
1385 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001386 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1387
Yifan Hong1deca4b2021-09-10 16:16:44 -07001388 explicit Server() {}
1389 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001390 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001391 [[nodiscard]] AssertionResult setUp(
1392 const Param& param,
1393 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001394 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001395 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001396 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001397 switch (socketType) {
1398 case SocketType::PRECONNECTED: {
1399 return AssertionFailure() << "Not supported by this test";
1400 } break;
1401 case SocketType::UNIX: {
1402 auto addr = allocateSocketAddress();
1403 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1404 if (status != OK) {
1405 return AssertionFailure()
1406 << "setupUnixDomainServer: " << statusToString(status);
1407 }
1408 mConnectToServer = [addr] {
1409 return connectTo(UnixSocketAddress(addr.c_str()));
1410 };
1411 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001412 case SocketType::UNIX_BOOTSTRAP: {
1413 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1414 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1415 return AssertionFailure() << "Socketpair() failed";
1416 }
1417 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1418 std::move(bootstrapFdServer));
1419 if (status != OK) {
1420 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1421 << statusToString(status);
1422 }
1423 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1424 mAcceptConnection = &Server::recvmsgServerConnection;
1425 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1426 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001427 case SocketType::UNIX_RAW: {
1428 auto addr = allocateSocketAddress();
1429 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1430 if (status != OK) {
1431 return AssertionFailure()
1432 << "setupRawSocketServer: " << statusToString(status);
1433 }
1434 mConnectToServer = [addr] {
1435 return connectTo(UnixSocketAddress(addr.c_str()));
1436 };
1437 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001438 case SocketType::VSOCK: {
1439 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001440 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001441 if (status != OK) {
1442 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1443 }
1444 mConnectToServer = [port] {
1445 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1446 };
1447 } break;
1448 case SocketType::INET: {
1449 unsigned int port;
1450 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1451 if (status != OK) {
1452 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1453 }
1454 mConnectToServer = [port] {
1455 const char* addr = kLocalInetAddress;
1456 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1457 if (aiStart == nullptr) return base::unique_fd{};
1458 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1459 auto fd = connectTo(
1460 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1461 if (fd.ok()) return fd;
1462 }
1463 ALOGE("None of the socket address resolved for %s:%u can be connected",
1464 addr, port);
1465 return base::unique_fd{};
1466 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001467 } break;
1468 case SocketType::TIPC: {
1469 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1470 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001471 }
1472 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001473 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001474 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001475 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1476 mSetup = true;
1477 return AssertionSuccess();
1478 }
1479 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1480 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1481 return mCertVerifier;
1482 }
1483 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1484 void start() {
1485 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1486 mThread = std::make_unique<std::thread>(&Server::run, this);
1487 }
David Brazdil21c887c2022-09-23 12:25:18 +01001488
1489 base::unique_fd acceptServerConnection() {
1490 return base::unique_fd(TEMP_FAILURE_RETRY(
1491 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1492 }
1493
1494 base::unique_fd recvmsgServerConnection() {
1495 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1496 int buf;
1497 iovec iov{&buf, sizeof(buf)};
1498
1499 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1500 int savedErrno = errno;
1501 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1502 }
1503 if (fds.size() != 1) {
1504 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1505 }
1506 return std::move(std::get<base::unique_fd>(fds[0]));
1507 }
1508
Yifan Hong1deca4b2021-09-10 16:16:44 -07001509 void run() {
1510 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1511
1512 std::vector<std::thread> threads;
1513 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001514 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001515 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1516 }
1517
1518 for (auto& thread : threads) thread.join();
1519 }
1520 void handleOne(android::base::unique_fd acceptedFd) {
1521 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001522 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001523 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001524 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001525 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001526 }
Yifan Honge07d2732021-09-13 21:59:14 -07001527 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001528 shutdown();
1529 join();
1530 }
1531 void shutdown() { mFdTrigger->trigger(); }
1532
1533 void setPostConnect(
1534 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1535 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001536 }
1537
1538 private:
1539 std::unique_ptr<std::thread> mThread;
1540 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001541 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001542 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001543 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001544 std::unique_ptr<RpcTransportCtx> mCtx;
1545 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1546 std::make_shared<RpcCertificateVerifierSimple>();
1547 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001548 // The function invoked after connection and handshake. By default, it is
1549 // |defaultPostConnect| that sends |kMessage| to the client.
1550 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1551 Server::defaultPostConnect;
1552
1553 void join() {
1554 if (mThread != nullptr) {
1555 mThread->join();
1556 mThread = nullptr;
1557 }
1558 }
1559
1560 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1561 FdTrigger* fdTrigger) {
1562 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001563 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001564 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001565 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001566 if (status != OK) return AssertionFailure() << statusToString(status);
1567 return AssertionSuccess();
1568 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001569 };
1570
1571 class Client {
1572 public:
1573 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1574 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001575 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001576 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1577 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001578 mFdTrigger = FdTrigger::make();
1579 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1580 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1581 return AssertionSuccess();
1582 }
1583 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1584 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1585 return mCertVerifier;
1586 }
Yifan Hong67519322021-09-13 18:51:16 -07001587 // connect() and do handshake
1588 bool setUpTransport() {
1589 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001590 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001591 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1592 return mClientTransport != nullptr;
1593 }
1594 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1595 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1596 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001597 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001598 status_t readStatus =
1599 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001600 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001601 if (readStatus != OK) {
1602 return AssertionFailure() << statusToString(readStatus);
1603 }
1604 if (readMessage != expectedMessage) {
1605 return AssertionFailure()
1606 << "Expected " << expectedMessage << ", actual " << readMessage;
1607 }
1608 return AssertionSuccess();
1609 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001610 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001611 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001612 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1613 return;
1614 }
1615 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001616 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001617 }
1618
Pawan49d74cb2022-08-03 21:19:11 +00001619 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1620
Yifan Hong1deca4b2021-09-10 16:16:44 -07001621 private:
1622 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001623 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001624 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1625 std::unique_ptr<RpcTransportCtx> mCtx;
1626 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1627 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001628 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001629 };
1630
1631 // Make A trust B.
1632 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001633 static status_t trust(RpcSecurity rpcSecurity,
1634 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1635 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001636 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001637 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1638 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1639 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001640 }
1641
1642 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001643};
1644
1645class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1646public:
1647 using Server = RpcTransportTestUtils::Server;
1648 using Client = RpcTransportTestUtils::Client;
1649 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001650 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001651 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1652 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001653 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001654 return ret;
1655 }
1656 static std::vector<ParamType> getRpcTranportTestParams() {
1657 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001658 for (auto serverVersion : testVersions()) {
1659 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1660 for (auto rpcSecurity : RpcSecurityValues()) {
1661 switch (rpcSecurity) {
1662 case RpcSecurity::RAW: {
1663 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1664 } break;
1665 case RpcSecurity::TLS: {
1666 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1667 serverVersion);
1668 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1669 serverVersion);
1670 } break;
1671 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001672 }
1673 }
1674 }
1675 return ret;
1676 }
1677 template <typename A, typename B>
1678 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001679 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1680 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001681 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1682 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001683 void SetUp() override {
1684 if constexpr (!kEnableRpcThreads) {
1685 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1686 }
1687 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001688};
1689
1690TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001691 auto server = std::make_unique<Server>();
1692 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001693
1694 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001695 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001696
1697 ASSERT_EQ(OK, trust(&client, server));
1698 ASSERT_EQ(OK, trust(server, &client));
1699
1700 server->start();
1701 client.run();
1702}
1703
1704TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001705 auto server = std::make_unique<Server>();
1706 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001707
1708 std::vector<Client> clients;
1709 for (int i = 0; i < 2; i++) {
1710 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001711 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001712 ASSERT_EQ(OK, trust(&client, server));
1713 ASSERT_EQ(OK, trust(server, &client));
1714 }
1715
1716 server->start();
1717 for (auto& client : clients) client.run();
1718}
1719
1720TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001721 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1722 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001723
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001724 auto untrustedServer = std::make_unique<Server>();
1725 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001726
1727 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001728 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001729
1730 ASSERT_EQ(OK, trust(untrustedServer, &client));
1731
1732 untrustedServer->start();
1733
1734 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1735 // the client can't verify the server's identity.
1736 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1737 client.run(handshakeOk);
1738}
1739TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001740 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1741 (void)serverVersion;
1742
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001743 auto validServer = std::make_unique<Server>();
1744 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001745
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001746 auto maliciousServer = std::make_unique<Server>();
1747 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001748
1749 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001750 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001751
1752 ASSERT_EQ(OK, trust(&client, validServer));
1753 ASSERT_EQ(OK, trust(validServer, &client));
1754 ASSERT_EQ(OK, trust(maliciousServer, &client));
1755
1756 maliciousServer->start();
1757
1758 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1759 // the client can't verify the server's identity.
1760 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1761 client.run(handshakeOk);
1762}
1763
1764TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001765 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1766 (void)serverVersion;
1767
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001768 auto server = std::make_unique<Server>();
1769 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001770
1771 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001772 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001773
1774 ASSERT_EQ(OK, trust(&client, server));
1775
1776 server->start();
1777
1778 // For TLS, Client should be able to verify server's identity, so client should see
1779 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1780 // identity and should drop the connection, so client shouldn't be able to read anything.
1781 bool readOk = rpcSecurity != RpcSecurity::TLS;
1782 client.run(true, readOk);
1783}
1784
1785TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001786 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1787 (void)serverVersion;
1788
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001789 auto server = std::make_unique<Server>();
1790 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001791
1792 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001793 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001794 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001795 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001796
1797 ASSERT_EQ(OK, trust(&validClient, server));
1798 ASSERT_EQ(OK, trust(&maliciousClient, server));
1799
1800 server->start();
1801
1802 // See UntrustedClient.
1803 bool readOk = rpcSecurity != RpcSecurity::TLS;
1804 maliciousClient.run(true, readOk);
1805}
1806
Yifan Hong67519322021-09-13 18:51:16 -07001807TEST_P(RpcTransportTest, Trigger) {
1808 std::string msg2 = ", world!";
1809 std::mutex writeMutex;
1810 std::condition_variable writeCv;
1811 bool shouldContinueWriting = false;
1812 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001813 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001814 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001815 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1816 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001817 if (status != OK) return AssertionFailure() << statusToString(status);
1818
1819 {
1820 std::unique_lock<std::mutex> lock(writeMutex);
1821 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1822 return AssertionFailure() << "write barrier not cleared in time!";
1823 }
1824 }
1825
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001826 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001827 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1828 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001829 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001830 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001831 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001832 << statusToString(status);
1833 return AssertionSuccess();
1834 };
1835
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001836 auto server = std::make_unique<Server>();
1837 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001838
1839 // Set up client
1840 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001841 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001842
1843 // Exchange keys
1844 ASSERT_EQ(OK, trust(&client, server));
1845 ASSERT_EQ(OK, trust(server, &client));
1846
1847 server->setPostConnect(serverPostConnect);
1848
Yifan Hong67519322021-09-13 18:51:16 -07001849 server->start();
1850 // connect() to server and do handshake
1851 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001852 // read the first message. This ensures that server has finished handshake and start handling
1853 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001854 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001855 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1856 // write is on an FdTrigger that has been shut down.
1857 server->shutdown();
1858 // Continues server thread to write the second message.
1859 {
Yifan Hong22211f82021-09-14 12:32:25 -07001860 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001861 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001862 }
Yifan Hong22211f82021-09-14 12:32:25 -07001863 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001864 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001865 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001866 // On the client side, second read fails with DEAD_OBJECT
1867 ASSERT_FALSE(client.readMessage(msg2));
1868}
1869
Pawan49d74cb2022-08-03 21:19:11 +00001870TEST_P(RpcTransportTest, CheckWaitingForRead) {
1871 std::mutex readMutex;
1872 std::condition_variable readCv;
1873 bool shouldContinueReading = false;
1874 // Server will write data on transport once its started
1875 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1876 std::string message(RpcTransportTestUtils::kMessage);
1877 iovec messageIov{message.data(), message.size()};
1878 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1879 std::nullopt, nullptr);
1880 if (status != OK) return AssertionFailure() << statusToString(status);
1881
1882 {
1883 std::unique_lock<std::mutex> lock(readMutex);
1884 shouldContinueReading = true;
1885 lock.unlock();
1886 readCv.notify_all();
1887 }
1888 return AssertionSuccess();
1889 };
1890
1891 // Setup Server and client
1892 auto server = std::make_unique<Server>();
1893 ASSERT_TRUE(server->setUp(GetParam()));
1894
1895 Client client(server->getConnectToServerFn());
1896 ASSERT_TRUE(client.setUp(GetParam()));
1897
1898 ASSERT_EQ(OK, trust(&client, server));
1899 ASSERT_EQ(OK, trust(server, &client));
1900 server->setPostConnect(serverPostConnect);
1901
1902 server->start();
1903 ASSERT_TRUE(client.setUpTransport());
1904 {
1905 // Wait till server writes data
1906 std::unique_lock<std::mutex> lock(readMutex);
1907 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1908 }
1909
1910 // Since there is no read polling here, we will get polling count 0
1911 ASSERT_FALSE(client.isTransportWaiting());
1912 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1913 // Thread should increment polling count, read and decrement polling count
1914 // Again, polling count should be zero here
1915 ASSERT_FALSE(client.isTransportWaiting());
1916
1917 server->shutdown();
1918}
1919
Yifan Hong1deca4b2021-09-10 16:16:44 -07001920INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001921 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001922 RpcTransportTest::PrintParamInfo);
1923
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001924class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001925 : public testing::TestWithParam<
1926 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001927public:
1928 template <typename A, typename B>
1929 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001930 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1931 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001932 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1933 }
1934 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001935 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1936 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1937 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001938 };
1939};
1940
1941TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001942 if constexpr (!kEnableRpcThreads) {
1943 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1944 }
1945
Frederick Mayledc07cf82022-05-26 20:30:12 +00001946 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001947
1948 std::vector<uint8_t> pkeyData, certData;
1949 {
1950 auto pkey = makeKeyPairForSelfSignedCert();
1951 ASSERT_NE(nullptr, pkey);
1952 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1953 ASSERT_NE(nullptr, cert);
1954 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1955 certData = serializeCertificate(cert.get(), certificateFormat);
1956 }
1957
1958 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1959 auto desCert = deserializeCertificate(certData, certificateFormat);
1960 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001961 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1962 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001963
1964 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1965 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1966
1967 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1968 ASSERT_TRUE(client.setUp(utilsParam));
1969
1970 ASSERT_EQ(OK, trust(&client, server));
1971 ASSERT_EQ(OK, trust(server, &client));
1972
1973 server->start();
1974 client.run();
1975}
1976
1977INSTANTIATE_TEST_CASE_P(
1978 BinderRpc, RpcTransportTlsKeyTest,
1979 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1980 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001981 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1982 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001983 RpcTransportTlsKeyTest::PrintParamInfo);
1984
Steven Morelandc1635952021-04-01 16:20:47 +00001985} // namespace android
1986
1987int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001988 ::testing::InitGoogleTest(&argc, argv);
1989 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07001990
Steven Moreland5553ac42020-11-11 02:14:45 +00001991 return RUN_ALL_TESTS();
1992}