blob: 8d1def138474bafd940e90b761f79cfbe5e94449 [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 Homescud65666d2023-03-03 07:28:02 +000031#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000032#include <binder/RpcTransportTipcAndroid.h>
33#include <trusty/tipc.h>
Andrei Homescud65666d2023-03-03 07:28:02 +000034#endif // BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000035
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 Homescud65666d2023-03-03 07:28:02 +000053#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000054constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
55#endif
56
Frederick Maylea12b0962022-06-25 01:13:22 +000057static std::string WaitStatusToString(int wstatus) {
58 if (WIFEXITED(wstatus)) {
59 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
60 }
61 if (WIFSIGNALED(wstatus)) {
62 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
63 }
64 return base::StringPrintf("unexpected state %d", wstatus);
65}
66
Steven Moreland276d8df2022-09-28 23:56:39 +000067static void debugBacktrace(pid_t pid) {
68 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
69 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
70}
71
Steven Moreland5553ac42020-11-11 02:14:45 +000072class Process {
73public:
Andrei Homescu96834632022-10-14 00:49:49 +000074 Process(Process&& other)
75 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
76 mReadEnd(std::move(other.mReadEnd)),
77 mWriteEnd(std::move(other.mWriteEnd)) {
78 // The default move constructor doesn't clear mPid after moving it,
79 // which we need to do because the destructor checks for mPid!=0
80 mPid = other.mPid;
81 other.mPid = 0;
82 }
Yifan Hong1deca4b2021-09-10 16:16:44 -070083 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
84 android::base::borrowed_fd /* readEnd */)>& f) {
85 android::base::unique_fd childWriteEnd;
86 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +000087 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
88 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +000089 if (0 == (mPid = fork())) {
90 // racey: assume parent doesn't crash before this is set
91 prctl(PR_SET_PDEATHSIG, SIGHUP);
92
Yifan Hong1deca4b2021-09-10 16:16:44 -070093 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +000094
95 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +000096 }
97 }
98 ~Process() {
99 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000100 int wstatus;
101 waitpid(mPid, &wstatus, 0);
102 if (mCustomExitStatusCheck) {
103 mCustomExitStatusCheck(wstatus);
104 } else {
105 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
106 << "server process failed: " << WaitStatusToString(wstatus);
107 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000108 }
109 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700110 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700111 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000112
Frederick Maylea12b0962022-06-25 01:13:22 +0000113 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
114 mCustomExitStatusCheck = std::move(f);
115 }
116
Frederick Mayle69a0c992022-05-26 20:38:39 +0000117 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
118 void terminate() { kill(mPid, SIGTERM); }
119
Steven Moreland276d8df2022-09-28 23:56:39 +0000120 pid_t getPid() { return mPid; }
121
Steven Moreland5553ac42020-11-11 02:14:45 +0000122private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000123 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000124 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700125 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700126 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000127};
128
129static std::string allocateSocketAddress() {
130 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000131 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000132 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700133 unlink(ret.c_str());
134 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000135};
136
Steven Morelandda573042021-06-12 01:13:45 +0000137static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000138 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000139 return vsockPort++;
140}
141
Alice Wang893a9912022-10-24 10:44:09 +0000142static base::unique_fd initUnixSocket(std::string addr) {
143 auto socket_addr = UnixSocketAddress(addr.c_str());
144 base::unique_fd fd(
145 TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
146 CHECK(fd.ok());
147 CHECK_EQ(0, TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize())));
148 return fd;
149}
150
Andrei Homescu96834632022-10-14 00:49:49 +0000151// Destructors need to be defined, even if pure virtual
152ProcessSession::~ProcessSession() {}
153
154class LinuxProcessSession : public ProcessSession {
155public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000156 // reference to process hosting a socket server
157 Process host;
158
Andrei Homescu96834632022-10-14 00:49:49 +0000159 LinuxProcessSession(LinuxProcessSession&&) = default;
160 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
161 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000162 for (auto& session : sessions) {
163 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000164 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000165
Steven Moreland67f85902023-03-15 01:13:49 +0000166 for (size_t sessionNum = 0; sessionNum < sessions.size(); sessionNum++) {
167 auto& info = sessions.at(sessionNum);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000168 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000169
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000170 EXPECT_NE(nullptr, session);
171 EXPECT_NE(nullptr, session->state());
172 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000173
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000174 wp<RpcSession> weakSession = session;
175 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000176
Steven Moreland57042712022-10-04 23:56:45 +0000177 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
178 // the object should not actually be promotable. By looping, we distinguish a race here
179 // from a bug causing the object to not be promotable.
180 for (size_t i = 0; i < 3; i++) {
181 sp<RpcSession> strongSession = weakSession.promote();
182 EXPECT_EQ(nullptr, strongSession)
Steven Moreland67f85902023-03-15 01:13:49 +0000183 << "For session " << sessionNum << ". "
Steven Moreland57042712022-10-04 23:56:45 +0000184 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
185 "Leaked sess: ")
186 << strongSession->getStrongCount() << " checked time " << i;
187
188 if (strongSession != nullptr) {
189 sleep(1);
190 }
191 }
Steven Moreland736664b2021-05-01 04:27:25 +0000192 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000193 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000194
Andrei Homescu96834632022-10-14 00:49:49 +0000195 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
196 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000197 }
Andrei Homescu96834632022-10-14 00:49:49 +0000198
199 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000200};
201
Yifan Hong1deca4b2021-09-10 16:16:44 -0700202static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700203 base::unique_fd serverFd(
204 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
205 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700206 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
207 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700208
209 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
210 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700211 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
212 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700213 }
214 return serverFd;
215}
216
Andrei Homescud65666d2023-03-03 07:28:02 +0000217#ifndef BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100218static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
219 base::unique_fd sockClient, sockServer;
220 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
221 int savedErrno = errno;
222 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
223 }
224
225 int zero = 0;
226 iovec iov{&zero, sizeof(zero)};
227 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
228 fds.emplace_back(std::move(sockServer));
229
230 if (sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
231 int savedErrno = errno;
232 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
233 }
234 return std::move(sockClient);
235}
Andrei Homescud65666d2023-03-03 07:28:02 +0000236#endif // BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100237
Andrei Homescuf30148c2023-03-10 00:31:45 +0000238std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
239 return newTlsFactory(rpcSecurity);
Andrei Homescu96834632022-10-14 00:49:49 +0000240}
Andrei Homescu2a298012022-06-15 01:08:54 +0000241
Andrei Homescu96834632022-10-14 00:49:49 +0000242// This creates a new process serving an interface on a certain number of
243// threads.
244std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
245 const BinderRpcOptions& options) {
246 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000247
Steven Moreland67f85902023-03-15 01:13:49 +0000248 if (options.numIncomingConnectionsBySession.size() != 0) {
249 CHECK_EQ(options.numIncomingConnectionsBySession.size(), options.numSessions);
250 }
251
Andrei Homescu96834632022-10-14 00:49:49 +0000252 SocketType socketType = std::get<0>(GetParam());
253 RpcSecurity rpcSecurity = std::get<1>(GetParam());
254 uint32_t clientVersion = std::get<2>(GetParam());
255 uint32_t serverVersion = std::get<3>(GetParam());
256 bool singleThreaded = std::get<4>(GetParam());
257 bool noKernel = std::get<5>(GetParam());
258
259 std::string path = android::base::GetExecutableDirectory();
260 auto servicePath = android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
261 singleThreaded ? "_single_threaded" : "",
262 noKernel ? "_no_kernel" : "");
263
Alice Wang1ef010b2022-11-14 09:09:25 +0000264 base::unique_fd bootstrapClientFd, socketFd;
265
Alice Wang893a9912022-10-24 10:44:09 +0000266 auto addr = allocateSocketAddress();
267 // Initializes the socket before the fork/exec.
268 if (socketType == SocketType::UNIX_RAW) {
269 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000270 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
271 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
272 // This is because we cannot pass ParcelFileDescriptor over a pipe.
273 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
274 int savedErrno = errno;
275 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
276 }
Alice Wang893a9912022-10-24 10:44:09 +0000277 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000278
Andrei Homescu96834632022-10-14 00:49:49 +0000279 auto ret = std::make_unique<LinuxProcessSession>(
280 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000281 if (socketType == SocketType::TIPC) {
282 // Trusty has a single persistent service
283 return;
284 }
285
Andrei Homescu96834632022-10-14 00:49:49 +0000286 auto writeFd = std::to_string(writeEnd.get());
287 auto readFd = std::to_string(readEnd.get());
288 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
289 NULL);
290 }));
291
292 BinderRpcTestServerConfig serverConfig;
293 serverConfig.numThreads = options.numThreads;
294 serverConfig.socketType = static_cast<int32_t>(socketType);
295 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
296 serverConfig.serverVersion = serverVersion;
297 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000298 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000299 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000300 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
301 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
302 static_cast<int32_t>(mode));
303 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000304 if (socketType != SocketType::TIPC) {
305 writeToFd(ret->host.writeEnd(), serverConfig);
306 }
Andrei Homescu96834632022-10-14 00:49:49 +0000307
308 std::vector<sp<RpcSession>> sessions;
309 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
310 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000311 std::unique_ptr<RpcTransportCtxFactory> factory;
312 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000313#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000314 factory = RpcTransportCtxFactoryTipcAndroid::make();
315#else
316 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
317#endif
318 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000319 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000320 }
321 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100322 }
323
Andrei Homescu68a55612022-08-02 01:25:15 +0000324 BinderRpcTestServerInfo serverInfo;
325 if (socketType != SocketType::TIPC) {
326 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
327 BinderRpcTestClientInfo clientInfo;
328 for (const auto& session : sessions) {
329 auto& parcelableCert = clientInfo.certs.emplace_back();
330 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
331 }
332 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000333
Andrei Homescu68a55612022-08-02 01:25:15 +0000334 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
335 if (socketType == SocketType::INET) {
336 CHECK_NE(0, serverInfo.port);
337 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000338
Andrei Homescu68a55612022-08-02 01:25:15 +0000339 if (rpcSecurity == RpcSecurity::TLS) {
340 const auto& serverCert = serverInfo.cert.data;
341 CHECK_EQ(OK,
342 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
343 serverCert));
344 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700345 }
346
Andrei Homescu96834632022-10-14 00:49:49 +0000347 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000348
Steven Moreland67f85902023-03-15 01:13:49 +0000349 for (size_t i = 0; i < sessions.size(); i++) {
350 const auto& session = sessions.at(i);
351
352 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
353 ? options.numIncomingConnectionsBySession.at(i)
354 : 0;
355
Andrei Homescu96834632022-10-14 00:49:49 +0000356 CHECK(session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000357 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000358 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000359 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000360
Andrei Homescu96834632022-10-14 00:49:49 +0000361 switch (socketType) {
362 case SocketType::PRECONNECTED:
363 status = session->setupPreconnectedClient({}, [=]() {
364 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
365 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000366 break;
Alice Wang893a9912022-10-24 10:44:09 +0000367 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000368 case SocketType::UNIX:
369 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
370 break;
371 case SocketType::UNIX_BOOTSTRAP:
372 status = session->setupUnixDomainSocketBootstrapClient(
373 base::unique_fd(dup(bootstrapClientFd.get())));
374 break;
375 case SocketType::VSOCK:
376 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
377 break;
378 case SocketType::INET:
379 status = session->setupInetClient("127.0.0.1", serverInfo.port);
380 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000381 case SocketType::TIPC:
382 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000383#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000384 auto port = trustyIpcPort(serverVersion);
385 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
386 return tipcFd >= 0 ? android::base::unique_fd(tipcFd)
387 : android::base::unique_fd();
388#else
389 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
390 return android::base::unique_fd();
391#endif
392 });
393 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000394 default:
395 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000396 }
Andrei Homescu96834632022-10-14 00:49:49 +0000397 if (options.allowConnectFailure && status != OK) {
398 ret->sessions.clear();
399 break;
400 }
401 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
402 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000403 }
Andrei Homescu96834632022-10-14 00:49:49 +0000404 return ret;
405}
Steven Morelandc1635952021-04-01 16:20:47 +0000406
Andrei Homescua858b0e2022-08-01 23:43:09 +0000407TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
408 if (clientOrServerSingleThreaded()) {
409 GTEST_SKIP() << "This test requires multiple threads";
410 }
411
Steven Moreland5553ac42020-11-11 02:14:45 +0000412 constexpr size_t kNumThreads = 10;
413
Steven Moreland4313d7e2021-07-15 23:41:22 +0000414 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000415
416 EXPECT_OK(proc.rootIface->lock());
417
418 // block all but one thread taking locks
419 std::vector<std::thread> ts;
420 for (size_t i = 0; i < kNumThreads - 1; i++) {
421 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
422 }
423
Steven Morelandd6d816f2022-12-23 01:37:17 +0000424 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000425
426 // other calls still work
427 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
428
Steven Morelandd6d816f2022-12-23 01:37:17 +0000429 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000430 size_t epochMsBefore = epochMillis();
431 // after this, we should never see a response within this time
432 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
433
434 // this call should be blocked for blockTimeMs
435 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
436
437 size_t epochMsAfter = epochMillis();
438 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
439
440 for (auto& t : ts) t.join();
441}
442
Steven Moreland27f620a2023-03-06 19:44:36 +0000443static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000444 size_t epochMsBefore = epochMillis();
445
446 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700447 for (size_t i = 0; i < numCalls; i++) {
448 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000449 }
450
451 for (auto& t : ts) t.join();
452
453 size_t epochMsAfter = epochMillis();
454
Yifan Hong1f44f982021-10-08 17:16:47 -0700455 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000456
457 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700458 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
459}
460
Andrei Homescua858b0e2022-08-01 23:43:09 +0000461TEST_P(BinderRpc, ThreadPoolOverSaturated) {
462 if (clientOrServerSingleThreaded()) {
463 GTEST_SKIP() << "This test requires multiple threads";
464 }
465
Yifan Hong1f44f982021-10-08 17:16:47 -0700466 constexpr size_t kNumThreads = 10;
467 constexpr size_t kNumCalls = kNumThreads + 3;
468 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000469
470 // b/272429574 - below 500ms, the test fails
471 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700472}
473
Andrei Homescua858b0e2022-08-01 23:43:09 +0000474TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
475 if (clientOrServerSingleThreaded()) {
476 GTEST_SKIP() << "This test requires multiple threads";
477 }
478
Yifan Hong1f44f982021-10-08 17:16:47 -0700479 constexpr size_t kNumThreads = 20;
480 constexpr size_t kNumOutgoingConnections = 10;
481 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
482 auto proc = createRpcTestSocketServerProcess(
483 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000484
485 // b/272429574 - below 500ms, the test fails
486 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000487}
488
Andrei Homescua858b0e2022-08-01 23:43:09 +0000489TEST_P(BinderRpc, ThreadingStressTest) {
490 if (clientOrServerSingleThreaded()) {
491 GTEST_SKIP() << "This test requires multiple threads";
492 }
493
Steven Moreland27f620a2023-03-06 19:44:36 +0000494 constexpr size_t kNumClientThreads = 5;
495 constexpr size_t kNumServerThreads = 5;
496 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000497
Steven Moreland4313d7e2021-07-15 23:41:22 +0000498 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000499
500 std::vector<std::thread> threads;
501 for (size_t i = 0; i < kNumClientThreads; i++) {
502 threads.push_back(std::thread([&] {
503 for (size_t j = 0; j < kNumCalls; j++) {
504 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000505 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000506 EXPECT_EQ(proc.rootBinder, out);
507 }
508 }));
509 }
510
511 for (auto& t : threads) t.join();
512}
513
Steven Moreland925ba0a2021-09-17 18:06:32 -0700514static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
515 std::vector<std::thread> threads;
516 for (size_t i = 0; i < threadCount; i++) {
517 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
518 }
519 for (auto& t : threads) t.join();
520}
521
Andrei Homescua858b0e2022-08-01 23:43:09 +0000522TEST_P(BinderRpc, OnewayStressTest) {
523 if (clientOrServerSingleThreaded()) {
524 GTEST_SKIP() << "This test requires multiple threads";
525 }
526
Steven Morelandc6046982021-04-20 00:49:42 +0000527 constexpr size_t kNumClientThreads = 10;
528 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700529 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000530
Steven Moreland4313d7e2021-07-15 23:41:22 +0000531 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000532
533 std::vector<std::thread> threads;
534 for (size_t i = 0; i < kNumClientThreads; i++) {
535 threads.push_back(std::thread([&] {
536 for (size_t j = 0; j < kNumCalls; j++) {
537 EXPECT_OK(proc.rootIface->sendString("a"));
538 }
Steven Morelandc6046982021-04-20 00:49:42 +0000539 }));
540 }
541
542 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700543
544 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000545}
546
Frederick Mayleb0221d12022-10-03 23:10:53 +0000547TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
548 if (!supportsFdTransport()) {
549 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
550 }
551 if (clientOrServerSingleThreaded()) {
552 GTEST_SKIP() << "This test requires multiple threads";
553 }
554
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000555 constexpr size_t kNumServerThreads = 3;
556
Frederick Mayleb0221d12022-10-03 23:10:53 +0000557 // This test forces a oneway transaction to be queued by issuing two
558 // `blockingSendFdOneway` calls, then drains the queue by issuing two
559 // `blockingRecvFd` calls.
560 //
561 // For more details about the queuing semantics see
562 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
563
564 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000565 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000566 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
567 .serverSupportedFileDescriptorTransportModes =
568 {RpcSession::FileDescriptorTransportMode::UNIX},
569 });
570
571 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
572 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
573 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
574 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
575
576 android::os::ParcelFileDescriptor fdA;
577 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
578 std::string result;
579 CHECK(android::base::ReadFdToString(fdA.get(), &result));
580 EXPECT_EQ(result, "a");
581
582 android::os::ParcelFileDescriptor fdB;
583 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
584 CHECK(android::base::ReadFdToString(fdB.get(), &result));
585 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000586
587 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000588}
589
Andrei Homescua858b0e2022-08-01 23:43:09 +0000590TEST_P(BinderRpc, OnewayCallQueueing) {
591 if (clientOrServerSingleThreaded()) {
592 GTEST_SKIP() << "This test requires multiple threads";
593 }
594
Frederick Mayle96872592023-03-07 14:56:15 -0800595 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000596 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000597
598 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000599 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000600
Frederick Mayle96872592023-03-07 14:56:15 -0800601 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700602 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800603 for (size_t i = 0; i + 1 < kNumQueued; i++) {
604 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000605 }
Frederick Mayle96872592023-03-07 14:56:15 -0800606 for (size_t i = 0; i + 1 < kNumQueued; i++) {
607 int n;
608 proc.rootIface->blockingRecvInt(&n);
609 EXPECT_EQ(n, i);
610 }
Steven Morelandf5174272021-05-25 00:39:28 +0000611
Steven Moreland925ba0a2021-09-17 18:06:32 -0700612 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000613}
614
Andrei Homescua858b0e2022-08-01 23:43:09 +0000615TEST_P(BinderRpc, OnewayCallExhaustion) {
616 if (clientOrServerSingleThreaded()) {
617 GTEST_SKIP() << "This test requires multiple threads";
618 }
619
Steven Morelandd45be622021-06-04 02:19:37 +0000620 constexpr size_t kNumClients = 2;
621 constexpr size_t kTooLongMs = 1000;
622
Steven Moreland4313d7e2021-07-15 23:41:22 +0000623 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000624
625 // Build up oneway calls on the second session to make sure it terminates
626 // and shuts down. The first session should be unaffected (proc destructor
627 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000628 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000629
630 std::vector<std::thread> threads;
631 for (size_t i = 0; i < kNumClients; i++) {
632 // one of these threads will get stuck queueing a transaction once the
633 // socket fills up, the other will be able to fill up transactions on
634 // this object
635 threads.push_back(std::thread([&] {
636 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
637 }
638 }));
639 }
640 for (auto& t : threads) t.join();
641
642 Status status = iface->sleepMsAsync(kTooLongMs);
643 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
644
Steven Moreland798e0d12021-07-14 23:19:25 +0000645 // now that it has died, wait for the remote session to shutdown
646 std::vector<int32_t> remoteCounts;
647 do {
648 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
649 } while (remoteCounts.size() == kNumClients);
650
Steven Morelandd45be622021-06-04 02:19:37 +0000651 // the second session should be shutdown in the other process by the time we
652 // are able to join above (it'll only be hung up once it finishes processing
653 // any pending commands). We need to erase this session from the record
654 // here, so that the destructor for our session won't check that this
655 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000656 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000657}
658
Steven Moreland67f85902023-03-15 01:13:49 +0000659TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
660 if (clientOrServerSingleThreaded()) {
661 GTEST_SKIP() << "This test requires multiple threads";
662 }
663
664 // session 0 - will check for leaks in destrutor of proc
665 // session 1 - we want to make sure it gets deleted when we drop all references to it
666 auto proc = createRpcTestSocketServerProcess(
667 {.numThreads = 1, .numIncomingConnectionsBySession = {0, 1}, .numSessions = 2});
668
669 wp<RpcSession> session = proc.proc->sessions.at(1).session;
670
671 // remove all references to the second session
672 proc.proc->sessions.at(1).root = nullptr;
673 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
674
675 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
676 // to drain commands.
677 for (size_t i = 0; i < 100; i++) {
678 usleep(10 * 1000);
679 if (session.promote() == nullptr) break;
680 }
681
682 EXPECT_EQ(nullptr, session.promote());
683}
684
Devin Moore66d5b7a2022-07-07 21:42:10 +0000685TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000686 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000687 GTEST_SKIP() << "This test requires multiple threads";
688 }
689 class MyDeathRec : public IBinder::DeathRecipient {
690 public:
691 void binderDied(const wp<IBinder>& /* who */) override {
692 dead = true;
693 mCv.notify_one();
694 }
695 std::mutex mMtx;
696 std::condition_variable mCv;
697 bool dead = false;
698 };
699
700 // Death recipient needs to have an incoming connection to be called
701 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000702 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000703
704 auto dr = sp<MyDeathRec>::make();
705 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
706
707 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
708 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
709 }
710
711 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000712 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000713
714 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000715 // can't do this before checking the death recipient by calling
716 // forceShutdown earlier, because shutdownAndWait will also trigger
717 // a death recipient, but if we had a way to wait for the service
718 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000719 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000720 proc.expectAlreadyShutdown = true;
721}
722
723TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000724 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000725 GTEST_SKIP() << "This test requires multiple threads";
726 }
727 class MyDeathRec : public IBinder::DeathRecipient {
728 public:
729 void binderDied(const wp<IBinder>& /* who */) override {
730 dead = true;
731 mCv.notify_one();
732 }
733 std::mutex mMtx;
734 std::condition_variable mCv;
735 bool dead = false;
736 };
737
738 // Death recipient needs to have an incoming connection to be called
739 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000740 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000741
742 auto dr = sp<MyDeathRec>::make();
743 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
744
745 // Explicitly calling shutDownAndWait will cause the death recipients
746 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000747 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000748
749 std::unique_lock<std::mutex> lock(dr->mMtx);
750 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000751 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000752 }
753 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
754
Andrei Homescu96834632022-10-14 00:49:49 +0000755 proc.proc->terminate();
756 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000757 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
758 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
759 });
760 proc.expectAlreadyShutdown = true;
761}
762
Steven Moreland5ec743f2023-01-18 01:02:06 +0000763TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000764 if (socketType() == SocketType::TIPC) {
765 // This should work, but Trusty takes too long to restart the service
766 GTEST_SKIP() << "Service death test not supported on Trusty";
767 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000768 class MyDeathRec : public IBinder::DeathRecipient {
769 public:
770 void binderDied(const wp<IBinder>& /* who */) override {}
771 };
772
Steven Moreland67f85902023-03-15 01:13:49 +0000773 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000774
775 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000776 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000777}
778
779TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000780 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000781 GTEST_SKIP() << "This test requires multiple threads";
782 }
783 class MyDeathRec : public IBinder::DeathRecipient {
784 public:
785 void binderDied(const wp<IBinder>& /* who */) override {
786 GTEST_FAIL() << "This should not be called after unlinkToDeath";
787 }
788 };
789
790 // Death recipient needs to have an incoming connection to be called
791 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000792 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000793
794 auto dr = sp<MyDeathRec>::make();
795 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
796 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
797
Steven Moreland67f85902023-03-15 01:13:49 +0000798 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000799}
800
Steven Morelandc1635952021-04-01 16:20:47 +0000801TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000802 if (socketType() == SocketType::TIPC) {
803 // This should work, but Trusty takes too long to restart the service
804 GTEST_SKIP() << "Service death test not supported on Trusty";
805 }
806
Steven Moreland5553ac42020-11-11 02:14:45 +0000807 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000808 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000809
810 // make sure there is some state during crash
811 // 1. we hold their binder
812 sp<IBinderRpcSession> session;
813 EXPECT_OK(proc.rootIface->openSession("happy", &session));
814 // 2. they hold our binder
815 sp<IBinder> binder = new BBinder();
816 EXPECT_OK(proc.rootIface->holdBinder(binder));
817
818 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
819 << "Do death cleanup: " << doDeathCleanup;
820
Andrei Homescu96834632022-10-14 00:49:49 +0000821 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000822 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
823 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
824 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000825 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000826 }
827}
828
Steven Morelandd7302072021-05-15 01:32:04 +0000829TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000830 // This test only works if the current process shared the internal state of
831 // ProcessState with the service across the call to fork(). Both the static
832 // libraries and libbinder.so have their own separate copies of all the
833 // globals, so the test only works when the test client and service both use
834 // libbinder.so (when using static libraries, even a client and service
835 // using the same kind of static library should have separate copies of the
836 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000837 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000838 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
839 "at build time.";
840 }
841
Steven Moreland4313d7e2021-07-15 23:41:22 +0000842 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000843
Andrei Homescu2a298012022-06-15 01:08:54 +0000844 // we can't allocate IPCThreadState so actually the first time should
845 // succeed :(
846 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000847
848 // second time! we catch the error :)
849 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
850
Andrei Homescu96834632022-10-14 00:49:49 +0000851 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000852 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
853 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
854 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000855 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000856}
857
Frederick Mayle69a0c992022-05-26 20:38:39 +0000858TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000859 if (socketType() == SocketType::TIPC) {
860 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
861 }
862
Frederick Mayle69a0c992022-05-26 20:38:39 +0000863 auto proc = createRpcTestSocketServerProcess({
864 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
865 .serverSupportedFileDescriptorTransportModes =
866 {RpcSession::FileDescriptorTransportMode::UNIX},
867 .allowConnectFailure = true,
868 });
Andrei Homescu96834632022-10-14 00:49:49 +0000869 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
870 proc.proc->terminate();
871 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000872 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
873 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
874 });
875 proc.expectAlreadyShutdown = true;
876}
877
878TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000879 if (socketType() == SocketType::TIPC) {
880 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
881 }
882
Frederick Mayle69a0c992022-05-26 20:38:39 +0000883 auto proc = createRpcTestSocketServerProcess({
884 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
885 .serverSupportedFileDescriptorTransportModes =
886 {RpcSession::FileDescriptorTransportMode::NONE},
887 .allowConnectFailure = true,
888 });
Andrei Homescu96834632022-10-14 00:49:49 +0000889 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
890 proc.proc->terminate();
891 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000892 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
893 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
894 });
895 proc.expectAlreadyShutdown = true;
896}
897
898TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000899 if (socketType() == SocketType::TIPC) {
900 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
901 }
902
Frederick Mayle69a0c992022-05-26 20:38:39 +0000903 auto proc = createRpcTestSocketServerProcess({
904 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
905 .serverSupportedFileDescriptorTransportModes =
906 {RpcSession::FileDescriptorTransportMode::NONE,
907 RpcSession::FileDescriptorTransportMode::UNIX},
908 });
909
910 android::os::ParcelFileDescriptor out;
911 auto status = proc.rootIface->echoAsFile("hello", &out);
912 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
913}
914
915TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000916 if (socketType() == SocketType::TIPC) {
917 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
918 }
919
Frederick Mayle69a0c992022-05-26 20:38:39 +0000920 auto proc = createRpcTestSocketServerProcess({
921 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
922 .serverSupportedFileDescriptorTransportModes =
923 {RpcSession::FileDescriptorTransportMode::UNIX},
924 });
925
926 android::os::ParcelFileDescriptor out;
927 auto status = proc.rootIface->echoAsFile("hello", &out);
928 if (!supportsFdTransport()) {
929 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
930 return;
931 }
932 ASSERT_TRUE(status.isOk()) << status;
933
934 std::string result;
935 CHECK(android::base::ReadFdToString(out.get(), &result));
936 EXPECT_EQ(result, "hello");
937}
938
939TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000940 if (socketType() == SocketType::TIPC) {
941 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
942 }
943
Frederick Mayle69a0c992022-05-26 20:38:39 +0000944 auto proc = createRpcTestSocketServerProcess({
945 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
946 .serverSupportedFileDescriptorTransportModes =
947 {RpcSession::FileDescriptorTransportMode::UNIX},
948 });
949
950 std::vector<android::os::ParcelFileDescriptor> files;
951 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
952 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
953 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
954 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
955
956 android::os::ParcelFileDescriptor out;
957 auto status = proc.rootIface->concatFiles(files, &out);
958 if (!supportsFdTransport()) {
959 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
960 return;
961 }
962 ASSERT_TRUE(status.isOk()) << status;
963
964 std::string result;
965 CHECK(android::base::ReadFdToString(out.get(), &result));
966 EXPECT_EQ(result, "123abcd");
967}
968
969TEST_P(BinderRpc, SendMaxFiles) {
970 if (!supportsFdTransport()) {
971 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
972 }
973
974 auto proc = createRpcTestSocketServerProcess({
975 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
976 .serverSupportedFileDescriptorTransportModes =
977 {RpcSession::FileDescriptorTransportMode::UNIX},
978 });
979
980 std::vector<android::os::ParcelFileDescriptor> files;
981 for (int i = 0; i < 253; i++) {
982 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
983 }
984
985 android::os::ParcelFileDescriptor out;
986 auto status = proc.rootIface->concatFiles(files, &out);
987 ASSERT_TRUE(status.isOk()) << status;
988
989 std::string result;
990 CHECK(android::base::ReadFdToString(out.get(), &result));
991 EXPECT_EQ(result, std::string(253, 'a'));
992}
993
994TEST_P(BinderRpc, SendTooManyFiles) {
995 if (!supportsFdTransport()) {
996 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
997 }
998
999 auto proc = createRpcTestSocketServerProcess({
1000 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1001 .serverSupportedFileDescriptorTransportModes =
1002 {RpcSession::FileDescriptorTransportMode::UNIX},
1003 });
1004
1005 std::vector<android::os::ParcelFileDescriptor> files;
1006 for (int i = 0; i < 254; i++) {
1007 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1008 }
1009
1010 android::os::ParcelFileDescriptor out;
1011 auto status = proc.rootIface->concatFiles(files, &out);
1012 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1013}
1014
Andrei Homescufc221502022-10-08 03:51:17 +00001015TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001016 if (socketType() == SocketType::TIPC) {
1017 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1018 }
1019
Andrei Homescufc221502022-10-08 03:51:17 +00001020 auto proc = createRpcTestSocketServerProcess({
1021 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1022 .serverSupportedFileDescriptorTransportModes =
1023 {RpcSession::FileDescriptorTransportMode::UNIX},
1024 });
1025
1026 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1027 ASSERT_NE(badFd, -1);
1028
1029 // Close the file descriptor so it becomes invalid for dup
1030 close(badFd);
1031
1032 Parcel p1;
1033 p1.markForBinder(proc.rootBinder);
1034 p1.writeInt32(3);
1035 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1036
1037 Parcel pRaw;
1038 pRaw.markForBinder(proc.rootBinder);
1039 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1040
1041 pRaw.setDataPosition(0);
1042 EXPECT_EQ(3, pRaw.readInt32());
1043 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1044}
1045
Andrei Homescu68a55612022-08-02 01:25:15 +00001046#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001047TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001048 if constexpr (!kEnableSharedLibs) {
1049 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1050 }
1051
Steven Moreland4313d7e2021-07-15 23:41:22 +00001052 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001053
1054 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1055 ASSERT_NE(binder, nullptr);
1056
1057 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1058}
1059
1060TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001061 if constexpr (!kEnableSharedLibs) {
1062 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1063 }
1064
Steven Moreland4313d7e2021-07-15 23:41:22 +00001065 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001066
1067 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1068 ASSERT_NE(binder, nullptr);
1069
1070 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1071 ASSERT_NE(ndkBinder, nullptr);
1072
1073 std::string out;
1074 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1075 ASSERT_TRUE(status.isOk()) << status.getDescription();
1076 ASSERT_EQ("aoeuaoeu", out);
1077}
Andrei Homescu68a55612022-08-02 01:25:15 +00001078#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001079
Steven Moreland5553ac42020-11-11 02:14:45 +00001080ssize_t countFds() {
1081 DIR* dir = opendir("/proc/self/fd/");
1082 if (dir == nullptr) return -1;
1083 ssize_t ret = 0;
1084 dirent* ent;
1085 while ((ent = readdir(dir)) != nullptr) ret++;
1086 closedir(dir);
1087 return ret;
1088}
1089
Andrei Homescua858b0e2022-08-01 23:43:09 +00001090TEST_P(BinderRpc, Fds) {
1091 if (serverSingleThreaded()) {
1092 GTEST_SKIP() << "This test requires multiple threads";
1093 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001094 if (socketType() == SocketType::TIPC) {
1095 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1096 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001097
Steven Moreland5553ac42020-11-11 02:14:45 +00001098 ssize_t beforeFds = countFds();
1099 ASSERT_GE(beforeFds, 0);
1100 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001101 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001102 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1103 }
1104 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1105}
1106
Andrei Homescud65666d2023-03-03 07:28:02 +00001107#ifdef BINDER_RPC_TO_TRUSTY_TEST
1108INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc,
1109 ::testing::Combine(::testing::Values(SocketType::TIPC),
1110 ::testing::Values(RpcSecurity::RAW),
1111 ::testing::ValuesIn(testVersions()),
1112 ::testing::ValuesIn(testVersions()),
1113 ::testing::Values(true), ::testing::Values(true)),
1114 BinderRpc::PrintParamInfo);
1115#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandda573042021-06-12 01:13:45 +00001116static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001117 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001118 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001119
Andrei Homescu992a4052022-06-28 21:26:18 +00001120 android::base::unique_fd serverFd(
1121 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1122 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1123
1124 sockaddr_vm serverAddr{
1125 .svm_family = AF_VSOCK,
1126 .svm_port = vsockPort,
1127 .svm_cid = VMADDR_CID_ANY,
1128 };
1129 int ret = TEMP_FAILURE_RETRY(
1130 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1131 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1132 strerror(errno));
1133
1134 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1135 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1136 strerror(errno));
1137
1138 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1139 // to see if the kernel supports it. It's safe to use a blocking
1140 // connect because vsock sockets have a 2 second connection timeout,
1141 // and they return ETIMEDOUT after that.
1142 android::base::unique_fd connectFd(
1143 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1144 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1145 strerror(errno));
1146
1147 bool success = false;
1148 sockaddr_vm connectAddr{
1149 .svm_family = AF_VSOCK,
1150 .svm_port = vsockPort,
1151 .svm_cid = VMADDR_CID_LOCAL,
1152 };
1153 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1154 sizeof(connectAddr)));
1155 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1156 android::base::unique_fd acceptFd;
1157 while (true) {
1158 pollfd pfd[]{
1159 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1160 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1161 };
1162 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1163 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1164
1165 if (pfd[0].revents & POLLIN) {
1166 sockaddr_vm acceptAddr;
1167 socklen_t acceptAddrLen = sizeof(acceptAddr);
1168 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1169 reinterpret_cast<sockaddr*>(&acceptAddr),
1170 &acceptAddrLen, SOCK_CLOEXEC));
1171 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1172 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1173 "Truncated address");
1174
1175 // Store the fd in acceptFd so we keep the connection alive
1176 // while polling connectFd
1177 acceptFd.reset(ret);
1178 }
1179
1180 if (pfd[1].revents & POLLOUT) {
1181 // Connect either succeeded or timed out
1182 int connectErrno;
1183 socklen_t connectErrnoLen = sizeof(connectErrno);
1184 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1185 &connectErrnoLen);
1186 LOG_ALWAYS_FATAL_IF(ret == -1,
1187 "Could not getsockopt() after connect() "
1188 "on non-blocking socket: %s.",
1189 strerror(errno));
1190
1191 // We're done, this is all we wanted
1192 success = connectErrno == 0;
1193 break;
1194 }
1195 }
1196 } else {
1197 success = ret == 0;
1198 }
1199
1200 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1201
1202 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001203}
1204
Yifan Hong1deca4b2021-09-10 16:16:44 -07001205static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001206 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1207 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001208
1209 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001210
1211 static bool hasVsockLoopback = testSupportVsockLoopback();
1212
1213 if (hasVsockLoopback) {
1214 ret.push_back(SocketType::VSOCK);
1215 }
1216
1217 return ret;
1218}
1219
Yifan Hong702115c2021-06-24 15:39:18 -07001220INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1221 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001222 ::testing::ValuesIn(RpcSecurityValues()),
1223 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001224 ::testing::ValuesIn(testVersions()),
1225 ::testing::Values(false, true),
1226 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001227 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001228
Yifan Hong702115c2021-06-24 15:39:18 -07001229class BinderRpcServerRootObject
1230 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001231
1232TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1233 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1234 auto setRootObject = [](bool isStrong) -> SetFn {
1235 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1236 };
1237
Yifan Hong702115c2021-06-24 15:39:18 -07001238 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001239 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001240 auto binder1 = sp<BBinder>::make();
1241 IBinder* binderRaw1 = binder1.get();
1242 setRootObject(isStrong1)(server.get(), binder1);
1243 EXPECT_EQ(binderRaw1, server->getRootObject());
1244 binder1.clear();
1245 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1246
1247 auto binder2 = sp<BBinder>::make();
1248 IBinder* binderRaw2 = binder2.get();
1249 setRootObject(isStrong2)(server.get(), binder2);
1250 EXPECT_EQ(binderRaw2, server->getRootObject());
1251 binder2.clear();
1252 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1253}
1254
1255INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001256 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1257 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001258
Yifan Hong1a235852021-05-13 16:07:47 -07001259class OneOffSignal {
1260public:
1261 // If notify() was previously called, or is called within |duration|, return true; else false.
1262 template <typename R, typename P>
1263 bool wait(std::chrono::duration<R, P> duration) {
1264 std::unique_lock<std::mutex> lock(mMutex);
1265 return mCv.wait_for(lock, duration, [this] { return mValue; });
1266 }
1267 void notify() {
1268 std::unique_lock<std::mutex> lock(mMutex);
1269 mValue = true;
1270 lock.unlock();
1271 mCv.notify_all();
1272 }
1273
1274private:
1275 std::mutex mMutex;
1276 std::condition_variable mCv;
1277 bool mValue = false;
1278};
1279
Yifan Hong194acf22021-06-29 18:44:56 -07001280TEST(BinderRpc, Java) {
1281#if !defined(__ANDROID__)
1282 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1283 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1284 "to binderHostDeviceTest. Hence, just disable this test on host.";
1285#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001286 if constexpr (!kEnableKernelIpc) {
1287 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1288 "at build time.";
1289 }
1290
Yifan Hong194acf22021-06-29 18:44:56 -07001291 sp<IServiceManager> sm = defaultServiceManager();
1292 ASSERT_NE(nullptr, sm);
1293 // Any Java service with non-empty getInterfaceDescriptor() would do.
1294 // Let's pick batteryproperties.
1295 auto binder = sm->checkService(String16("batteryproperties"));
1296 ASSERT_NE(nullptr, binder);
1297 auto descriptor = binder->getInterfaceDescriptor();
1298 ASSERT_GE(descriptor.size(), 0);
1299 ASSERT_EQ(OK, binder->pingBinder());
1300
1301 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001302 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001303 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001304 auto socket = rpcServer->releaseServer();
1305
1306 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001307 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1308
Yifan Honge3caaf22022-01-12 14:46:56 -08001309 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1310 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001311 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001312 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1313 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001314 << statusToString(setRpcClientDebugStatus);
1315 GTEST_SKIP();
1316 }
1317
1318 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001319
1320 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001321 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001322 auto rpcBinder = rpcSession->getRootObject();
1323 ASSERT_NE(nullptr, rpcBinder);
1324
1325 ASSERT_EQ(OK, rpcBinder->pingBinder());
1326
1327 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1328 << "getInterfaceDescriptor should not crash system_server";
1329 ASSERT_EQ(OK, rpcBinder->pingBinder());
1330}
1331
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001332class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1333public:
1334 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001335 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001336 std::to_string(std::get<1>(info.param));
1337 }
1338};
1339
1340TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1341 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1342 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001343 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001344 server->setProtocolVersion(std::get<1>(GetParam()));
1345 ASSERT_FALSE(server->hasServer());
1346 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1347 ASSERT_TRUE(server->hasServer());
1348 base::unique_fd retrieved = server->releaseServer();
1349 ASSERT_FALSE(server->hasServer());
1350 ASSERT_EQ(sinkFd, retrieved.get());
1351}
1352
1353TEST_P(BinderRpcServerOnly, Shutdown) {
1354 if constexpr (!kEnableRpcThreads) {
1355 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1356 }
1357
1358 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001359 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001360 server->setProtocolVersion(std::get<1>(GetParam()));
1361 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1362 auto joinEnds = std::make_shared<OneOffSignal>();
1363
1364 // If things are broken and the thread never stops, don't block other tests. Because the thread
1365 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1366 // shared pointers are passed.
1367 std::thread([server, joinEnds] {
1368 server->join();
1369 joinEnds->notify();
1370 }).detach();
1371
1372 bool shutdown = false;
1373 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001374 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001375 if (server->shutdown()) shutdown = true;
1376 }
1377 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1378
1379 ASSERT_TRUE(joinEnds->wait(2s))
1380 << "After server->shutdown() returns true, join() did not stop after 2s";
1381}
1382
Frederick Mayledc07cf82022-05-26 20:30:12 +00001383INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1384 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1385 ::testing::ValuesIn(testVersions())),
1386 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001387
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001388class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001389public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001390 // Only parameterized only server version because `RpcSession` is bypassed
1391 // in the client half of the tests.
1392 using Param =
1393 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001394 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001395
1396 // A server that handles client socket connections.
1397 class Server {
1398 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001399 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1400
Yifan Hong1deca4b2021-09-10 16:16:44 -07001401 explicit Server() {}
1402 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001403 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001404 [[nodiscard]] AssertionResult setUp(
1405 const Param& param,
1406 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001407 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001408 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001409 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001410 switch (socketType) {
1411 case SocketType::PRECONNECTED: {
1412 return AssertionFailure() << "Not supported by this test";
1413 } break;
1414 case SocketType::UNIX: {
1415 auto addr = allocateSocketAddress();
1416 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1417 if (status != OK) {
1418 return AssertionFailure()
1419 << "setupUnixDomainServer: " << statusToString(status);
1420 }
1421 mConnectToServer = [addr] {
1422 return connectTo(UnixSocketAddress(addr.c_str()));
1423 };
1424 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001425 case SocketType::UNIX_BOOTSTRAP: {
1426 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1427 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1428 return AssertionFailure() << "Socketpair() failed";
1429 }
1430 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1431 std::move(bootstrapFdServer));
1432 if (status != OK) {
1433 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1434 << statusToString(status);
1435 }
1436 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1437 mAcceptConnection = &Server::recvmsgServerConnection;
1438 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1439 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001440 case SocketType::UNIX_RAW: {
1441 auto addr = allocateSocketAddress();
1442 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1443 if (status != OK) {
1444 return AssertionFailure()
1445 << "setupRawSocketServer: " << statusToString(status);
1446 }
1447 mConnectToServer = [addr] {
1448 return connectTo(UnixSocketAddress(addr.c_str()));
1449 };
1450 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001451 case SocketType::VSOCK: {
1452 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001453 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001454 if (status != OK) {
1455 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1456 }
1457 mConnectToServer = [port] {
1458 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1459 };
1460 } break;
1461 case SocketType::INET: {
1462 unsigned int port;
1463 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1464 if (status != OK) {
1465 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1466 }
1467 mConnectToServer = [port] {
1468 const char* addr = kLocalInetAddress;
1469 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1470 if (aiStart == nullptr) return base::unique_fd{};
1471 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1472 auto fd = connectTo(
1473 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1474 if (fd.ok()) return fd;
1475 }
1476 ALOGE("None of the socket address resolved for %s:%u can be connected",
1477 addr, port);
1478 return base::unique_fd{};
1479 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001480 } break;
1481 case SocketType::TIPC: {
1482 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1483 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001484 }
1485 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001486 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00001487 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001488 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1489 mSetup = true;
1490 return AssertionSuccess();
1491 }
1492 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1493 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1494 return mCertVerifier;
1495 }
1496 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1497 void start() {
1498 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1499 mThread = std::make_unique<std::thread>(&Server::run, this);
1500 }
David Brazdil21c887c2022-09-23 12:25:18 +01001501
1502 base::unique_fd acceptServerConnection() {
1503 return base::unique_fd(TEMP_FAILURE_RETRY(
1504 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1505 }
1506
1507 base::unique_fd recvmsgServerConnection() {
1508 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1509 int buf;
1510 iovec iov{&buf, sizeof(buf)};
1511
1512 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1513 int savedErrno = errno;
1514 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1515 }
1516 if (fds.size() != 1) {
1517 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1518 }
1519 return std::move(std::get<base::unique_fd>(fds[0]));
1520 }
1521
Yifan Hong1deca4b2021-09-10 16:16:44 -07001522 void run() {
1523 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1524
1525 std::vector<std::thread> threads;
1526 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001527 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001528 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1529 }
1530
1531 for (auto& thread : threads) thread.join();
1532 }
1533 void handleOne(android::base::unique_fd acceptedFd) {
1534 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001535 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001536 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001537 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001538 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001539 }
Yifan Honge07d2732021-09-13 21:59:14 -07001540 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001541 shutdown();
1542 join();
1543 }
1544 void shutdown() { mFdTrigger->trigger(); }
1545
1546 void setPostConnect(
1547 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1548 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001549 }
1550
1551 private:
1552 std::unique_ptr<std::thread> mThread;
1553 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001554 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001555 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001556 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001557 std::unique_ptr<RpcTransportCtx> mCtx;
1558 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1559 std::make_shared<RpcCertificateVerifierSimple>();
1560 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001561 // The function invoked after connection and handshake. By default, it is
1562 // |defaultPostConnect| that sends |kMessage| to the client.
1563 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1564 Server::defaultPostConnect;
1565
1566 void join() {
1567 if (mThread != nullptr) {
1568 mThread->join();
1569 mThread = nullptr;
1570 }
1571 }
1572
1573 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1574 FdTrigger* fdTrigger) {
1575 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001576 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001577 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001578 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001579 if (status != OK) return AssertionFailure() << statusToString(status);
1580 return AssertionSuccess();
1581 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001582 };
1583
1584 class Client {
1585 public:
1586 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1587 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001588 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001589 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1590 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001591 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001592 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001593 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1594 return AssertionSuccess();
1595 }
1596 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1597 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1598 return mCertVerifier;
1599 }
Yifan Hong67519322021-09-13 18:51:16 -07001600 // connect() and do handshake
1601 bool setUpTransport() {
1602 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001603 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001604 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1605 return mClientTransport != nullptr;
1606 }
1607 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1608 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1609 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001610 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001611 status_t readStatus =
1612 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001613 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001614 if (readStatus != OK) {
1615 return AssertionFailure() << statusToString(readStatus);
1616 }
1617 if (readMessage != expectedMessage) {
1618 return AssertionFailure()
1619 << "Expected " << expectedMessage << ", actual " << readMessage;
1620 }
1621 return AssertionSuccess();
1622 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001623 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001624 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001625 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1626 return;
1627 }
1628 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001629 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001630 }
1631
Pawan49d74cb2022-08-03 21:19:11 +00001632 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1633
Yifan Hong1deca4b2021-09-10 16:16:44 -07001634 private:
1635 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001636 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001637 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1638 std::unique_ptr<RpcTransportCtx> mCtx;
1639 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1640 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001641 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001642 };
1643
1644 // Make A trust B.
1645 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001646 static status_t trust(RpcSecurity rpcSecurity,
1647 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1648 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001649 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001650 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1651 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1652 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001653 }
1654
1655 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001656};
1657
1658class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1659public:
1660 using Server = RpcTransportTestUtils::Server;
1661 using Client = RpcTransportTestUtils::Client;
1662 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001663 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001664 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001665 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001666 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001667 return ret;
1668 }
1669 static std::vector<ParamType> getRpcTranportTestParams() {
1670 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001671 for (auto serverVersion : testVersions()) {
1672 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1673 for (auto rpcSecurity : RpcSecurityValues()) {
1674 switch (rpcSecurity) {
1675 case RpcSecurity::RAW: {
1676 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1677 } break;
1678 case RpcSecurity::TLS: {
1679 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1680 serverVersion);
1681 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1682 serverVersion);
1683 } break;
1684 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001685 }
1686 }
1687 }
1688 return ret;
1689 }
1690 template <typename A, typename B>
1691 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001692 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1693 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001694 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1695 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001696 void SetUp() override {
1697 if constexpr (!kEnableRpcThreads) {
1698 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1699 }
1700 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001701};
1702
1703TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001704 auto server = std::make_unique<Server>();
1705 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001706
1707 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001708 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001709
1710 ASSERT_EQ(OK, trust(&client, server));
1711 ASSERT_EQ(OK, trust(server, &client));
1712
1713 server->start();
1714 client.run();
1715}
1716
1717TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001718 auto server = std::make_unique<Server>();
1719 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001720
1721 std::vector<Client> clients;
1722 for (int i = 0; i < 2; i++) {
1723 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001724 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001725 ASSERT_EQ(OK, trust(&client, server));
1726 ASSERT_EQ(OK, trust(server, &client));
1727 }
1728
1729 server->start();
1730 for (auto& client : clients) client.run();
1731}
1732
1733TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001734 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1735 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001736
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001737 auto untrustedServer = std::make_unique<Server>();
1738 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001739
1740 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001741 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001742
1743 ASSERT_EQ(OK, trust(untrustedServer, &client));
1744
1745 untrustedServer->start();
1746
1747 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1748 // the client can't verify the server's identity.
1749 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1750 client.run(handshakeOk);
1751}
1752TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001753 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1754 (void)serverVersion;
1755
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001756 auto validServer = std::make_unique<Server>();
1757 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001758
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001759 auto maliciousServer = std::make_unique<Server>();
1760 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001761
1762 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001763 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001764
1765 ASSERT_EQ(OK, trust(&client, validServer));
1766 ASSERT_EQ(OK, trust(validServer, &client));
1767 ASSERT_EQ(OK, trust(maliciousServer, &client));
1768
1769 maliciousServer->start();
1770
1771 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1772 // the client can't verify the server's identity.
1773 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1774 client.run(handshakeOk);
1775}
1776
1777TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001778 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1779 (void)serverVersion;
1780
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001781 auto server = std::make_unique<Server>();
1782 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001783
1784 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001785 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001786
1787 ASSERT_EQ(OK, trust(&client, server));
1788
1789 server->start();
1790
1791 // For TLS, Client should be able to verify server's identity, so client should see
1792 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1793 // identity and should drop the connection, so client shouldn't be able to read anything.
1794 bool readOk = rpcSecurity != RpcSecurity::TLS;
1795 client.run(true, readOk);
1796}
1797
1798TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001799 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1800 (void)serverVersion;
1801
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001802 auto server = std::make_unique<Server>();
1803 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001804
1805 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001806 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001807 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001808 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001809
1810 ASSERT_EQ(OK, trust(&validClient, server));
1811 ASSERT_EQ(OK, trust(&maliciousClient, server));
1812
1813 server->start();
1814
1815 // See UntrustedClient.
1816 bool readOk = rpcSecurity != RpcSecurity::TLS;
1817 maliciousClient.run(true, readOk);
1818}
1819
Yifan Hong67519322021-09-13 18:51:16 -07001820TEST_P(RpcTransportTest, Trigger) {
1821 std::string msg2 = ", world!";
1822 std::mutex writeMutex;
1823 std::condition_variable writeCv;
1824 bool shouldContinueWriting = false;
1825 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001826 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001827 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001828 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1829 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001830 if (status != OK) return AssertionFailure() << statusToString(status);
1831
1832 {
1833 std::unique_lock<std::mutex> lock(writeMutex);
1834 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1835 return AssertionFailure() << "write barrier not cleared in time!";
1836 }
1837 }
1838
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001839 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001840 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1841 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001842 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001843 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001844 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001845 << statusToString(status);
1846 return AssertionSuccess();
1847 };
1848
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001849 auto server = std::make_unique<Server>();
1850 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001851
1852 // Set up client
1853 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001854 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001855
1856 // Exchange keys
1857 ASSERT_EQ(OK, trust(&client, server));
1858 ASSERT_EQ(OK, trust(server, &client));
1859
1860 server->setPostConnect(serverPostConnect);
1861
Yifan Hong67519322021-09-13 18:51:16 -07001862 server->start();
1863 // connect() to server and do handshake
1864 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001865 // read the first message. This ensures that server has finished handshake and start handling
1866 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001867 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001868 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1869 // write is on an FdTrigger that has been shut down.
1870 server->shutdown();
1871 // Continues server thread to write the second message.
1872 {
Yifan Hong22211f82021-09-14 12:32:25 -07001873 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001874 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001875 }
Yifan Hong22211f82021-09-14 12:32:25 -07001876 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001877 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001878 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001879 // On the client side, second read fails with DEAD_OBJECT
1880 ASSERT_FALSE(client.readMessage(msg2));
1881}
1882
Pawan49d74cb2022-08-03 21:19:11 +00001883TEST_P(RpcTransportTest, CheckWaitingForRead) {
1884 std::mutex readMutex;
1885 std::condition_variable readCv;
1886 bool shouldContinueReading = false;
1887 // Server will write data on transport once its started
1888 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1889 std::string message(RpcTransportTestUtils::kMessage);
1890 iovec messageIov{message.data(), message.size()};
1891 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1892 std::nullopt, nullptr);
1893 if (status != OK) return AssertionFailure() << statusToString(status);
1894
1895 {
1896 std::unique_lock<std::mutex> lock(readMutex);
1897 shouldContinueReading = true;
1898 lock.unlock();
1899 readCv.notify_all();
1900 }
1901 return AssertionSuccess();
1902 };
1903
1904 // Setup Server and client
1905 auto server = std::make_unique<Server>();
1906 ASSERT_TRUE(server->setUp(GetParam()));
1907
1908 Client client(server->getConnectToServerFn());
1909 ASSERT_TRUE(client.setUp(GetParam()));
1910
1911 ASSERT_EQ(OK, trust(&client, server));
1912 ASSERT_EQ(OK, trust(server, &client));
1913 server->setPostConnect(serverPostConnect);
1914
1915 server->start();
1916 ASSERT_TRUE(client.setUpTransport());
1917 {
1918 // Wait till server writes data
1919 std::unique_lock<std::mutex> lock(readMutex);
1920 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1921 }
1922
1923 // Since there is no read polling here, we will get polling count 0
1924 ASSERT_FALSE(client.isTransportWaiting());
1925 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1926 // Thread should increment polling count, read and decrement polling count
1927 // Again, polling count should be zero here
1928 ASSERT_FALSE(client.isTransportWaiting());
1929
1930 server->shutdown();
1931}
1932
Yifan Hong1deca4b2021-09-10 16:16:44 -07001933INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001934 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001935 RpcTransportTest::PrintParamInfo);
1936
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001937class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001938 : public testing::TestWithParam<
1939 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001940public:
1941 template <typename A, typename B>
1942 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001943 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1944 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001945 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1946 }
1947 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001948 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1949 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1950 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001951 };
1952};
1953
1954TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001955 if constexpr (!kEnableRpcThreads) {
1956 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1957 }
1958
Frederick Mayledc07cf82022-05-26 20:30:12 +00001959 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001960
1961 std::vector<uint8_t> pkeyData, certData;
1962 {
1963 auto pkey = makeKeyPairForSelfSignedCert();
1964 ASSERT_NE(nullptr, pkey);
1965 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1966 ASSERT_NE(nullptr, cert);
1967 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1968 certData = serializeCertificate(cert.get(), certificateFormat);
1969 }
1970
1971 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1972 auto desCert = deserializeCertificate(certData, certificateFormat);
1973 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001974 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1975 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001976
1977 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1978 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1979
1980 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1981 ASSERT_TRUE(client.setUp(utilsParam));
1982
1983 ASSERT_EQ(OK, trust(&client, server));
1984 ASSERT_EQ(OK, trust(server, &client));
1985
1986 server->start();
1987 client.run();
1988}
1989
1990INSTANTIATE_TEST_CASE_P(
1991 BinderRpc, RpcTransportTlsKeyTest,
1992 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1993 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001994 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1995 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001996 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00001997#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001998
Steven Morelandc1635952021-04-01 16:20:47 +00001999} // namespace android
2000
2001int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002002 ::testing::InitGoogleTest(&argc, argv);
2003 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002004
Steven Moreland5553ac42020-11-11 02:14:45 +00002005 return RUN_ALL_TESTS();
2006}