blob: d9e5b9aae2b968267c07879d03271c6092bbe6bf [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andrei Homescu9d8adb12022-08-02 04:38:30 +000017#include <aidl/IBinderRpcTest.h>
Frederick Maylea12b0962022-06-25 01:13:22 +000018#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000019
Steven Morelandc1635952021-04-01 16:20:47 +000020#include <chrono>
21#include <cstdlib>
22#include <iostream>
23#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000024#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000025
Andrei Homescu2a298012022-06-15 01:08:54 +000026#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070027#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000029#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000030
Andrei Homescu68a55612022-08-02 01:25:15 +000031#ifdef __ANDROID_VENDOR__
32#include <binder/RpcTransportTipcAndroid.h>
33#include <trusty/tipc.h>
34#endif // __ANDROID_VENDOR__
35
Andrei Homescu2a298012022-06-15 01:08:54 +000036#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000037#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000038
Yifan Hong1a235852021-05-13 16:07:47 -070039using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070040using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070041using testing::AssertionFailure;
42using testing::AssertionResult;
43using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070044
Steven Moreland5553ac42020-11-11 02:14:45 +000045namespace android {
46
Andrei Homescu12106de2022-04-27 04:42:21 +000047#ifdef BINDER_TEST_NO_SHARED_LIBS
48constexpr bool kEnableSharedLibs = false;
49#else
50constexpr bool kEnableSharedLibs = true;
51#endif
52
Andrei Homescu68a55612022-08-02 01:25:15 +000053#ifdef __ANDROID_VENDOR__
54constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
55#endif
56
Frederick Maylea12b0962022-06-25 01:13:22 +000057static std::string WaitStatusToString(int wstatus) {
58 if (WIFEXITED(wstatus)) {
59 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
60 }
61 if (WIFSIGNALED(wstatus)) {
62 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
63 }
64 return base::StringPrintf("unexpected state %d", wstatus);
65}
66
Steven Moreland276d8df2022-09-28 23:56:39 +000067static void debugBacktrace(pid_t pid) {
68 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
69 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
70}
71
Steven Moreland5553ac42020-11-11 02:14:45 +000072class Process {
73public:
Andrei Homescu96834632022-10-14 00:49:49 +000074 Process(Process&& other)
75 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
76 mReadEnd(std::move(other.mReadEnd)),
77 mWriteEnd(std::move(other.mWriteEnd)) {
78 // The default move constructor doesn't clear mPid after moving it,
79 // which we need to do because the destructor checks for mPid!=0
80 mPid = other.mPid;
81 other.mPid = 0;
82 }
Yifan Hong1deca4b2021-09-10 16:16:44 -070083 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
84 android::base::borrowed_fd /* readEnd */)>& f) {
85 android::base::unique_fd childWriteEnd;
86 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +000087 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
88 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +000089 if (0 == (mPid = fork())) {
90 // racey: assume parent doesn't crash before this is set
91 prctl(PR_SET_PDEATHSIG, SIGHUP);
92
Yifan Hong1deca4b2021-09-10 16:16:44 -070093 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +000094
95 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +000096 }
97 }
98 ~Process() {
99 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000100 int wstatus;
101 waitpid(mPid, &wstatus, 0);
102 if (mCustomExitStatusCheck) {
103 mCustomExitStatusCheck(wstatus);
104 } else {
105 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
106 << "server process failed: " << WaitStatusToString(wstatus);
107 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000108 }
109 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700110 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700111 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000112
Frederick Maylea12b0962022-06-25 01:13:22 +0000113 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
114 mCustomExitStatusCheck = std::move(f);
115 }
116
Frederick Mayle69a0c992022-05-26 20:38:39 +0000117 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
118 void terminate() { kill(mPid, SIGTERM); }
119
Steven Moreland276d8df2022-09-28 23:56:39 +0000120 pid_t getPid() { return mPid; }
121
Steven Moreland5553ac42020-11-11 02:14:45 +0000122private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000123 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000124 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700125 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700126 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000127};
128
129static std::string allocateSocketAddress() {
130 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000131 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000132 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700133 unlink(ret.c_str());
134 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000135};
136
Steven Morelandda573042021-06-12 01:13:45 +0000137static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000138 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000139 return vsockPort++;
140}
141
Alice Wang893a9912022-10-24 10:44:09 +0000142static base::unique_fd initUnixSocket(std::string addr) {
143 auto socket_addr = UnixSocketAddress(addr.c_str());
144 base::unique_fd fd(
145 TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
146 CHECK(fd.ok());
147 CHECK_EQ(0, TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize())));
148 return fd;
149}
150
Andrei Homescu96834632022-10-14 00:49:49 +0000151// Destructors need to be defined, even if pure virtual
152ProcessSession::~ProcessSession() {}
153
154class LinuxProcessSession : public ProcessSession {
155public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000156 // reference to process hosting a socket server
157 Process host;
158
Andrei Homescu96834632022-10-14 00:49:49 +0000159 LinuxProcessSession(LinuxProcessSession&&) = default;
160 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
161 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000162 for (auto& session : sessions) {
163 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000164 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000165
Steven 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 Homescuf30148c2023-03-10 00:31:45 +0000234std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
235 return newTlsFactory(rpcSecurity);
Andrei Homescu96834632022-10-14 00:49:49 +0000236}
Andrei Homescu2a298012022-06-15 01:08:54 +0000237
Andrei Homescu96834632022-10-14 00:49:49 +0000238// This creates a new process serving an interface on a certain number of
239// threads.
240std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
241 const BinderRpcOptions& options) {
242 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000243
Andrei Homescu96834632022-10-14 00:49:49 +0000244 SocketType socketType = std::get<0>(GetParam());
245 RpcSecurity rpcSecurity = std::get<1>(GetParam());
246 uint32_t clientVersion = std::get<2>(GetParam());
247 uint32_t serverVersion = std::get<3>(GetParam());
248 bool singleThreaded = std::get<4>(GetParam());
249 bool noKernel = std::get<5>(GetParam());
250
251 std::string path = android::base::GetExecutableDirectory();
252 auto servicePath = android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
253 singleThreaded ? "_single_threaded" : "",
254 noKernel ? "_no_kernel" : "");
255
Alice Wang1ef010b2022-11-14 09:09:25 +0000256 base::unique_fd bootstrapClientFd, socketFd;
257
Alice Wang893a9912022-10-24 10:44:09 +0000258 auto addr = allocateSocketAddress();
259 // Initializes the socket before the fork/exec.
260 if (socketType == SocketType::UNIX_RAW) {
261 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000262 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
263 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
264 // This is because we cannot pass ParcelFileDescriptor over a pipe.
265 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
266 int savedErrno = errno;
267 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
268 }
Alice Wang893a9912022-10-24 10:44:09 +0000269 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000270
Andrei Homescu96834632022-10-14 00:49:49 +0000271 auto ret = std::make_unique<LinuxProcessSession>(
272 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000273 if (socketType == SocketType::TIPC) {
274 // Trusty has a single persistent service
275 return;
276 }
277
Andrei Homescu96834632022-10-14 00:49:49 +0000278 auto writeFd = std::to_string(writeEnd.get());
279 auto readFd = std::to_string(readEnd.get());
280 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
281 NULL);
282 }));
283
284 BinderRpcTestServerConfig serverConfig;
285 serverConfig.numThreads = options.numThreads;
286 serverConfig.socketType = static_cast<int32_t>(socketType);
287 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
288 serverConfig.serverVersion = serverVersion;
289 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000290 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000291 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000292 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
293 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
294 static_cast<int32_t>(mode));
295 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000296 if (socketType != SocketType::TIPC) {
297 writeToFd(ret->host.writeEnd(), serverConfig);
298 }
Andrei Homescu96834632022-10-14 00:49:49 +0000299
300 std::vector<sp<RpcSession>> sessions;
301 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
302 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000303 std::unique_ptr<RpcTransportCtxFactory> factory;
304 if (socketType == SocketType::TIPC) {
305#ifdef __ANDROID_VENDOR__
306 factory = RpcTransportCtxFactoryTipcAndroid::make();
307#else
308 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
309#endif
310 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000311 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000312 }
313 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100314 }
315
Andrei Homescu68a55612022-08-02 01:25:15 +0000316 BinderRpcTestServerInfo serverInfo;
317 if (socketType != SocketType::TIPC) {
318 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
319 BinderRpcTestClientInfo clientInfo;
320 for (const auto& session : sessions) {
321 auto& parcelableCert = clientInfo.certs.emplace_back();
322 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
323 }
324 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000325
Andrei Homescu68a55612022-08-02 01:25:15 +0000326 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
327 if (socketType == SocketType::INET) {
328 CHECK_NE(0, serverInfo.port);
329 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000330
Andrei Homescu68a55612022-08-02 01:25:15 +0000331 if (rpcSecurity == RpcSecurity::TLS) {
332 const auto& serverCert = serverInfo.cert.data;
333 CHECK_EQ(OK,
334 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
335 serverCert));
336 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700337 }
338
Andrei Homescu96834632022-10-14 00:49:49 +0000339 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000340
Andrei Homescu96834632022-10-14 00:49:49 +0000341 for (const auto& session : sessions) {
342 CHECK(session->setProtocolVersion(clientVersion));
343 session->setMaxIncomingThreads(options.numIncomingConnections);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000344 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000345 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000346
Andrei Homescu96834632022-10-14 00:49:49 +0000347 switch (socketType) {
348 case SocketType::PRECONNECTED:
349 status = session->setupPreconnectedClient({}, [=]() {
350 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
351 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000352 break;
Alice Wang893a9912022-10-24 10:44:09 +0000353 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000354 case SocketType::UNIX:
355 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
356 break;
357 case SocketType::UNIX_BOOTSTRAP:
358 status = session->setupUnixDomainSocketBootstrapClient(
359 base::unique_fd(dup(bootstrapClientFd.get())));
360 break;
361 case SocketType::VSOCK:
362 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
363 break;
364 case SocketType::INET:
365 status = session->setupInetClient("127.0.0.1", serverInfo.port);
366 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000367 case SocketType::TIPC:
368 status = session->setupPreconnectedClient({}, [=]() {
369#ifdef __ANDROID_VENDOR__
370 auto port = trustyIpcPort(serverVersion);
371 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
372 return tipcFd >= 0 ? android::base::unique_fd(tipcFd)
373 : android::base::unique_fd();
374#else
375 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
376 return android::base::unique_fd();
377#endif
378 });
379 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000380 default:
381 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000382 }
Andrei Homescu96834632022-10-14 00:49:49 +0000383 if (options.allowConnectFailure && status != OK) {
384 ret->sessions.clear();
385 break;
386 }
387 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
388 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000389 }
Andrei Homescu96834632022-10-14 00:49:49 +0000390 return ret;
391}
Steven Morelandc1635952021-04-01 16:20:47 +0000392
Andrei Homescua858b0e2022-08-01 23:43:09 +0000393TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
394 if (clientOrServerSingleThreaded()) {
395 GTEST_SKIP() << "This test requires multiple threads";
396 }
397
Steven Moreland5553ac42020-11-11 02:14:45 +0000398 constexpr size_t kNumThreads = 10;
399
Steven Moreland4313d7e2021-07-15 23:41:22 +0000400 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000401
402 EXPECT_OK(proc.rootIface->lock());
403
404 // block all but one thread taking locks
405 std::vector<std::thread> ts;
406 for (size_t i = 0; i < kNumThreads - 1; i++) {
407 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
408 }
409
Steven Morelandd6d816f2022-12-23 01:37:17 +0000410 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000411
412 // other calls still work
413 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
414
Steven Morelandd6d816f2022-12-23 01:37:17 +0000415 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000416 size_t epochMsBefore = epochMillis();
417 // after this, we should never see a response within this time
418 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
419
420 // this call should be blocked for blockTimeMs
421 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
422
423 size_t epochMsAfter = epochMillis();
424 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
425
426 for (auto& t : ts) t.join();
427}
428
Steven Moreland27f620a2023-03-06 19:44:36 +0000429static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000430 size_t epochMsBefore = epochMillis();
431
432 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700433 for (size_t i = 0; i < numCalls; i++) {
434 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000435 }
436
437 for (auto& t : ts) t.join();
438
439 size_t epochMsAfter = epochMillis();
440
Yifan Hong1f44f982021-10-08 17:16:47 -0700441 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000442
443 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700444 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
445}
446
Andrei Homescua858b0e2022-08-01 23:43:09 +0000447TEST_P(BinderRpc, ThreadPoolOverSaturated) {
448 if (clientOrServerSingleThreaded()) {
449 GTEST_SKIP() << "This test requires multiple threads";
450 }
451
Yifan Hong1f44f982021-10-08 17:16:47 -0700452 constexpr size_t kNumThreads = 10;
453 constexpr size_t kNumCalls = kNumThreads + 3;
454 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland27f620a2023-03-06 19:44:36 +0000455 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 250 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700456}
457
Andrei Homescua858b0e2022-08-01 23:43:09 +0000458TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
459 if (clientOrServerSingleThreaded()) {
460 GTEST_SKIP() << "This test requires multiple threads";
461 }
462
Yifan Hong1f44f982021-10-08 17:16:47 -0700463 constexpr size_t kNumThreads = 20;
464 constexpr size_t kNumOutgoingConnections = 10;
465 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
466 auto proc = createRpcTestSocketServerProcess(
467 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland27f620a2023-03-06 19:44:36 +0000468 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 250 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000469}
470
Andrei Homescua858b0e2022-08-01 23:43:09 +0000471TEST_P(BinderRpc, ThreadingStressTest) {
472 if (clientOrServerSingleThreaded()) {
473 GTEST_SKIP() << "This test requires multiple threads";
474 }
475
Steven Moreland27f620a2023-03-06 19:44:36 +0000476 constexpr size_t kNumClientThreads = 5;
477 constexpr size_t kNumServerThreads = 5;
478 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000479
Steven Moreland4313d7e2021-07-15 23:41:22 +0000480 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000481
482 std::vector<std::thread> threads;
483 for (size_t i = 0; i < kNumClientThreads; i++) {
484 threads.push_back(std::thread([&] {
485 for (size_t j = 0; j < kNumCalls; j++) {
486 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000487 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000488 EXPECT_EQ(proc.rootBinder, out);
489 }
490 }));
491 }
492
493 for (auto& t : threads) t.join();
494}
495
Steven Moreland925ba0a2021-09-17 18:06:32 -0700496static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
497 std::vector<std::thread> threads;
498 for (size_t i = 0; i < threadCount; i++) {
499 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
500 }
501 for (auto& t : threads) t.join();
502}
503
Andrei Homescua858b0e2022-08-01 23:43:09 +0000504TEST_P(BinderRpc, OnewayStressTest) {
505 if (clientOrServerSingleThreaded()) {
506 GTEST_SKIP() << "This test requires multiple threads";
507 }
508
Steven Morelandc6046982021-04-20 00:49:42 +0000509 constexpr size_t kNumClientThreads = 10;
510 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700511 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000512
Steven Moreland4313d7e2021-07-15 23:41:22 +0000513 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000514
515 std::vector<std::thread> threads;
516 for (size_t i = 0; i < kNumClientThreads; i++) {
517 threads.push_back(std::thread([&] {
518 for (size_t j = 0; j < kNumCalls; j++) {
519 EXPECT_OK(proc.rootIface->sendString("a"));
520 }
Steven Morelandc6046982021-04-20 00:49:42 +0000521 }));
522 }
523
524 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700525
526 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000527}
528
Frederick Mayleb0221d12022-10-03 23:10:53 +0000529TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
530 if (!supportsFdTransport()) {
531 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
532 }
533 if (clientOrServerSingleThreaded()) {
534 GTEST_SKIP() << "This test requires multiple threads";
535 }
536
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000537 constexpr size_t kNumServerThreads = 3;
538
Frederick Mayleb0221d12022-10-03 23:10:53 +0000539 // This test forces a oneway transaction to be queued by issuing two
540 // `blockingSendFdOneway` calls, then drains the queue by issuing two
541 // `blockingRecvFd` calls.
542 //
543 // For more details about the queuing semantics see
544 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
545
546 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000547 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000548 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
549 .serverSupportedFileDescriptorTransportModes =
550 {RpcSession::FileDescriptorTransportMode::UNIX},
551 });
552
553 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
554 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
555 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
556 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
557
558 android::os::ParcelFileDescriptor fdA;
559 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
560 std::string result;
561 CHECK(android::base::ReadFdToString(fdA.get(), &result));
562 EXPECT_EQ(result, "a");
563
564 android::os::ParcelFileDescriptor fdB;
565 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
566 CHECK(android::base::ReadFdToString(fdB.get(), &result));
567 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000568
569 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000570}
571
Andrei Homescua858b0e2022-08-01 23:43:09 +0000572TEST_P(BinderRpc, OnewayCallQueueing) {
573 if (clientOrServerSingleThreaded()) {
574 GTEST_SKIP() << "This test requires multiple threads";
575 }
576
Steven Moreland5553ac42020-11-11 02:14:45 +0000577 constexpr size_t kNumSleeps = 10;
578 constexpr size_t kNumExtraServerThreads = 4;
579 constexpr size_t kSleepMs = 50;
580
581 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000582 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000583
584 EXPECT_OK(proc.rootIface->lock());
585
Steven Moreland1c678802021-09-17 16:48:47 -0700586 size_t epochMsBefore = epochMillis();
587
588 // all these *Async commands should be queued on the server sequentially,
589 // even though there are multiple threads.
590 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000591 proc.rootIface->sleepMsAsync(kSleepMs);
592 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000593 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
594
Steven Moreland1c678802021-09-17 16:48:47 -0700595 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000596 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700597
Steven Moreland5553ac42020-11-11 02:14:45 +0000598 size_t epochMsAfter = epochMillis();
599
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000600 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000601
Steven Moreland925ba0a2021-09-17 18:06:32 -0700602 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000603}
604
Andrei Homescua858b0e2022-08-01 23:43:09 +0000605TEST_P(BinderRpc, OnewayCallExhaustion) {
606 if (clientOrServerSingleThreaded()) {
607 GTEST_SKIP() << "This test requires multiple threads";
608 }
609
Steven Morelandd45be622021-06-04 02:19:37 +0000610 constexpr size_t kNumClients = 2;
611 constexpr size_t kTooLongMs = 1000;
612
Steven Moreland4313d7e2021-07-15 23:41:22 +0000613 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000614
615 // Build up oneway calls on the second session to make sure it terminates
616 // and shuts down. The first session should be unaffected (proc destructor
617 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000618 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000619
620 std::vector<std::thread> threads;
621 for (size_t i = 0; i < kNumClients; i++) {
622 // one of these threads will get stuck queueing a transaction once the
623 // socket fills up, the other will be able to fill up transactions on
624 // this object
625 threads.push_back(std::thread([&] {
626 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
627 }
628 }));
629 }
630 for (auto& t : threads) t.join();
631
632 Status status = iface->sleepMsAsync(kTooLongMs);
633 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
634
Steven Moreland798e0d12021-07-14 23:19:25 +0000635 // now that it has died, wait for the remote session to shutdown
636 std::vector<int32_t> remoteCounts;
637 do {
638 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
639 } while (remoteCounts.size() == kNumClients);
640
Steven Morelandd45be622021-06-04 02:19:37 +0000641 // the second session should be shutdown in the other process by the time we
642 // are able to join above (it'll only be hung up once it finishes processing
643 // any pending commands). We need to erase this session from the record
644 // here, so that the destructor for our session won't check that this
645 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000646 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000647}
648
Devin Moore66d5b7a2022-07-07 21:42:10 +0000649TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000650 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000651 GTEST_SKIP() << "This test requires multiple threads";
652 }
653 class MyDeathRec : public IBinder::DeathRecipient {
654 public:
655 void binderDied(const wp<IBinder>& /* who */) override {
656 dead = true;
657 mCv.notify_one();
658 }
659 std::mutex mMtx;
660 std::condition_variable mCv;
661 bool dead = false;
662 };
663
664 // Death recipient needs to have an incoming connection to be called
665 auto proc = createRpcTestSocketServerProcess(
666 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
667
668 auto dr = sp<MyDeathRec>::make();
669 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
670
671 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
672 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
673 }
674
675 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000676 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000677
678 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000679 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000680 proc.expectAlreadyShutdown = true;
681}
682
683TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000684 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000685 GTEST_SKIP() << "This test requires multiple threads";
686 }
687 class MyDeathRec : public IBinder::DeathRecipient {
688 public:
689 void binderDied(const wp<IBinder>& /* who */) override {
690 dead = true;
691 mCv.notify_one();
692 }
693 std::mutex mMtx;
694 std::condition_variable mCv;
695 bool dead = false;
696 };
697
698 // Death recipient needs to have an incoming connection to be called
699 auto proc = createRpcTestSocketServerProcess(
700 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
701
702 auto dr = sp<MyDeathRec>::make();
703 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
704
705 // Explicitly calling shutDownAndWait will cause the death recipients
706 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000707 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000708
709 std::unique_lock<std::mutex> lock(dr->mMtx);
710 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000711 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000712 }
713 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
714
Andrei Homescu96834632022-10-14 00:49:49 +0000715 proc.proc->terminate();
716 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000717 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
718 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
719 });
720 proc.expectAlreadyShutdown = true;
721}
722
Steven Moreland5ec743f2023-01-18 01:02:06 +0000723TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000724 if (socketType() == SocketType::TIPC) {
725 // This should work, but Trusty takes too long to restart the service
726 GTEST_SKIP() << "Service death test not supported on Trusty";
727 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000728 class MyDeathRec : public IBinder::DeathRecipient {
729 public:
730 void binderDied(const wp<IBinder>& /* who */) override {}
731 };
732
733 auto proc = createRpcTestSocketServerProcess(
734 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
735
736 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000737 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000738}
739
740TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000741 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000742 GTEST_SKIP() << "This test requires multiple threads";
743 }
744 class MyDeathRec : public IBinder::DeathRecipient {
745 public:
746 void binderDied(const wp<IBinder>& /* who */) override {
747 GTEST_FAIL() << "This should not be called after unlinkToDeath";
748 }
749 };
750
751 // Death recipient needs to have an incoming connection to be called
752 auto proc = createRpcTestSocketServerProcess(
753 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
754
755 auto dr = sp<MyDeathRec>::make();
756 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
757 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
758
759 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
760 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
761 }
762
763 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000764 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000765 proc.expectAlreadyShutdown = true;
766}
767
Steven Morelandc1635952021-04-01 16:20:47 +0000768TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000769 if (socketType() == SocketType::TIPC) {
770 // This should work, but Trusty takes too long to restart the service
771 GTEST_SKIP() << "Service death test not supported on Trusty";
772 }
773
Steven Moreland5553ac42020-11-11 02:14:45 +0000774 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000775 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000776
777 // make sure there is some state during crash
778 // 1. we hold their binder
779 sp<IBinderRpcSession> session;
780 EXPECT_OK(proc.rootIface->openSession("happy", &session));
781 // 2. they hold our binder
782 sp<IBinder> binder = new BBinder();
783 EXPECT_OK(proc.rootIface->holdBinder(binder));
784
785 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
786 << "Do death cleanup: " << doDeathCleanup;
787
Andrei Homescu96834632022-10-14 00:49:49 +0000788 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000789 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
790 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
791 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000792 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000793 }
794}
795
Steven Morelandd7302072021-05-15 01:32:04 +0000796TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000797 // This test only works if the current process shared the internal state of
798 // ProcessState with the service across the call to fork(). Both the static
799 // libraries and libbinder.so have their own separate copies of all the
800 // globals, so the test only works when the test client and service both use
801 // libbinder.so (when using static libraries, even a client and service
802 // using the same kind of static library should have separate copies of the
803 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000804 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000805 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
806 "at build time.";
807 }
808
Steven Moreland4313d7e2021-07-15 23:41:22 +0000809 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000810
Andrei Homescu2a298012022-06-15 01:08:54 +0000811 // we can't allocate IPCThreadState so actually the first time should
812 // succeed :(
813 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000814
815 // second time! we catch the error :)
816 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
817
Andrei Homescu96834632022-10-14 00:49:49 +0000818 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000819 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
820 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
821 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000822 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000823}
824
Frederick Mayle69a0c992022-05-26 20:38:39 +0000825TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000826 if (socketType() == SocketType::TIPC) {
827 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
828 }
829
Frederick Mayle69a0c992022-05-26 20:38:39 +0000830 auto proc = createRpcTestSocketServerProcess({
831 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
832 .serverSupportedFileDescriptorTransportModes =
833 {RpcSession::FileDescriptorTransportMode::UNIX},
834 .allowConnectFailure = true,
835 });
Andrei Homescu96834632022-10-14 00:49:49 +0000836 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
837 proc.proc->terminate();
838 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000839 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
840 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
841 });
842 proc.expectAlreadyShutdown = true;
843}
844
845TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000846 if (socketType() == SocketType::TIPC) {
847 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
848 }
849
Frederick Mayle69a0c992022-05-26 20:38:39 +0000850 auto proc = createRpcTestSocketServerProcess({
851 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
852 .serverSupportedFileDescriptorTransportModes =
853 {RpcSession::FileDescriptorTransportMode::NONE},
854 .allowConnectFailure = true,
855 });
Andrei Homescu96834632022-10-14 00:49:49 +0000856 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
857 proc.proc->terminate();
858 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000859 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
860 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
861 });
862 proc.expectAlreadyShutdown = true;
863}
864
865TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000866 if (socketType() == SocketType::TIPC) {
867 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
868 }
869
Frederick Mayle69a0c992022-05-26 20:38:39 +0000870 auto proc = createRpcTestSocketServerProcess({
871 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
872 .serverSupportedFileDescriptorTransportModes =
873 {RpcSession::FileDescriptorTransportMode::NONE,
874 RpcSession::FileDescriptorTransportMode::UNIX},
875 });
876
877 android::os::ParcelFileDescriptor out;
878 auto status = proc.rootIface->echoAsFile("hello", &out);
879 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
880}
881
882TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000883 if (socketType() == SocketType::TIPC) {
884 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
885 }
886
Frederick Mayle69a0c992022-05-26 20:38:39 +0000887 auto proc = createRpcTestSocketServerProcess({
888 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
889 .serverSupportedFileDescriptorTransportModes =
890 {RpcSession::FileDescriptorTransportMode::UNIX},
891 });
892
893 android::os::ParcelFileDescriptor out;
894 auto status = proc.rootIface->echoAsFile("hello", &out);
895 if (!supportsFdTransport()) {
896 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
897 return;
898 }
899 ASSERT_TRUE(status.isOk()) << status;
900
901 std::string result;
902 CHECK(android::base::ReadFdToString(out.get(), &result));
903 EXPECT_EQ(result, "hello");
904}
905
906TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000907 if (socketType() == SocketType::TIPC) {
908 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
909 }
910
Frederick Mayle69a0c992022-05-26 20:38:39 +0000911 auto proc = createRpcTestSocketServerProcess({
912 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
913 .serverSupportedFileDescriptorTransportModes =
914 {RpcSession::FileDescriptorTransportMode::UNIX},
915 });
916
917 std::vector<android::os::ParcelFileDescriptor> files;
918 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
919 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
920 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
921 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
922
923 android::os::ParcelFileDescriptor out;
924 auto status = proc.rootIface->concatFiles(files, &out);
925 if (!supportsFdTransport()) {
926 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
927 return;
928 }
929 ASSERT_TRUE(status.isOk()) << status;
930
931 std::string result;
932 CHECK(android::base::ReadFdToString(out.get(), &result));
933 EXPECT_EQ(result, "123abcd");
934}
935
936TEST_P(BinderRpc, SendMaxFiles) {
937 if (!supportsFdTransport()) {
938 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
939 }
940
941 auto proc = createRpcTestSocketServerProcess({
942 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
943 .serverSupportedFileDescriptorTransportModes =
944 {RpcSession::FileDescriptorTransportMode::UNIX},
945 });
946
947 std::vector<android::os::ParcelFileDescriptor> files;
948 for (int i = 0; i < 253; i++) {
949 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
950 }
951
952 android::os::ParcelFileDescriptor out;
953 auto status = proc.rootIface->concatFiles(files, &out);
954 ASSERT_TRUE(status.isOk()) << status;
955
956 std::string result;
957 CHECK(android::base::ReadFdToString(out.get(), &result));
958 EXPECT_EQ(result, std::string(253, 'a'));
959}
960
961TEST_P(BinderRpc, SendTooManyFiles) {
962 if (!supportsFdTransport()) {
963 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
964 }
965
966 auto proc = createRpcTestSocketServerProcess({
967 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
968 .serverSupportedFileDescriptorTransportModes =
969 {RpcSession::FileDescriptorTransportMode::UNIX},
970 });
971
972 std::vector<android::os::ParcelFileDescriptor> files;
973 for (int i = 0; i < 254; i++) {
974 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
975 }
976
977 android::os::ParcelFileDescriptor out;
978 auto status = proc.rootIface->concatFiles(files, &out);
979 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
980}
981
Andrei Homescufc221502022-10-08 03:51:17 +0000982TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000983 if (socketType() == SocketType::TIPC) {
984 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
985 }
986
Andrei Homescufc221502022-10-08 03:51:17 +0000987 auto proc = createRpcTestSocketServerProcess({
988 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
989 .serverSupportedFileDescriptorTransportModes =
990 {RpcSession::FileDescriptorTransportMode::UNIX},
991 });
992
993 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
994 ASSERT_NE(badFd, -1);
995
996 // Close the file descriptor so it becomes invalid for dup
997 close(badFd);
998
999 Parcel p1;
1000 p1.markForBinder(proc.rootBinder);
1001 p1.writeInt32(3);
1002 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1003
1004 Parcel pRaw;
1005 pRaw.markForBinder(proc.rootBinder);
1006 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1007
1008 pRaw.setDataPosition(0);
1009 EXPECT_EQ(3, pRaw.readInt32());
1010 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1011}
1012
Andrei Homescu68a55612022-08-02 01:25:15 +00001013#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001014TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001015 if constexpr (!kEnableSharedLibs) {
1016 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1017 }
1018
Steven Moreland4313d7e2021-07-15 23:41:22 +00001019 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001020
1021 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1022 ASSERT_NE(binder, nullptr);
1023
1024 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1025}
1026
1027TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001028 if constexpr (!kEnableSharedLibs) {
1029 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1030 }
1031
Steven Moreland4313d7e2021-07-15 23:41:22 +00001032 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001033
1034 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1035 ASSERT_NE(binder, nullptr);
1036
1037 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1038 ASSERT_NE(ndkBinder, nullptr);
1039
1040 std::string out;
1041 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1042 ASSERT_TRUE(status.isOk()) << status.getDescription();
1043 ASSERT_EQ("aoeuaoeu", out);
1044}
Andrei Homescu68a55612022-08-02 01:25:15 +00001045#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001046
Steven Moreland5553ac42020-11-11 02:14:45 +00001047ssize_t countFds() {
1048 DIR* dir = opendir("/proc/self/fd/");
1049 if (dir == nullptr) return -1;
1050 ssize_t ret = 0;
1051 dirent* ent;
1052 while ((ent = readdir(dir)) != nullptr) ret++;
1053 closedir(dir);
1054 return ret;
1055}
1056
Andrei Homescua858b0e2022-08-01 23:43:09 +00001057TEST_P(BinderRpc, Fds) {
1058 if (serverSingleThreaded()) {
1059 GTEST_SKIP() << "This test requires multiple threads";
1060 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001061 if (socketType() == SocketType::TIPC) {
1062 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1063 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001064
Steven Moreland5553ac42020-11-11 02:14:45 +00001065 ssize_t beforeFds = countFds();
1066 ASSERT_GE(beforeFds, 0);
1067 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001068 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001069 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1070 }
1071 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1072}
1073
Steven Morelandda573042021-06-12 01:13:45 +00001074static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001075 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001076 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001077
Andrei Homescu992a4052022-06-28 21:26:18 +00001078 android::base::unique_fd serverFd(
1079 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1080 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1081
1082 sockaddr_vm serverAddr{
1083 .svm_family = AF_VSOCK,
1084 .svm_port = vsockPort,
1085 .svm_cid = VMADDR_CID_ANY,
1086 };
1087 int ret = TEMP_FAILURE_RETRY(
1088 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1089 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1090 strerror(errno));
1091
1092 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1093 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1094 strerror(errno));
1095
1096 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1097 // to see if the kernel supports it. It's safe to use a blocking
1098 // connect because vsock sockets have a 2 second connection timeout,
1099 // and they return ETIMEDOUT after that.
1100 android::base::unique_fd connectFd(
1101 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1102 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1103 strerror(errno));
1104
1105 bool success = false;
1106 sockaddr_vm connectAddr{
1107 .svm_family = AF_VSOCK,
1108 .svm_port = vsockPort,
1109 .svm_cid = VMADDR_CID_LOCAL,
1110 };
1111 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1112 sizeof(connectAddr)));
1113 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1114 android::base::unique_fd acceptFd;
1115 while (true) {
1116 pollfd pfd[]{
1117 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1118 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1119 };
1120 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1121 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1122
1123 if (pfd[0].revents & POLLIN) {
1124 sockaddr_vm acceptAddr;
1125 socklen_t acceptAddrLen = sizeof(acceptAddr);
1126 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1127 reinterpret_cast<sockaddr*>(&acceptAddr),
1128 &acceptAddrLen, SOCK_CLOEXEC));
1129 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1130 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1131 "Truncated address");
1132
1133 // Store the fd in acceptFd so we keep the connection alive
1134 // while polling connectFd
1135 acceptFd.reset(ret);
1136 }
1137
1138 if (pfd[1].revents & POLLOUT) {
1139 // Connect either succeeded or timed out
1140 int connectErrno;
1141 socklen_t connectErrnoLen = sizeof(connectErrno);
1142 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1143 &connectErrnoLen);
1144 LOG_ALWAYS_FATAL_IF(ret == -1,
1145 "Could not getsockopt() after connect() "
1146 "on non-blocking socket: %s.",
1147 strerror(errno));
1148
1149 // We're done, this is all we wanted
1150 success = connectErrno == 0;
1151 break;
1152 }
1153 }
1154 } else {
1155 success = ret == 0;
1156 }
1157
1158 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1159
1160 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001161}
1162
Yifan Hong1deca4b2021-09-10 16:16:44 -07001163static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001164 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1165 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001166
1167 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001168
1169 static bool hasVsockLoopback = testSupportVsockLoopback();
1170
1171 if (hasVsockLoopback) {
1172 ret.push_back(SocketType::VSOCK);
1173 }
1174
1175 return ret;
1176}
1177
Andrei Homescu68a55612022-08-02 01:25:15 +00001178static std::vector<SocketType> testTipcSocketTypes() {
1179#ifdef __ANDROID_VENDOR__
1180 auto port = trustyIpcPort(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1181 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
1182 if (tipcFd >= 0) {
1183 close(tipcFd);
1184 return {SocketType::TIPC};
1185 }
1186#endif // __ANDROID_VENDOR__
1187
1188 // TIPC is not supported on this device, most likely
1189 // because /dev/trusty-ipc-dev0 is missing
1190 return {};
1191}
1192
Yifan Hong702115c2021-06-24 15:39:18 -07001193INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1194 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001195 ::testing::ValuesIn(RpcSecurityValues()),
1196 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001197 ::testing::ValuesIn(testVersions()),
1198 ::testing::Values(false, true),
1199 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001200 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001201
Andrei Homescu68a55612022-08-02 01:25:15 +00001202INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc,
1203 ::testing::Combine(::testing::ValuesIn(testTipcSocketTypes()),
1204 ::testing::Values(RpcSecurity::RAW),
1205 ::testing::ValuesIn(testVersions()),
1206 ::testing::ValuesIn(testVersions()),
1207 ::testing::Values(true), ::testing::Values(true)),
1208 BinderRpc::PrintParamInfo);
1209
Yifan Hong702115c2021-06-24 15:39:18 -07001210class BinderRpcServerRootObject
1211 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001212
1213TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1214 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1215 auto setRootObject = [](bool isStrong) -> SetFn {
1216 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1217 };
1218
Yifan Hong702115c2021-06-24 15:39:18 -07001219 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001220 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001221 auto binder1 = sp<BBinder>::make();
1222 IBinder* binderRaw1 = binder1.get();
1223 setRootObject(isStrong1)(server.get(), binder1);
1224 EXPECT_EQ(binderRaw1, server->getRootObject());
1225 binder1.clear();
1226 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1227
1228 auto binder2 = sp<BBinder>::make();
1229 IBinder* binderRaw2 = binder2.get();
1230 setRootObject(isStrong2)(server.get(), binder2);
1231 EXPECT_EQ(binderRaw2, server->getRootObject());
1232 binder2.clear();
1233 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1234}
1235
1236INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001237 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1238 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001239
Yifan Hong1a235852021-05-13 16:07:47 -07001240class OneOffSignal {
1241public:
1242 // If notify() was previously called, or is called within |duration|, return true; else false.
1243 template <typename R, typename P>
1244 bool wait(std::chrono::duration<R, P> duration) {
1245 std::unique_lock<std::mutex> lock(mMutex);
1246 return mCv.wait_for(lock, duration, [this] { return mValue; });
1247 }
1248 void notify() {
1249 std::unique_lock<std::mutex> lock(mMutex);
1250 mValue = true;
1251 lock.unlock();
1252 mCv.notify_all();
1253 }
1254
1255private:
1256 std::mutex mMutex;
1257 std::condition_variable mCv;
1258 bool mValue = false;
1259};
1260
Yifan Hong194acf22021-06-29 18:44:56 -07001261TEST(BinderRpc, Java) {
1262#if !defined(__ANDROID__)
1263 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1264 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1265 "to binderHostDeviceTest. Hence, just disable this test on host.";
1266#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001267 if constexpr (!kEnableKernelIpc) {
1268 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1269 "at build time.";
1270 }
1271
Yifan Hong194acf22021-06-29 18:44:56 -07001272 sp<IServiceManager> sm = defaultServiceManager();
1273 ASSERT_NE(nullptr, sm);
1274 // Any Java service with non-empty getInterfaceDescriptor() would do.
1275 // Let's pick batteryproperties.
1276 auto binder = sm->checkService(String16("batteryproperties"));
1277 ASSERT_NE(nullptr, binder);
1278 auto descriptor = binder->getInterfaceDescriptor();
1279 ASSERT_GE(descriptor.size(), 0);
1280 ASSERT_EQ(OK, binder->pingBinder());
1281
1282 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001283 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001284 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001285 auto socket = rpcServer->releaseServer();
1286
1287 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001288 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1289
Yifan Honge3caaf22022-01-12 14:46:56 -08001290 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1291 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001292 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001293 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1294 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001295 << statusToString(setRpcClientDebugStatus);
1296 GTEST_SKIP();
1297 }
1298
1299 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001300
1301 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001302 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001303 auto rpcBinder = rpcSession->getRootObject();
1304 ASSERT_NE(nullptr, rpcBinder);
1305
1306 ASSERT_EQ(OK, rpcBinder->pingBinder());
1307
1308 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1309 << "getInterfaceDescriptor should not crash system_server";
1310 ASSERT_EQ(OK, rpcBinder->pingBinder());
1311}
1312
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001313class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1314public:
1315 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001316 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001317 std::to_string(std::get<1>(info.param));
1318 }
1319};
1320
1321TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1322 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1323 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001324 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001325 server->setProtocolVersion(std::get<1>(GetParam()));
1326 ASSERT_FALSE(server->hasServer());
1327 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1328 ASSERT_TRUE(server->hasServer());
1329 base::unique_fd retrieved = server->releaseServer();
1330 ASSERT_FALSE(server->hasServer());
1331 ASSERT_EQ(sinkFd, retrieved.get());
1332}
1333
1334TEST_P(BinderRpcServerOnly, Shutdown) {
1335 if constexpr (!kEnableRpcThreads) {
1336 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1337 }
1338
1339 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001340 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001341 server->setProtocolVersion(std::get<1>(GetParam()));
1342 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1343 auto joinEnds = std::make_shared<OneOffSignal>();
1344
1345 // If things are broken and the thread never stops, don't block other tests. Because the thread
1346 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1347 // shared pointers are passed.
1348 std::thread([server, joinEnds] {
1349 server->join();
1350 joinEnds->notify();
1351 }).detach();
1352
1353 bool shutdown = false;
1354 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001355 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001356 if (server->shutdown()) shutdown = true;
1357 }
1358 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1359
1360 ASSERT_TRUE(joinEnds->wait(2s))
1361 << "After server->shutdown() returns true, join() did not stop after 2s";
1362}
1363
Frederick Mayledc07cf82022-05-26 20:30:12 +00001364INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1365 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1366 ::testing::ValuesIn(testVersions())),
1367 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001368
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001369class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001370public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001371 // Only parameterized only server version because `RpcSession` is bypassed
1372 // in the client half of the tests.
1373 using Param =
1374 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001375 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001376
1377 // A server that handles client socket connections.
1378 class Server {
1379 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001380 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1381
Yifan Hong1deca4b2021-09-10 16:16:44 -07001382 explicit Server() {}
1383 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001384 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001385 [[nodiscard]] AssertionResult setUp(
1386 const Param& param,
1387 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001388 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001389 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001390 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001391 switch (socketType) {
1392 case SocketType::PRECONNECTED: {
1393 return AssertionFailure() << "Not supported by this test";
1394 } break;
1395 case SocketType::UNIX: {
1396 auto addr = allocateSocketAddress();
1397 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1398 if (status != OK) {
1399 return AssertionFailure()
1400 << "setupUnixDomainServer: " << statusToString(status);
1401 }
1402 mConnectToServer = [addr] {
1403 return connectTo(UnixSocketAddress(addr.c_str()));
1404 };
1405 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001406 case SocketType::UNIX_BOOTSTRAP: {
1407 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1408 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1409 return AssertionFailure() << "Socketpair() failed";
1410 }
1411 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1412 std::move(bootstrapFdServer));
1413 if (status != OK) {
1414 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1415 << statusToString(status);
1416 }
1417 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1418 mAcceptConnection = &Server::recvmsgServerConnection;
1419 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1420 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001421 case SocketType::UNIX_RAW: {
1422 auto addr = allocateSocketAddress();
1423 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1424 if (status != OK) {
1425 return AssertionFailure()
1426 << "setupRawSocketServer: " << statusToString(status);
1427 }
1428 mConnectToServer = [addr] {
1429 return connectTo(UnixSocketAddress(addr.c_str()));
1430 };
1431 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001432 case SocketType::VSOCK: {
1433 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001434 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001435 if (status != OK) {
1436 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1437 }
1438 mConnectToServer = [port] {
1439 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1440 };
1441 } break;
1442 case SocketType::INET: {
1443 unsigned int port;
1444 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1445 if (status != OK) {
1446 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1447 }
1448 mConnectToServer = [port] {
1449 const char* addr = kLocalInetAddress;
1450 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1451 if (aiStart == nullptr) return base::unique_fd{};
1452 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1453 auto fd = connectTo(
1454 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1455 if (fd.ok()) return fd;
1456 }
1457 ALOGE("None of the socket address resolved for %s:%u can be connected",
1458 addr, port);
1459 return base::unique_fd{};
1460 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001461 } break;
1462 case SocketType::TIPC: {
1463 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1464 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001465 }
1466 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001467 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00001468 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001469 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1470 mSetup = true;
1471 return AssertionSuccess();
1472 }
1473 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1474 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1475 return mCertVerifier;
1476 }
1477 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1478 void start() {
1479 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1480 mThread = std::make_unique<std::thread>(&Server::run, this);
1481 }
David Brazdil21c887c2022-09-23 12:25:18 +01001482
1483 base::unique_fd acceptServerConnection() {
1484 return base::unique_fd(TEMP_FAILURE_RETRY(
1485 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1486 }
1487
1488 base::unique_fd recvmsgServerConnection() {
1489 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1490 int buf;
1491 iovec iov{&buf, sizeof(buf)};
1492
1493 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1494 int savedErrno = errno;
1495 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1496 }
1497 if (fds.size() != 1) {
1498 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1499 }
1500 return std::move(std::get<base::unique_fd>(fds[0]));
1501 }
1502
Yifan Hong1deca4b2021-09-10 16:16:44 -07001503 void run() {
1504 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1505
1506 std::vector<std::thread> threads;
1507 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001508 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001509 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1510 }
1511
1512 for (auto& thread : threads) thread.join();
1513 }
1514 void handleOne(android::base::unique_fd acceptedFd) {
1515 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001516 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001517 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001518 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001519 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001520 }
Yifan Honge07d2732021-09-13 21:59:14 -07001521 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001522 shutdown();
1523 join();
1524 }
1525 void shutdown() { mFdTrigger->trigger(); }
1526
1527 void setPostConnect(
1528 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1529 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001530 }
1531
1532 private:
1533 std::unique_ptr<std::thread> mThread;
1534 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001535 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001536 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001537 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001538 std::unique_ptr<RpcTransportCtx> mCtx;
1539 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1540 std::make_shared<RpcCertificateVerifierSimple>();
1541 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001542 // The function invoked after connection and handshake. By default, it is
1543 // |defaultPostConnect| that sends |kMessage| to the client.
1544 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1545 Server::defaultPostConnect;
1546
1547 void join() {
1548 if (mThread != nullptr) {
1549 mThread->join();
1550 mThread = nullptr;
1551 }
1552 }
1553
1554 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1555 FdTrigger* fdTrigger) {
1556 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001557 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001558 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001559 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001560 if (status != OK) return AssertionFailure() << statusToString(status);
1561 return AssertionSuccess();
1562 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001563 };
1564
1565 class Client {
1566 public:
1567 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1568 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001569 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001570 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1571 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001572 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001573 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001574 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1575 return AssertionSuccess();
1576 }
1577 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1578 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1579 return mCertVerifier;
1580 }
Yifan Hong67519322021-09-13 18:51:16 -07001581 // connect() and do handshake
1582 bool setUpTransport() {
1583 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001584 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001585 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1586 return mClientTransport != nullptr;
1587 }
1588 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1589 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1590 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001591 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001592 status_t readStatus =
1593 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001594 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001595 if (readStatus != OK) {
1596 return AssertionFailure() << statusToString(readStatus);
1597 }
1598 if (readMessage != expectedMessage) {
1599 return AssertionFailure()
1600 << "Expected " << expectedMessage << ", actual " << readMessage;
1601 }
1602 return AssertionSuccess();
1603 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001604 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001605 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001606 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1607 return;
1608 }
1609 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001610 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001611 }
1612
Pawan49d74cb2022-08-03 21:19:11 +00001613 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1614
Yifan Hong1deca4b2021-09-10 16:16:44 -07001615 private:
1616 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001617 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001618 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1619 std::unique_ptr<RpcTransportCtx> mCtx;
1620 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1621 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001622 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001623 };
1624
1625 // Make A trust B.
1626 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001627 static status_t trust(RpcSecurity rpcSecurity,
1628 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1629 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001630 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001631 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1632 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1633 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001634 }
1635
1636 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001637};
1638
1639class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1640public:
1641 using Server = RpcTransportTestUtils::Server;
1642 using Client = RpcTransportTestUtils::Client;
1643 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001644 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001645 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001646 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001647 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001648 return ret;
1649 }
1650 static std::vector<ParamType> getRpcTranportTestParams() {
1651 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001652 for (auto serverVersion : testVersions()) {
1653 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1654 for (auto rpcSecurity : RpcSecurityValues()) {
1655 switch (rpcSecurity) {
1656 case RpcSecurity::RAW: {
1657 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1658 } break;
1659 case RpcSecurity::TLS: {
1660 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1661 serverVersion);
1662 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1663 serverVersion);
1664 } break;
1665 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001666 }
1667 }
1668 }
1669 return ret;
1670 }
1671 template <typename A, typename B>
1672 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001673 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1674 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001675 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1676 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001677 void SetUp() override {
1678 if constexpr (!kEnableRpcThreads) {
1679 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1680 }
1681 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001682};
1683
1684TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001685 auto server = std::make_unique<Server>();
1686 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001687
1688 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001689 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001690
1691 ASSERT_EQ(OK, trust(&client, server));
1692 ASSERT_EQ(OK, trust(server, &client));
1693
1694 server->start();
1695 client.run();
1696}
1697
1698TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001699 auto server = std::make_unique<Server>();
1700 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001701
1702 std::vector<Client> clients;
1703 for (int i = 0; i < 2; i++) {
1704 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001705 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001706 ASSERT_EQ(OK, trust(&client, server));
1707 ASSERT_EQ(OK, trust(server, &client));
1708 }
1709
1710 server->start();
1711 for (auto& client : clients) client.run();
1712}
1713
1714TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001715 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1716 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001717
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001718 auto untrustedServer = std::make_unique<Server>();
1719 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001720
1721 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001722 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001723
1724 ASSERT_EQ(OK, trust(untrustedServer, &client));
1725
1726 untrustedServer->start();
1727
1728 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1729 // the client can't verify the server's identity.
1730 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1731 client.run(handshakeOk);
1732}
1733TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001734 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1735 (void)serverVersion;
1736
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001737 auto validServer = std::make_unique<Server>();
1738 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001739
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001740 auto maliciousServer = std::make_unique<Server>();
1741 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001742
1743 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001744 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001745
1746 ASSERT_EQ(OK, trust(&client, validServer));
1747 ASSERT_EQ(OK, trust(validServer, &client));
1748 ASSERT_EQ(OK, trust(maliciousServer, &client));
1749
1750 maliciousServer->start();
1751
1752 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1753 // the client can't verify the server's identity.
1754 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1755 client.run(handshakeOk);
1756}
1757
1758TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001759 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1760 (void)serverVersion;
1761
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001762 auto server = std::make_unique<Server>();
1763 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001764
1765 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001766 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001767
1768 ASSERT_EQ(OK, trust(&client, server));
1769
1770 server->start();
1771
1772 // For TLS, Client should be able to verify server's identity, so client should see
1773 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1774 // identity and should drop the connection, so client shouldn't be able to read anything.
1775 bool readOk = rpcSecurity != RpcSecurity::TLS;
1776 client.run(true, readOk);
1777}
1778
1779TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001780 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1781 (void)serverVersion;
1782
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001783 auto server = std::make_unique<Server>();
1784 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001785
1786 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001787 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001788 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001789 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001790
1791 ASSERT_EQ(OK, trust(&validClient, server));
1792 ASSERT_EQ(OK, trust(&maliciousClient, server));
1793
1794 server->start();
1795
1796 // See UntrustedClient.
1797 bool readOk = rpcSecurity != RpcSecurity::TLS;
1798 maliciousClient.run(true, readOk);
1799}
1800
Yifan Hong67519322021-09-13 18:51:16 -07001801TEST_P(RpcTransportTest, Trigger) {
1802 std::string msg2 = ", world!";
1803 std::mutex writeMutex;
1804 std::condition_variable writeCv;
1805 bool shouldContinueWriting = false;
1806 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001807 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001808 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001809 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1810 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001811 if (status != OK) return AssertionFailure() << statusToString(status);
1812
1813 {
1814 std::unique_lock<std::mutex> lock(writeMutex);
1815 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1816 return AssertionFailure() << "write barrier not cleared in time!";
1817 }
1818 }
1819
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001820 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001821 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1822 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001823 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001824 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001825 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001826 << statusToString(status);
1827 return AssertionSuccess();
1828 };
1829
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001830 auto server = std::make_unique<Server>();
1831 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001832
1833 // Set up client
1834 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001835 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001836
1837 // Exchange keys
1838 ASSERT_EQ(OK, trust(&client, server));
1839 ASSERT_EQ(OK, trust(server, &client));
1840
1841 server->setPostConnect(serverPostConnect);
1842
Yifan Hong67519322021-09-13 18:51:16 -07001843 server->start();
1844 // connect() to server and do handshake
1845 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001846 // read the first message. This ensures that server has finished handshake and start handling
1847 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001848 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001849 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1850 // write is on an FdTrigger that has been shut down.
1851 server->shutdown();
1852 // Continues server thread to write the second message.
1853 {
Yifan Hong22211f82021-09-14 12:32:25 -07001854 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001855 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001856 }
Yifan Hong22211f82021-09-14 12:32:25 -07001857 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001858 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001859 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001860 // On the client side, second read fails with DEAD_OBJECT
1861 ASSERT_FALSE(client.readMessage(msg2));
1862}
1863
Pawan49d74cb2022-08-03 21:19:11 +00001864TEST_P(RpcTransportTest, CheckWaitingForRead) {
1865 std::mutex readMutex;
1866 std::condition_variable readCv;
1867 bool shouldContinueReading = false;
1868 // Server will write data on transport once its started
1869 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1870 std::string message(RpcTransportTestUtils::kMessage);
1871 iovec messageIov{message.data(), message.size()};
1872 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1873 std::nullopt, nullptr);
1874 if (status != OK) return AssertionFailure() << statusToString(status);
1875
1876 {
1877 std::unique_lock<std::mutex> lock(readMutex);
1878 shouldContinueReading = true;
1879 lock.unlock();
1880 readCv.notify_all();
1881 }
1882 return AssertionSuccess();
1883 };
1884
1885 // Setup Server and client
1886 auto server = std::make_unique<Server>();
1887 ASSERT_TRUE(server->setUp(GetParam()));
1888
1889 Client client(server->getConnectToServerFn());
1890 ASSERT_TRUE(client.setUp(GetParam()));
1891
1892 ASSERT_EQ(OK, trust(&client, server));
1893 ASSERT_EQ(OK, trust(server, &client));
1894 server->setPostConnect(serverPostConnect);
1895
1896 server->start();
1897 ASSERT_TRUE(client.setUpTransport());
1898 {
1899 // Wait till server writes data
1900 std::unique_lock<std::mutex> lock(readMutex);
1901 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1902 }
1903
1904 // Since there is no read polling here, we will get polling count 0
1905 ASSERT_FALSE(client.isTransportWaiting());
1906 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1907 // Thread should increment polling count, read and decrement polling count
1908 // Again, polling count should be zero here
1909 ASSERT_FALSE(client.isTransportWaiting());
1910
1911 server->shutdown();
1912}
1913
Yifan Hong1deca4b2021-09-10 16:16:44 -07001914INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001915 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001916 RpcTransportTest::PrintParamInfo);
1917
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001918class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001919 : public testing::TestWithParam<
1920 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001921public:
1922 template <typename A, typename B>
1923 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001924 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1925 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001926 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1927 }
1928 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001929 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1930 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1931 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001932 };
1933};
1934
1935TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001936 if constexpr (!kEnableRpcThreads) {
1937 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1938 }
1939
Frederick Mayledc07cf82022-05-26 20:30:12 +00001940 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001941
1942 std::vector<uint8_t> pkeyData, certData;
1943 {
1944 auto pkey = makeKeyPairForSelfSignedCert();
1945 ASSERT_NE(nullptr, pkey);
1946 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1947 ASSERT_NE(nullptr, cert);
1948 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1949 certData = serializeCertificate(cert.get(), certificateFormat);
1950 }
1951
1952 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1953 auto desCert = deserializeCertificate(certData, certificateFormat);
1954 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001955 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1956 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001957
1958 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1959 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1960
1961 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1962 ASSERT_TRUE(client.setUp(utilsParam));
1963
1964 ASSERT_EQ(OK, trust(&client, server));
1965 ASSERT_EQ(OK, trust(server, &client));
1966
1967 server->start();
1968 client.run();
1969}
1970
1971INSTANTIATE_TEST_CASE_P(
1972 BinderRpc, RpcTransportTlsKeyTest,
1973 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1974 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001975 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1976 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001977 RpcTransportTlsKeyTest::PrintParamInfo);
1978
Steven Morelandc1635952021-04-01 16:20:47 +00001979} // namespace android
1980
1981int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001982 ::testing::InitGoogleTest(&argc, argv);
1983 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07001984
Steven Moreland5553ac42020-11-11 02:14:45 +00001985 return RUN_ALL_TESTS();
1986}