blob: 6e34d254bbcb1c77ba9a6073408e840c6b0ed486 [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);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000353 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000354 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
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000547 constexpr size_t kNumServerThreads = 3;
548
Frederick Mayleb0221d12022-10-03 23:10:53 +0000549 // This test forces a oneway transaction to be queued by issuing two
550 // `blockingSendFdOneway` calls, then drains the queue by issuing two
551 // `blockingRecvFd` calls.
552 //
553 // For more details about the queuing semantics see
554 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
555
556 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000557 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000558 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
559 .serverSupportedFileDescriptorTransportModes =
560 {RpcSession::FileDescriptorTransportMode::UNIX},
561 });
562
563 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
564 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
565 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
566 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
567
568 android::os::ParcelFileDescriptor fdA;
569 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
570 std::string result;
571 CHECK(android::base::ReadFdToString(fdA.get(), &result));
572 EXPECT_EQ(result, "a");
573
574 android::os::ParcelFileDescriptor fdB;
575 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
576 CHECK(android::base::ReadFdToString(fdB.get(), &result));
577 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000578
579 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000580}
581
Andrei Homescua858b0e2022-08-01 23:43:09 +0000582TEST_P(BinderRpc, OnewayCallQueueing) {
583 if (clientOrServerSingleThreaded()) {
584 GTEST_SKIP() << "This test requires multiple threads";
585 }
586
Steven Moreland5553ac42020-11-11 02:14:45 +0000587 constexpr size_t kNumSleeps = 10;
588 constexpr size_t kNumExtraServerThreads = 4;
589 constexpr size_t kSleepMs = 50;
590
591 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000592 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000593
594 EXPECT_OK(proc.rootIface->lock());
595
Steven Moreland1c678802021-09-17 16:48:47 -0700596 size_t epochMsBefore = epochMillis();
597
598 // all these *Async commands should be queued on the server sequentially,
599 // even though there are multiple threads.
600 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000601 proc.rootIface->sleepMsAsync(kSleepMs);
602 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000603 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
604
Steven Moreland1c678802021-09-17 16:48:47 -0700605 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000606 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700607
Steven Moreland5553ac42020-11-11 02:14:45 +0000608 size_t epochMsAfter = epochMillis();
609
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000610 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000611
Steven Moreland925ba0a2021-09-17 18:06:32 -0700612 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000613}
614
Andrei Homescua858b0e2022-08-01 23:43:09 +0000615TEST_P(BinderRpc, OnewayCallExhaustion) {
616 if (clientOrServerSingleThreaded()) {
617 GTEST_SKIP() << "This test requires multiple threads";
618 }
619
Steven Morelandd45be622021-06-04 02:19:37 +0000620 constexpr size_t kNumClients = 2;
621 constexpr size_t kTooLongMs = 1000;
622
Steven Moreland4313d7e2021-07-15 23:41:22 +0000623 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000624
625 // Build up oneway calls on the second session to make sure it terminates
626 // and shuts down. The first session should be unaffected (proc destructor
627 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000628 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000629
630 std::vector<std::thread> threads;
631 for (size_t i = 0; i < kNumClients; i++) {
632 // one of these threads will get stuck queueing a transaction once the
633 // socket fills up, the other will be able to fill up transactions on
634 // this object
635 threads.push_back(std::thread([&] {
636 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
637 }
638 }));
639 }
640 for (auto& t : threads) t.join();
641
642 Status status = iface->sleepMsAsync(kTooLongMs);
643 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
644
Steven Moreland798e0d12021-07-14 23:19:25 +0000645 // now that it has died, wait for the remote session to shutdown
646 std::vector<int32_t> remoteCounts;
647 do {
648 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
649 } while (remoteCounts.size() == kNumClients);
650
Steven Morelandd45be622021-06-04 02:19:37 +0000651 // the second session should be shutdown in the other process by the time we
652 // are able to join above (it'll only be hung up once it finishes processing
653 // any pending commands). We need to erase this session from the record
654 // here, so that the destructor for our session won't check that this
655 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000656 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000657}
658
Devin Moore66d5b7a2022-07-07 21:42:10 +0000659TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000660 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000661 GTEST_SKIP() << "This test requires multiple threads";
662 }
663 class MyDeathRec : public IBinder::DeathRecipient {
664 public:
665 void binderDied(const wp<IBinder>& /* who */) override {
666 dead = true;
667 mCv.notify_one();
668 }
669 std::mutex mMtx;
670 std::condition_variable mCv;
671 bool dead = false;
672 };
673
674 // Death recipient needs to have an incoming connection to be called
675 auto proc = createRpcTestSocketServerProcess(
676 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
677
678 auto dr = sp<MyDeathRec>::make();
679 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
680
681 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
682 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
683 }
684
685 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000686 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000687
688 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000689 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000690 proc.expectAlreadyShutdown = true;
691}
692
693TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000694 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000695 GTEST_SKIP() << "This test requires multiple threads";
696 }
697 class MyDeathRec : public IBinder::DeathRecipient {
698 public:
699 void binderDied(const wp<IBinder>& /* who */) override {
700 dead = true;
701 mCv.notify_one();
702 }
703 std::mutex mMtx;
704 std::condition_variable mCv;
705 bool dead = false;
706 };
707
708 // Death recipient needs to have an incoming connection to be called
709 auto proc = createRpcTestSocketServerProcess(
710 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
711
712 auto dr = sp<MyDeathRec>::make();
713 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
714
715 // Explicitly calling shutDownAndWait will cause the death recipients
716 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000717 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000718
719 std::unique_lock<std::mutex> lock(dr->mMtx);
720 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000721 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000722 }
723 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
724
Andrei Homescu96834632022-10-14 00:49:49 +0000725 proc.proc->terminate();
726 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000727 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
728 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
729 });
730 proc.expectAlreadyShutdown = true;
731}
732
Steven Moreland5ec743f2023-01-18 01:02:06 +0000733TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000734 if (socketType() == SocketType::TIPC) {
735 // This should work, but Trusty takes too long to restart the service
736 GTEST_SKIP() << "Service death test not supported on Trusty";
737 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000738 class MyDeathRec : public IBinder::DeathRecipient {
739 public:
740 void binderDied(const wp<IBinder>& /* who */) override {}
741 };
742
743 auto proc = createRpcTestSocketServerProcess(
744 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
745
746 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000747 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000748}
749
750TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000751 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000752 GTEST_SKIP() << "This test requires multiple threads";
753 }
754 class MyDeathRec : public IBinder::DeathRecipient {
755 public:
756 void binderDied(const wp<IBinder>& /* who */) override {
757 GTEST_FAIL() << "This should not be called after unlinkToDeath";
758 }
759 };
760
761 // Death recipient needs to have an incoming connection to be called
762 auto proc = createRpcTestSocketServerProcess(
763 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
764
765 auto dr = sp<MyDeathRec>::make();
766 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
767 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
768
769 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
770 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
771 }
772
773 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000774 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000775 proc.expectAlreadyShutdown = true;
776}
777
Steven Morelandc1635952021-04-01 16:20:47 +0000778TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000779 if (socketType() == SocketType::TIPC) {
780 // This should work, but Trusty takes too long to restart the service
781 GTEST_SKIP() << "Service death test not supported on Trusty";
782 }
783
Steven Moreland5553ac42020-11-11 02:14:45 +0000784 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000785 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000786
787 // make sure there is some state during crash
788 // 1. we hold their binder
789 sp<IBinderRpcSession> session;
790 EXPECT_OK(proc.rootIface->openSession("happy", &session));
791 // 2. they hold our binder
792 sp<IBinder> binder = new BBinder();
793 EXPECT_OK(proc.rootIface->holdBinder(binder));
794
795 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
796 << "Do death cleanup: " << doDeathCleanup;
797
Andrei Homescu96834632022-10-14 00:49:49 +0000798 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000799 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
800 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
801 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000802 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000803 }
804}
805
Steven Morelandd7302072021-05-15 01:32:04 +0000806TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000807 // This test only works if the current process shared the internal state of
808 // ProcessState with the service across the call to fork(). Both the static
809 // libraries and libbinder.so have their own separate copies of all the
810 // globals, so the test only works when the test client and service both use
811 // libbinder.so (when using static libraries, even a client and service
812 // using the same kind of static library should have separate copies of the
813 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000814 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000815 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
816 "at build time.";
817 }
818
Steven Moreland4313d7e2021-07-15 23:41:22 +0000819 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000820
Andrei Homescu2a298012022-06-15 01:08:54 +0000821 // we can't allocate IPCThreadState so actually the first time should
822 // succeed :(
823 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000824
825 // second time! we catch the error :)
826 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
827
Andrei Homescu96834632022-10-14 00:49:49 +0000828 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000829 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
830 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
831 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000832 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000833}
834
Frederick Mayle69a0c992022-05-26 20:38:39 +0000835TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000836 if (socketType() == SocketType::TIPC) {
837 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
838 }
839
Frederick Mayle69a0c992022-05-26 20:38:39 +0000840 auto proc = createRpcTestSocketServerProcess({
841 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
842 .serverSupportedFileDescriptorTransportModes =
843 {RpcSession::FileDescriptorTransportMode::UNIX},
844 .allowConnectFailure = true,
845 });
Andrei Homescu96834632022-10-14 00:49:49 +0000846 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
847 proc.proc->terminate();
848 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000849 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
850 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
851 });
852 proc.expectAlreadyShutdown = true;
853}
854
855TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000856 if (socketType() == SocketType::TIPC) {
857 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
858 }
859
Frederick Mayle69a0c992022-05-26 20:38:39 +0000860 auto proc = createRpcTestSocketServerProcess({
861 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
862 .serverSupportedFileDescriptorTransportModes =
863 {RpcSession::FileDescriptorTransportMode::NONE},
864 .allowConnectFailure = true,
865 });
Andrei Homescu96834632022-10-14 00:49:49 +0000866 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
867 proc.proc->terminate();
868 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000869 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
870 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
871 });
872 proc.expectAlreadyShutdown = true;
873}
874
875TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000876 if (socketType() == SocketType::TIPC) {
877 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
878 }
879
Frederick Mayle69a0c992022-05-26 20:38:39 +0000880 auto proc = createRpcTestSocketServerProcess({
881 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
882 .serverSupportedFileDescriptorTransportModes =
883 {RpcSession::FileDescriptorTransportMode::NONE,
884 RpcSession::FileDescriptorTransportMode::UNIX},
885 });
886
887 android::os::ParcelFileDescriptor out;
888 auto status = proc.rootIface->echoAsFile("hello", &out);
889 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
890}
891
892TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000893 if (socketType() == SocketType::TIPC) {
894 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
895 }
896
Frederick Mayle69a0c992022-05-26 20:38:39 +0000897 auto proc = createRpcTestSocketServerProcess({
898 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
899 .serverSupportedFileDescriptorTransportModes =
900 {RpcSession::FileDescriptorTransportMode::UNIX},
901 });
902
903 android::os::ParcelFileDescriptor out;
904 auto status = proc.rootIface->echoAsFile("hello", &out);
905 if (!supportsFdTransport()) {
906 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
907 return;
908 }
909 ASSERT_TRUE(status.isOk()) << status;
910
911 std::string result;
912 CHECK(android::base::ReadFdToString(out.get(), &result));
913 EXPECT_EQ(result, "hello");
914}
915
916TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000917 if (socketType() == SocketType::TIPC) {
918 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
919 }
920
Frederick Mayle69a0c992022-05-26 20:38:39 +0000921 auto proc = createRpcTestSocketServerProcess({
922 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
923 .serverSupportedFileDescriptorTransportModes =
924 {RpcSession::FileDescriptorTransportMode::UNIX},
925 });
926
927 std::vector<android::os::ParcelFileDescriptor> files;
928 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
929 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
930 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
931 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
932
933 android::os::ParcelFileDescriptor out;
934 auto status = proc.rootIface->concatFiles(files, &out);
935 if (!supportsFdTransport()) {
936 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
937 return;
938 }
939 ASSERT_TRUE(status.isOk()) << status;
940
941 std::string result;
942 CHECK(android::base::ReadFdToString(out.get(), &result));
943 EXPECT_EQ(result, "123abcd");
944}
945
946TEST_P(BinderRpc, SendMaxFiles) {
947 if (!supportsFdTransport()) {
948 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
949 }
950
951 auto proc = createRpcTestSocketServerProcess({
952 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
953 .serverSupportedFileDescriptorTransportModes =
954 {RpcSession::FileDescriptorTransportMode::UNIX},
955 });
956
957 std::vector<android::os::ParcelFileDescriptor> files;
958 for (int i = 0; i < 253; i++) {
959 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
960 }
961
962 android::os::ParcelFileDescriptor out;
963 auto status = proc.rootIface->concatFiles(files, &out);
964 ASSERT_TRUE(status.isOk()) << status;
965
966 std::string result;
967 CHECK(android::base::ReadFdToString(out.get(), &result));
968 EXPECT_EQ(result, std::string(253, 'a'));
969}
970
971TEST_P(BinderRpc, SendTooManyFiles) {
972 if (!supportsFdTransport()) {
973 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
974 }
975
976 auto proc = createRpcTestSocketServerProcess({
977 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
978 .serverSupportedFileDescriptorTransportModes =
979 {RpcSession::FileDescriptorTransportMode::UNIX},
980 });
981
982 std::vector<android::os::ParcelFileDescriptor> files;
983 for (int i = 0; i < 254; i++) {
984 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
985 }
986
987 android::os::ParcelFileDescriptor out;
988 auto status = proc.rootIface->concatFiles(files, &out);
989 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
990}
991
Andrei Homescufc221502022-10-08 03:51:17 +0000992TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000993 if (socketType() == SocketType::TIPC) {
994 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
995 }
996
Andrei Homescufc221502022-10-08 03:51:17 +0000997 auto proc = createRpcTestSocketServerProcess({
998 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
999 .serverSupportedFileDescriptorTransportModes =
1000 {RpcSession::FileDescriptorTransportMode::UNIX},
1001 });
1002
1003 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1004 ASSERT_NE(badFd, -1);
1005
1006 // Close the file descriptor so it becomes invalid for dup
1007 close(badFd);
1008
1009 Parcel p1;
1010 p1.markForBinder(proc.rootBinder);
1011 p1.writeInt32(3);
1012 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1013
1014 Parcel pRaw;
1015 pRaw.markForBinder(proc.rootBinder);
1016 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1017
1018 pRaw.setDataPosition(0);
1019 EXPECT_EQ(3, pRaw.readInt32());
1020 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1021}
1022
Andrei Homescu68a55612022-08-02 01:25:15 +00001023#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001024TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001025 if constexpr (!kEnableSharedLibs) {
1026 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1027 }
1028
Steven Moreland4313d7e2021-07-15 23:41:22 +00001029 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001030
1031 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1032 ASSERT_NE(binder, nullptr);
1033
1034 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1035}
1036
1037TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001038 if constexpr (!kEnableSharedLibs) {
1039 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1040 }
1041
Steven Moreland4313d7e2021-07-15 23:41:22 +00001042 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001043
1044 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1045 ASSERT_NE(binder, nullptr);
1046
1047 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1048 ASSERT_NE(ndkBinder, nullptr);
1049
1050 std::string out;
1051 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1052 ASSERT_TRUE(status.isOk()) << status.getDescription();
1053 ASSERT_EQ("aoeuaoeu", out);
1054}
Andrei Homescu68a55612022-08-02 01:25:15 +00001055#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001056
Steven Moreland5553ac42020-11-11 02:14:45 +00001057ssize_t countFds() {
1058 DIR* dir = opendir("/proc/self/fd/");
1059 if (dir == nullptr) return -1;
1060 ssize_t ret = 0;
1061 dirent* ent;
1062 while ((ent = readdir(dir)) != nullptr) ret++;
1063 closedir(dir);
1064 return ret;
1065}
1066
Andrei Homescua858b0e2022-08-01 23:43:09 +00001067TEST_P(BinderRpc, Fds) {
1068 if (serverSingleThreaded()) {
1069 GTEST_SKIP() << "This test requires multiple threads";
1070 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001071 if (socketType() == SocketType::TIPC) {
1072 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1073 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001074
Steven Moreland5553ac42020-11-11 02:14:45 +00001075 ssize_t beforeFds = countFds();
1076 ASSERT_GE(beforeFds, 0);
1077 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001078 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001079 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1080 }
1081 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1082}
1083
Steven Morelandda573042021-06-12 01:13:45 +00001084static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001085 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001086 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001087
Andrei Homescu992a4052022-06-28 21:26:18 +00001088 android::base::unique_fd serverFd(
1089 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1090 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1091
1092 sockaddr_vm serverAddr{
1093 .svm_family = AF_VSOCK,
1094 .svm_port = vsockPort,
1095 .svm_cid = VMADDR_CID_ANY,
1096 };
1097 int ret = TEMP_FAILURE_RETRY(
1098 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1099 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1100 strerror(errno));
1101
1102 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1103 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1104 strerror(errno));
1105
1106 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1107 // to see if the kernel supports it. It's safe to use a blocking
1108 // connect because vsock sockets have a 2 second connection timeout,
1109 // and they return ETIMEDOUT after that.
1110 android::base::unique_fd connectFd(
1111 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1112 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1113 strerror(errno));
1114
1115 bool success = false;
1116 sockaddr_vm connectAddr{
1117 .svm_family = AF_VSOCK,
1118 .svm_port = vsockPort,
1119 .svm_cid = VMADDR_CID_LOCAL,
1120 };
1121 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1122 sizeof(connectAddr)));
1123 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1124 android::base::unique_fd acceptFd;
1125 while (true) {
1126 pollfd pfd[]{
1127 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1128 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1129 };
1130 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1131 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1132
1133 if (pfd[0].revents & POLLIN) {
1134 sockaddr_vm acceptAddr;
1135 socklen_t acceptAddrLen = sizeof(acceptAddr);
1136 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1137 reinterpret_cast<sockaddr*>(&acceptAddr),
1138 &acceptAddrLen, SOCK_CLOEXEC));
1139 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1140 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1141 "Truncated address");
1142
1143 // Store the fd in acceptFd so we keep the connection alive
1144 // while polling connectFd
1145 acceptFd.reset(ret);
1146 }
1147
1148 if (pfd[1].revents & POLLOUT) {
1149 // Connect either succeeded or timed out
1150 int connectErrno;
1151 socklen_t connectErrnoLen = sizeof(connectErrno);
1152 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1153 &connectErrnoLen);
1154 LOG_ALWAYS_FATAL_IF(ret == -1,
1155 "Could not getsockopt() after connect() "
1156 "on non-blocking socket: %s.",
1157 strerror(errno));
1158
1159 // We're done, this is all we wanted
1160 success = connectErrno == 0;
1161 break;
1162 }
1163 }
1164 } else {
1165 success = ret == 0;
1166 }
1167
1168 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1169
1170 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001171}
1172
Yifan Hong1deca4b2021-09-10 16:16:44 -07001173static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001174 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1175 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001176
1177 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001178
1179 static bool hasVsockLoopback = testSupportVsockLoopback();
1180
1181 if (hasVsockLoopback) {
1182 ret.push_back(SocketType::VSOCK);
1183 }
1184
1185 return ret;
1186}
1187
Andrei Homescu68a55612022-08-02 01:25:15 +00001188static std::vector<SocketType> testTipcSocketTypes() {
1189#ifdef __ANDROID_VENDOR__
1190 auto port = trustyIpcPort(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1191 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
1192 if (tipcFd >= 0) {
1193 close(tipcFd);
1194 return {SocketType::TIPC};
1195 }
1196#endif // __ANDROID_VENDOR__
1197
1198 // TIPC is not supported on this device, most likely
1199 // because /dev/trusty-ipc-dev0 is missing
1200 return {};
1201}
1202
Yifan Hong702115c2021-06-24 15:39:18 -07001203INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1204 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001205 ::testing::ValuesIn(RpcSecurityValues()),
1206 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001207 ::testing::ValuesIn(testVersions()),
1208 ::testing::Values(false, true),
1209 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001210 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001211
Andrei Homescu68a55612022-08-02 01:25:15 +00001212INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc,
1213 ::testing::Combine(::testing::ValuesIn(testTipcSocketTypes()),
1214 ::testing::Values(RpcSecurity::RAW),
1215 ::testing::ValuesIn(testVersions()),
1216 ::testing::ValuesIn(testVersions()),
1217 ::testing::Values(true), ::testing::Values(true)),
1218 BinderRpc::PrintParamInfo);
1219
Yifan Hong702115c2021-06-24 15:39:18 -07001220class BinderRpcServerRootObject
1221 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001222
1223TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1224 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1225 auto setRootObject = [](bool isStrong) -> SetFn {
1226 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1227 };
1228
Yifan Hong702115c2021-06-24 15:39:18 -07001229 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1230 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001231 auto binder1 = sp<BBinder>::make();
1232 IBinder* binderRaw1 = binder1.get();
1233 setRootObject(isStrong1)(server.get(), binder1);
1234 EXPECT_EQ(binderRaw1, server->getRootObject());
1235 binder1.clear();
1236 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1237
1238 auto binder2 = sp<BBinder>::make();
1239 IBinder* binderRaw2 = binder2.get();
1240 setRootObject(isStrong2)(server.get(), binder2);
1241 EXPECT_EQ(binderRaw2, server->getRootObject());
1242 binder2.clear();
1243 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1244}
1245
1246INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001247 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1248 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001249
Yifan Hong1a235852021-05-13 16:07:47 -07001250class OneOffSignal {
1251public:
1252 // If notify() was previously called, or is called within |duration|, return true; else false.
1253 template <typename R, typename P>
1254 bool wait(std::chrono::duration<R, P> duration) {
1255 std::unique_lock<std::mutex> lock(mMutex);
1256 return mCv.wait_for(lock, duration, [this] { return mValue; });
1257 }
1258 void notify() {
1259 std::unique_lock<std::mutex> lock(mMutex);
1260 mValue = true;
1261 lock.unlock();
1262 mCv.notify_all();
1263 }
1264
1265private:
1266 std::mutex mMutex;
1267 std::condition_variable mCv;
1268 bool mValue = false;
1269};
1270
Yifan Hong194acf22021-06-29 18:44:56 -07001271TEST(BinderRpc, Java) {
1272#if !defined(__ANDROID__)
1273 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1274 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1275 "to binderHostDeviceTest. Hence, just disable this test on host.";
1276#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001277 if constexpr (!kEnableKernelIpc) {
1278 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1279 "at build time.";
1280 }
1281
Yifan Hong194acf22021-06-29 18:44:56 -07001282 sp<IServiceManager> sm = defaultServiceManager();
1283 ASSERT_NE(nullptr, sm);
1284 // Any Java service with non-empty getInterfaceDescriptor() would do.
1285 // Let's pick batteryproperties.
1286 auto binder = sm->checkService(String16("batteryproperties"));
1287 ASSERT_NE(nullptr, binder);
1288 auto descriptor = binder->getInterfaceDescriptor();
1289 ASSERT_GE(descriptor.size(), 0);
1290 ASSERT_EQ(OK, binder->pingBinder());
1291
1292 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001293 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001294 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001295 auto socket = rpcServer->releaseServer();
1296
1297 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001298 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1299
Yifan Honge3caaf22022-01-12 14:46:56 -08001300 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1301 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001302 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001303 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1304 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001305 << statusToString(setRpcClientDebugStatus);
1306 GTEST_SKIP();
1307 }
1308
1309 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001310
1311 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001312 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001313 auto rpcBinder = rpcSession->getRootObject();
1314 ASSERT_NE(nullptr, rpcBinder);
1315
1316 ASSERT_EQ(OK, rpcBinder->pingBinder());
1317
1318 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1319 << "getInterfaceDescriptor should not crash system_server";
1320 ASSERT_EQ(OK, rpcBinder->pingBinder());
1321}
1322
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001323class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1324public:
1325 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1326 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1327 std::to_string(std::get<1>(info.param));
1328 }
1329};
1330
1331TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1332 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1333 int sinkFd = sink.get();
1334 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1335 server->setProtocolVersion(std::get<1>(GetParam()));
1336 ASSERT_FALSE(server->hasServer());
1337 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1338 ASSERT_TRUE(server->hasServer());
1339 base::unique_fd retrieved = server->releaseServer();
1340 ASSERT_FALSE(server->hasServer());
1341 ASSERT_EQ(sinkFd, retrieved.get());
1342}
1343
1344TEST_P(BinderRpcServerOnly, Shutdown) {
1345 if constexpr (!kEnableRpcThreads) {
1346 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1347 }
1348
1349 auto addr = allocateSocketAddress();
1350 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1351 server->setProtocolVersion(std::get<1>(GetParam()));
1352 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1353 auto joinEnds = std::make_shared<OneOffSignal>();
1354
1355 // If things are broken and the thread never stops, don't block other tests. Because the thread
1356 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1357 // shared pointers are passed.
1358 std::thread([server, joinEnds] {
1359 server->join();
1360 joinEnds->notify();
1361 }).detach();
1362
1363 bool shutdown = false;
1364 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001365 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001366 if (server->shutdown()) shutdown = true;
1367 }
1368 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1369
1370 ASSERT_TRUE(joinEnds->wait(2s))
1371 << "After server->shutdown() returns true, join() did not stop after 2s";
1372}
1373
Frederick Mayledc07cf82022-05-26 20:30:12 +00001374INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1375 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1376 ::testing::ValuesIn(testVersions())),
1377 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001378
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001379class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001380public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001381 // Only parameterized only server version because `RpcSession` is bypassed
1382 // in the client half of the tests.
1383 using Param =
1384 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001385 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001386
1387 // A server that handles client socket connections.
1388 class Server {
1389 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001390 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1391
Yifan Hong1deca4b2021-09-10 16:16:44 -07001392 explicit Server() {}
1393 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001394 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001395 [[nodiscard]] AssertionResult setUp(
1396 const Param& param,
1397 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001398 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001399 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001400 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001401 switch (socketType) {
1402 case SocketType::PRECONNECTED: {
1403 return AssertionFailure() << "Not supported by this test";
1404 } break;
1405 case SocketType::UNIX: {
1406 auto addr = allocateSocketAddress();
1407 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1408 if (status != OK) {
1409 return AssertionFailure()
1410 << "setupUnixDomainServer: " << statusToString(status);
1411 }
1412 mConnectToServer = [addr] {
1413 return connectTo(UnixSocketAddress(addr.c_str()));
1414 };
1415 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001416 case SocketType::UNIX_BOOTSTRAP: {
1417 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1418 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1419 return AssertionFailure() << "Socketpair() failed";
1420 }
1421 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1422 std::move(bootstrapFdServer));
1423 if (status != OK) {
1424 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1425 << statusToString(status);
1426 }
1427 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1428 mAcceptConnection = &Server::recvmsgServerConnection;
1429 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1430 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001431 case SocketType::UNIX_RAW: {
1432 auto addr = allocateSocketAddress();
1433 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1434 if (status != OK) {
1435 return AssertionFailure()
1436 << "setupRawSocketServer: " << statusToString(status);
1437 }
1438 mConnectToServer = [addr] {
1439 return connectTo(UnixSocketAddress(addr.c_str()));
1440 };
1441 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001442 case SocketType::VSOCK: {
1443 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001444 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001445 if (status != OK) {
1446 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1447 }
1448 mConnectToServer = [port] {
1449 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1450 };
1451 } break;
1452 case SocketType::INET: {
1453 unsigned int port;
1454 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1455 if (status != OK) {
1456 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1457 }
1458 mConnectToServer = [port] {
1459 const char* addr = kLocalInetAddress;
1460 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1461 if (aiStart == nullptr) return base::unique_fd{};
1462 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1463 auto fd = connectTo(
1464 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1465 if (fd.ok()) return fd;
1466 }
1467 ALOGE("None of the socket address resolved for %s:%u can be connected",
1468 addr, port);
1469 return base::unique_fd{};
1470 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001471 } break;
1472 case SocketType::TIPC: {
1473 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1474 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001475 }
1476 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001477 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001478 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001479 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1480 mSetup = true;
1481 return AssertionSuccess();
1482 }
1483 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1484 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1485 return mCertVerifier;
1486 }
1487 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1488 void start() {
1489 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1490 mThread = std::make_unique<std::thread>(&Server::run, this);
1491 }
David Brazdil21c887c2022-09-23 12:25:18 +01001492
1493 base::unique_fd acceptServerConnection() {
1494 return base::unique_fd(TEMP_FAILURE_RETRY(
1495 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1496 }
1497
1498 base::unique_fd recvmsgServerConnection() {
1499 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1500 int buf;
1501 iovec iov{&buf, sizeof(buf)};
1502
1503 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1504 int savedErrno = errno;
1505 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1506 }
1507 if (fds.size() != 1) {
1508 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1509 }
1510 return std::move(std::get<base::unique_fd>(fds[0]));
1511 }
1512
Yifan Hong1deca4b2021-09-10 16:16:44 -07001513 void run() {
1514 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1515
1516 std::vector<std::thread> threads;
1517 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001518 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001519 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1520 }
1521
1522 for (auto& thread : threads) thread.join();
1523 }
1524 void handleOne(android::base::unique_fd acceptedFd) {
1525 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001526 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001527 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001528 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001529 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001530 }
Yifan Honge07d2732021-09-13 21:59:14 -07001531 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001532 shutdown();
1533 join();
1534 }
1535 void shutdown() { mFdTrigger->trigger(); }
1536
1537 void setPostConnect(
1538 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1539 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001540 }
1541
1542 private:
1543 std::unique_ptr<std::thread> mThread;
1544 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001545 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001546 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001547 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001548 std::unique_ptr<RpcTransportCtx> mCtx;
1549 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1550 std::make_shared<RpcCertificateVerifierSimple>();
1551 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001552 // The function invoked after connection and handshake. By default, it is
1553 // |defaultPostConnect| that sends |kMessage| to the client.
1554 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1555 Server::defaultPostConnect;
1556
1557 void join() {
1558 if (mThread != nullptr) {
1559 mThread->join();
1560 mThread = nullptr;
1561 }
1562 }
1563
1564 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1565 FdTrigger* fdTrigger) {
1566 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001567 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001568 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001569 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001570 if (status != OK) return AssertionFailure() << statusToString(status);
1571 return AssertionSuccess();
1572 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001573 };
1574
1575 class Client {
1576 public:
1577 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1578 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001579 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001580 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1581 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001582 mFdTrigger = FdTrigger::make();
1583 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1584 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1585 return AssertionSuccess();
1586 }
1587 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1588 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1589 return mCertVerifier;
1590 }
Yifan Hong67519322021-09-13 18:51:16 -07001591 // connect() and do handshake
1592 bool setUpTransport() {
1593 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001594 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001595 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1596 return mClientTransport != nullptr;
1597 }
1598 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1599 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1600 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001601 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001602 status_t readStatus =
1603 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001604 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001605 if (readStatus != OK) {
1606 return AssertionFailure() << statusToString(readStatus);
1607 }
1608 if (readMessage != expectedMessage) {
1609 return AssertionFailure()
1610 << "Expected " << expectedMessage << ", actual " << readMessage;
1611 }
1612 return AssertionSuccess();
1613 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001614 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001615 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001616 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1617 return;
1618 }
1619 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001620 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001621 }
1622
Pawan49d74cb2022-08-03 21:19:11 +00001623 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1624
Yifan Hong1deca4b2021-09-10 16:16:44 -07001625 private:
1626 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001627 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001628 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1629 std::unique_ptr<RpcTransportCtx> mCtx;
1630 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1631 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001632 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001633 };
1634
1635 // Make A trust B.
1636 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001637 static status_t trust(RpcSecurity rpcSecurity,
1638 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1639 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001640 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001641 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1642 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1643 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001644 }
1645
1646 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001647};
1648
1649class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1650public:
1651 using Server = RpcTransportTestUtils::Server;
1652 using Client = RpcTransportTestUtils::Client;
1653 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001654 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001655 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1656 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001657 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001658 return ret;
1659 }
1660 static std::vector<ParamType> getRpcTranportTestParams() {
1661 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001662 for (auto serverVersion : testVersions()) {
1663 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1664 for (auto rpcSecurity : RpcSecurityValues()) {
1665 switch (rpcSecurity) {
1666 case RpcSecurity::RAW: {
1667 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1668 } break;
1669 case RpcSecurity::TLS: {
1670 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1671 serverVersion);
1672 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1673 serverVersion);
1674 } break;
1675 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001676 }
1677 }
1678 }
1679 return ret;
1680 }
1681 template <typename A, typename B>
1682 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001683 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1684 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001685 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1686 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001687 void SetUp() override {
1688 if constexpr (!kEnableRpcThreads) {
1689 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1690 }
1691 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001692};
1693
1694TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001695 auto server = std::make_unique<Server>();
1696 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001697
1698 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001699 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001700
1701 ASSERT_EQ(OK, trust(&client, server));
1702 ASSERT_EQ(OK, trust(server, &client));
1703
1704 server->start();
1705 client.run();
1706}
1707
1708TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001709 auto server = std::make_unique<Server>();
1710 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001711
1712 std::vector<Client> clients;
1713 for (int i = 0; i < 2; i++) {
1714 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001715 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001716 ASSERT_EQ(OK, trust(&client, server));
1717 ASSERT_EQ(OK, trust(server, &client));
1718 }
1719
1720 server->start();
1721 for (auto& client : clients) client.run();
1722}
1723
1724TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001725 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1726 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001727
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001728 auto untrustedServer = std::make_unique<Server>();
1729 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001730
1731 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001732 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001733
1734 ASSERT_EQ(OK, trust(untrustedServer, &client));
1735
1736 untrustedServer->start();
1737
1738 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1739 // the client can't verify the server's identity.
1740 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1741 client.run(handshakeOk);
1742}
1743TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001744 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1745 (void)serverVersion;
1746
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001747 auto validServer = std::make_unique<Server>();
1748 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001749
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001750 auto maliciousServer = std::make_unique<Server>();
1751 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001752
1753 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001754 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001755
1756 ASSERT_EQ(OK, trust(&client, validServer));
1757 ASSERT_EQ(OK, trust(validServer, &client));
1758 ASSERT_EQ(OK, trust(maliciousServer, &client));
1759
1760 maliciousServer->start();
1761
1762 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1763 // the client can't verify the server's identity.
1764 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1765 client.run(handshakeOk);
1766}
1767
1768TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001769 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1770 (void)serverVersion;
1771
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001772 auto server = std::make_unique<Server>();
1773 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001774
1775 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001776 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001777
1778 ASSERT_EQ(OK, trust(&client, server));
1779
1780 server->start();
1781
1782 // For TLS, Client should be able to verify server's identity, so client should see
1783 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1784 // identity and should drop the connection, so client shouldn't be able to read anything.
1785 bool readOk = rpcSecurity != RpcSecurity::TLS;
1786 client.run(true, readOk);
1787}
1788
1789TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001790 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1791 (void)serverVersion;
1792
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001793 auto server = std::make_unique<Server>();
1794 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001795
1796 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001797 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001798 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001799 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001800
1801 ASSERT_EQ(OK, trust(&validClient, server));
1802 ASSERT_EQ(OK, trust(&maliciousClient, server));
1803
1804 server->start();
1805
1806 // See UntrustedClient.
1807 bool readOk = rpcSecurity != RpcSecurity::TLS;
1808 maliciousClient.run(true, readOk);
1809}
1810
Yifan Hong67519322021-09-13 18:51:16 -07001811TEST_P(RpcTransportTest, Trigger) {
1812 std::string msg2 = ", world!";
1813 std::mutex writeMutex;
1814 std::condition_variable writeCv;
1815 bool shouldContinueWriting = false;
1816 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001817 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001818 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001819 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1820 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001821 if (status != OK) return AssertionFailure() << statusToString(status);
1822
1823 {
1824 std::unique_lock<std::mutex> lock(writeMutex);
1825 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1826 return AssertionFailure() << "write barrier not cleared in time!";
1827 }
1828 }
1829
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001830 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001831 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1832 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001833 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001834 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001835 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001836 << statusToString(status);
1837 return AssertionSuccess();
1838 };
1839
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001840 auto server = std::make_unique<Server>();
1841 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001842
1843 // Set up client
1844 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001845 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001846
1847 // Exchange keys
1848 ASSERT_EQ(OK, trust(&client, server));
1849 ASSERT_EQ(OK, trust(server, &client));
1850
1851 server->setPostConnect(serverPostConnect);
1852
Yifan Hong67519322021-09-13 18:51:16 -07001853 server->start();
1854 // connect() to server and do handshake
1855 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001856 // read the first message. This ensures that server has finished handshake and start handling
1857 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001858 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001859 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1860 // write is on an FdTrigger that has been shut down.
1861 server->shutdown();
1862 // Continues server thread to write the second message.
1863 {
Yifan Hong22211f82021-09-14 12:32:25 -07001864 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001865 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001866 }
Yifan Hong22211f82021-09-14 12:32:25 -07001867 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001868 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001869 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001870 // On the client side, second read fails with DEAD_OBJECT
1871 ASSERT_FALSE(client.readMessage(msg2));
1872}
1873
Pawan49d74cb2022-08-03 21:19:11 +00001874TEST_P(RpcTransportTest, CheckWaitingForRead) {
1875 std::mutex readMutex;
1876 std::condition_variable readCv;
1877 bool shouldContinueReading = false;
1878 // Server will write data on transport once its started
1879 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1880 std::string message(RpcTransportTestUtils::kMessage);
1881 iovec messageIov{message.data(), message.size()};
1882 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1883 std::nullopt, nullptr);
1884 if (status != OK) return AssertionFailure() << statusToString(status);
1885
1886 {
1887 std::unique_lock<std::mutex> lock(readMutex);
1888 shouldContinueReading = true;
1889 lock.unlock();
1890 readCv.notify_all();
1891 }
1892 return AssertionSuccess();
1893 };
1894
1895 // Setup Server and client
1896 auto server = std::make_unique<Server>();
1897 ASSERT_TRUE(server->setUp(GetParam()));
1898
1899 Client client(server->getConnectToServerFn());
1900 ASSERT_TRUE(client.setUp(GetParam()));
1901
1902 ASSERT_EQ(OK, trust(&client, server));
1903 ASSERT_EQ(OK, trust(server, &client));
1904 server->setPostConnect(serverPostConnect);
1905
1906 server->start();
1907 ASSERT_TRUE(client.setUpTransport());
1908 {
1909 // Wait till server writes data
1910 std::unique_lock<std::mutex> lock(readMutex);
1911 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1912 }
1913
1914 // Since there is no read polling here, we will get polling count 0
1915 ASSERT_FALSE(client.isTransportWaiting());
1916 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1917 // Thread should increment polling count, read and decrement polling count
1918 // Again, polling count should be zero here
1919 ASSERT_FALSE(client.isTransportWaiting());
1920
1921 server->shutdown();
1922}
1923
Yifan Hong1deca4b2021-09-10 16:16:44 -07001924INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001925 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001926 RpcTransportTest::PrintParamInfo);
1927
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001928class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001929 : public testing::TestWithParam<
1930 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001931public:
1932 template <typename A, typename B>
1933 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001934 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1935 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001936 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1937 }
1938 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001939 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1940 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1941 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001942 };
1943};
1944
1945TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001946 if constexpr (!kEnableRpcThreads) {
1947 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1948 }
1949
Frederick Mayledc07cf82022-05-26 20:30:12 +00001950 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001951
1952 std::vector<uint8_t> pkeyData, certData;
1953 {
1954 auto pkey = makeKeyPairForSelfSignedCert();
1955 ASSERT_NE(nullptr, pkey);
1956 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1957 ASSERT_NE(nullptr, cert);
1958 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1959 certData = serializeCertificate(cert.get(), certificateFormat);
1960 }
1961
1962 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1963 auto desCert = deserializeCertificate(certData, certificateFormat);
1964 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001965 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1966 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001967
1968 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1969 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1970
1971 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1972 ASSERT_TRUE(client.setUp(utilsParam));
1973
1974 ASSERT_EQ(OK, trust(&client, server));
1975 ASSERT_EQ(OK, trust(server, &client));
1976
1977 server->start();
1978 client.run();
1979}
1980
1981INSTANTIATE_TEST_CASE_P(
1982 BinderRpc, RpcTransportTlsKeyTest,
1983 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1984 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001985 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1986 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001987 RpcTransportTlsKeyTest::PrintParamInfo);
1988
Steven Morelandc1635952021-04-01 16:20:47 +00001989} // namespace android
1990
1991int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001992 ::testing::InitGoogleTest(&argc, argv);
1993 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07001994
Steven Moreland5553ac42020-11-11 02:14:45 +00001995 return RUN_ALL_TESTS();
1996}