blob: 5952c4172ede5eb866d27eee597d27044d830e7f [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andrei Homescu9d8adb12022-08-02 04:38:30 +000017#include <aidl/IBinderRpcTest.h>
Frederick Maylea12b0962022-06-25 01:13:22 +000018#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000019
Steven Morelandc1635952021-04-01 16:20:47 +000020#include <chrono>
21#include <cstdlib>
22#include <iostream>
23#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000024#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000025
Andrei Homescu2a298012022-06-15 01:08:54 +000026#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070027#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000029#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000030
Andrei Homescu68a55612022-08-02 01:25:15 +000031#ifdef __ANDROID_VENDOR__
32#include <binder/RpcTransportTipcAndroid.h>
33#include <trusty/tipc.h>
34#endif // __ANDROID_VENDOR__
35
Andrei Homescu2a298012022-06-15 01:08:54 +000036#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000037#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000038
Yifan Hong1a235852021-05-13 16:07:47 -070039using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070040using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070041using testing::AssertionFailure;
42using testing::AssertionResult;
43using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070044
Steven Moreland5553ac42020-11-11 02:14:45 +000045namespace android {
46
Andrei Homescu12106de2022-04-27 04:42:21 +000047#ifdef BINDER_TEST_NO_SHARED_LIBS
48constexpr bool kEnableSharedLibs = false;
49#else
50constexpr bool kEnableSharedLibs = true;
51#endif
52
Andrei Homescu68a55612022-08-02 01:25:15 +000053#ifdef __ANDROID_VENDOR__
54constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
55#endif
56
Frederick Maylea12b0962022-06-25 01:13:22 +000057static std::string WaitStatusToString(int wstatus) {
58 if (WIFEXITED(wstatus)) {
59 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
60 }
61 if (WIFSIGNALED(wstatus)) {
62 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
63 }
64 return base::StringPrintf("unexpected state %d", wstatus);
65}
66
Steven Moreland276d8df2022-09-28 23:56:39 +000067static void debugBacktrace(pid_t pid) {
68 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
69 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
70}
71
Steven Moreland5553ac42020-11-11 02:14:45 +000072class Process {
73public:
Andrei Homescu96834632022-10-14 00:49:49 +000074 Process(Process&& other)
75 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
76 mReadEnd(std::move(other.mReadEnd)),
77 mWriteEnd(std::move(other.mWriteEnd)) {
78 // The default move constructor doesn't clear mPid after moving it,
79 // which we need to do because the destructor checks for mPid!=0
80 mPid = other.mPid;
81 other.mPid = 0;
82 }
Yifan Hong1deca4b2021-09-10 16:16:44 -070083 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
84 android::base::borrowed_fd /* readEnd */)>& f) {
85 android::base::unique_fd childWriteEnd;
86 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +000087 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
88 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +000089 if (0 == (mPid = fork())) {
90 // racey: assume parent doesn't crash before this is set
91 prctl(PR_SET_PDEATHSIG, SIGHUP);
92
Yifan Hong1deca4b2021-09-10 16:16:44 -070093 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +000094
95 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +000096 }
97 }
98 ~Process() {
99 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000100 int wstatus;
101 waitpid(mPid, &wstatus, 0);
102 if (mCustomExitStatusCheck) {
103 mCustomExitStatusCheck(wstatus);
104 } else {
105 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
106 << "server process failed: " << WaitStatusToString(wstatus);
107 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000108 }
109 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700110 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700111 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000112
Frederick Maylea12b0962022-06-25 01:13:22 +0000113 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
114 mCustomExitStatusCheck = std::move(f);
115 }
116
Frederick Mayle69a0c992022-05-26 20:38:39 +0000117 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
118 void terminate() { kill(mPid, SIGTERM); }
119
Steven Moreland276d8df2022-09-28 23:56:39 +0000120 pid_t getPid() { return mPid; }
121
Steven Moreland5553ac42020-11-11 02:14:45 +0000122private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000123 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000124 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700125 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700126 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000127};
128
129static std::string allocateSocketAddress() {
130 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000131 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000132 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700133 unlink(ret.c_str());
134 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000135};
136
Steven Morelandda573042021-06-12 01:13:45 +0000137static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000138 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000139 return vsockPort++;
140}
141
Alice Wang893a9912022-10-24 10:44:09 +0000142static base::unique_fd initUnixSocket(std::string addr) {
143 auto socket_addr = UnixSocketAddress(addr.c_str());
144 base::unique_fd fd(
145 TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
146 CHECK(fd.ok());
147 CHECK_EQ(0, TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize())));
148 return fd;
149}
150
Andrei Homescu96834632022-10-14 00:49:49 +0000151// Destructors need to be defined, even if pure virtual
152ProcessSession::~ProcessSession() {}
153
154class LinuxProcessSession : public ProcessSession {
155public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000156 // reference to process hosting a socket server
157 Process host;
158
Andrei Homescu96834632022-10-14 00:49:49 +0000159 LinuxProcessSession(LinuxProcessSession&&) = default;
160 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
161 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000162 for (auto& session : sessions) {
163 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000164 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000165
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000166 for (auto& info : sessions) {
167 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000168
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000169 EXPECT_NE(nullptr, session);
170 EXPECT_NE(nullptr, session->state());
171 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000172
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000173 wp<RpcSession> weakSession = session;
174 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000175
Steven Moreland57042712022-10-04 23:56:45 +0000176 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
177 // the object should not actually be promotable. By looping, we distinguish a race here
178 // from a bug causing the object to not be promotable.
179 for (size_t i = 0; i < 3; i++) {
180 sp<RpcSession> strongSession = weakSession.promote();
181 EXPECT_EQ(nullptr, strongSession)
182 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
183 "Leaked sess: ")
184 << strongSession->getStrongCount() << " checked time " << i;
185
186 if (strongSession != nullptr) {
187 sleep(1);
188 }
189 }
Steven Moreland736664b2021-05-01 04:27:25 +0000190 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000191 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000192
Andrei Homescu96834632022-10-14 00:49:49 +0000193 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
194 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000195 }
Andrei Homescu96834632022-10-14 00:49:49 +0000196
197 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000198};
199
Yifan Hong1deca4b2021-09-10 16:16:44 -0700200static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700201 base::unique_fd serverFd(
202 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
203 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700204 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
205 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700206
207 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
208 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700209 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
210 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700211 }
212 return serverFd;
213}
214
David Brazdil21c887c2022-09-23 12:25:18 +0100215static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
216 base::unique_fd sockClient, sockServer;
217 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
218 int savedErrno = errno;
219 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
220 }
221
222 int zero = 0;
223 iovec iov{&zero, sizeof(zero)};
224 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
225 fds.emplace_back(std::move(sockServer));
226
227 if (sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
228 int savedErrno = errno;
229 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
230 }
231 return std::move(sockClient);
232}
233
Andrei Homescu96834632022-10-14 00:49:49 +0000234std::string BinderRpc::PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
235 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
236 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
237 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
238 if (singleThreaded) {
239 ret += "_single_threaded";
Steven Moreland5602a1a2023-03-06 19:25:46 +0000240 } else {
241 ret += "_multi_threaded";
Andrei Homescu96834632022-10-14 00:49:49 +0000242 }
243 if (noKernel) {
244 ret += "_no_kernel";
Steven Moreland5602a1a2023-03-06 19:25:46 +0000245 } else {
246 ret += "_with_kernel";
Andrei Homescu96834632022-10-14 00:49:49 +0000247 }
248 return ret;
249}
Andrei Homescu2a298012022-06-15 01:08:54 +0000250
Andrei Homescu96834632022-10-14 00:49:49 +0000251// This creates a new process serving an interface on a certain number of
252// threads.
253std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
254 const BinderRpcOptions& options) {
255 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000256
Andrei Homescu96834632022-10-14 00:49:49 +0000257 SocketType socketType = std::get<0>(GetParam());
258 RpcSecurity rpcSecurity = std::get<1>(GetParam());
259 uint32_t clientVersion = std::get<2>(GetParam());
260 uint32_t serverVersion = std::get<3>(GetParam());
261 bool singleThreaded = std::get<4>(GetParam());
262 bool noKernel = std::get<5>(GetParam());
263
264 std::string path = android::base::GetExecutableDirectory();
265 auto servicePath = android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
266 singleThreaded ? "_single_threaded" : "",
267 noKernel ? "_no_kernel" : "");
268
Alice Wang1ef010b2022-11-14 09:09:25 +0000269 base::unique_fd bootstrapClientFd, socketFd;
270
Alice Wang893a9912022-10-24 10:44:09 +0000271 auto addr = allocateSocketAddress();
272 // Initializes the socket before the fork/exec.
273 if (socketType == SocketType::UNIX_RAW) {
274 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000275 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
276 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
277 // This is because we cannot pass ParcelFileDescriptor over a pipe.
278 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
279 int savedErrno = errno;
280 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
281 }
Alice Wang893a9912022-10-24 10:44:09 +0000282 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000283
Andrei Homescu96834632022-10-14 00:49:49 +0000284 auto ret = std::make_unique<LinuxProcessSession>(
285 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000286 if (socketType == SocketType::TIPC) {
287 // Trusty has a single persistent service
288 return;
289 }
290
Andrei Homescu96834632022-10-14 00:49:49 +0000291 auto writeFd = std::to_string(writeEnd.get());
292 auto readFd = std::to_string(readEnd.get());
293 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
294 NULL);
295 }));
296
297 BinderRpcTestServerConfig serverConfig;
298 serverConfig.numThreads = options.numThreads;
299 serverConfig.socketType = static_cast<int32_t>(socketType);
300 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
301 serverConfig.serverVersion = serverVersion;
302 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000303 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000304 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000305 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
306 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
307 static_cast<int32_t>(mode));
308 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000309 if (socketType != SocketType::TIPC) {
310 writeToFd(ret->host.writeEnd(), serverConfig);
311 }
Andrei Homescu96834632022-10-14 00:49:49 +0000312
313 std::vector<sp<RpcSession>> sessions;
314 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
315 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000316 std::unique_ptr<RpcTransportCtxFactory> factory;
317 if (socketType == SocketType::TIPC) {
318#ifdef __ANDROID_VENDOR__
319 factory = RpcTransportCtxFactoryTipcAndroid::make();
320#else
321 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
322#endif
323 } else {
324 factory = newFactory(rpcSecurity, certVerifier);
325 }
326 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100327 }
328
Andrei Homescu68a55612022-08-02 01:25:15 +0000329 BinderRpcTestServerInfo serverInfo;
330 if (socketType != SocketType::TIPC) {
331 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
332 BinderRpcTestClientInfo clientInfo;
333 for (const auto& session : sessions) {
334 auto& parcelableCert = clientInfo.certs.emplace_back();
335 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
336 }
337 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000338
Andrei Homescu68a55612022-08-02 01:25:15 +0000339 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
340 if (socketType == SocketType::INET) {
341 CHECK_NE(0, serverInfo.port);
342 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000343
Andrei Homescu68a55612022-08-02 01:25:15 +0000344 if (rpcSecurity == RpcSecurity::TLS) {
345 const auto& serverCert = serverInfo.cert.data;
346 CHECK_EQ(OK,
347 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
348 serverCert));
349 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700350 }
351
Andrei Homescu96834632022-10-14 00:49:49 +0000352 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000353
Andrei Homescu96834632022-10-14 00:49:49 +0000354 for (const auto& session : sessions) {
355 CHECK(session->setProtocolVersion(clientVersion));
356 session->setMaxIncomingThreads(options.numIncomingConnections);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000357 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000358 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000359
Andrei Homescu96834632022-10-14 00:49:49 +0000360 switch (socketType) {
361 case SocketType::PRECONNECTED:
362 status = session->setupPreconnectedClient({}, [=]() {
363 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
364 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000365 break;
Alice Wang893a9912022-10-24 10:44:09 +0000366 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000367 case SocketType::UNIX:
368 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
369 break;
370 case SocketType::UNIX_BOOTSTRAP:
371 status = session->setupUnixDomainSocketBootstrapClient(
372 base::unique_fd(dup(bootstrapClientFd.get())));
373 break;
374 case SocketType::VSOCK:
375 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
376 break;
377 case SocketType::INET:
378 status = session->setupInetClient("127.0.0.1", serverInfo.port);
379 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000380 case SocketType::TIPC:
381 status = session->setupPreconnectedClient({}, [=]() {
382#ifdef __ANDROID_VENDOR__
383 auto port = trustyIpcPort(serverVersion);
384 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
385 return tipcFd >= 0 ? android::base::unique_fd(tipcFd)
386 : android::base::unique_fd();
387#else
388 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
389 return android::base::unique_fd();
390#endif
391 });
392 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000393 default:
394 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000395 }
Andrei Homescu96834632022-10-14 00:49:49 +0000396 if (options.allowConnectFailure && status != OK) {
397 ret->sessions.clear();
398 break;
399 }
400 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
401 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000402 }
Andrei Homescu96834632022-10-14 00:49:49 +0000403 return ret;
404}
Steven Morelandc1635952021-04-01 16:20:47 +0000405
Andrei Homescua858b0e2022-08-01 23:43:09 +0000406TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
407 if (clientOrServerSingleThreaded()) {
408 GTEST_SKIP() << "This test requires multiple threads";
409 }
410
Steven Moreland5553ac42020-11-11 02:14:45 +0000411 constexpr size_t kNumThreads = 10;
412
Steven Moreland4313d7e2021-07-15 23:41:22 +0000413 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000414
415 EXPECT_OK(proc.rootIface->lock());
416
417 // block all but one thread taking locks
418 std::vector<std::thread> ts;
419 for (size_t i = 0; i < kNumThreads - 1; i++) {
420 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
421 }
422
Steven Morelandd6d816f2022-12-23 01:37:17 +0000423 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000424
425 // other calls still work
426 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
427
Steven Morelandd6d816f2022-12-23 01:37:17 +0000428 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000429 size_t epochMsBefore = epochMillis();
430 // after this, we should never see a response within this time
431 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
432
433 // this call should be blocked for blockTimeMs
434 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
435
436 size_t epochMsAfter = epochMillis();
437 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
438
439 for (auto& t : ts) t.join();
440}
441
Steven Moreland27f620a2023-03-06 19:44:36 +0000442static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000443 size_t epochMsBefore = epochMillis();
444
445 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700446 for (size_t i = 0; i < numCalls; i++) {
447 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000448 }
449
450 for (auto& t : ts) t.join();
451
452 size_t epochMsAfter = epochMillis();
453
Yifan Hong1f44f982021-10-08 17:16:47 -0700454 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000455
456 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700457 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
458}
459
Andrei Homescua858b0e2022-08-01 23:43:09 +0000460TEST_P(BinderRpc, ThreadPoolOverSaturated) {
461 if (clientOrServerSingleThreaded()) {
462 GTEST_SKIP() << "This test requires multiple threads";
463 }
464
Yifan Hong1f44f982021-10-08 17:16:47 -0700465 constexpr size_t kNumThreads = 10;
466 constexpr size_t kNumCalls = kNumThreads + 3;
467 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland27f620a2023-03-06 19:44:36 +0000468 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 250 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700469}
470
Andrei Homescua858b0e2022-08-01 23:43:09 +0000471TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
472 if (clientOrServerSingleThreaded()) {
473 GTEST_SKIP() << "This test requires multiple threads";
474 }
475
Yifan Hong1f44f982021-10-08 17:16:47 -0700476 constexpr size_t kNumThreads = 20;
477 constexpr size_t kNumOutgoingConnections = 10;
478 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
479 auto proc = createRpcTestSocketServerProcess(
480 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland27f620a2023-03-06 19:44:36 +0000481 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 250 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000482}
483
Andrei Homescua858b0e2022-08-01 23:43:09 +0000484TEST_P(BinderRpc, ThreadingStressTest) {
485 if (clientOrServerSingleThreaded()) {
486 GTEST_SKIP() << "This test requires multiple threads";
487 }
488
Steven Moreland27f620a2023-03-06 19:44:36 +0000489 constexpr size_t kNumClientThreads = 5;
490 constexpr size_t kNumServerThreads = 5;
491 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000492
Steven Moreland4313d7e2021-07-15 23:41:22 +0000493 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000494
495 std::vector<std::thread> threads;
496 for (size_t i = 0; i < kNumClientThreads; i++) {
497 threads.push_back(std::thread([&] {
498 for (size_t j = 0; j < kNumCalls; j++) {
499 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000500 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000501 EXPECT_EQ(proc.rootBinder, out);
502 }
503 }));
504 }
505
506 for (auto& t : threads) t.join();
507}
508
Steven Moreland925ba0a2021-09-17 18:06:32 -0700509static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
510 std::vector<std::thread> threads;
511 for (size_t i = 0; i < threadCount; i++) {
512 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
513 }
514 for (auto& t : threads) t.join();
515}
516
Andrei Homescua858b0e2022-08-01 23:43:09 +0000517TEST_P(BinderRpc, OnewayStressTest) {
518 if (clientOrServerSingleThreaded()) {
519 GTEST_SKIP() << "This test requires multiple threads";
520 }
521
Steven Morelandc6046982021-04-20 00:49:42 +0000522 constexpr size_t kNumClientThreads = 10;
523 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700524 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000525
Steven Moreland4313d7e2021-07-15 23:41:22 +0000526 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000527
528 std::vector<std::thread> threads;
529 for (size_t i = 0; i < kNumClientThreads; i++) {
530 threads.push_back(std::thread([&] {
531 for (size_t j = 0; j < kNumCalls; j++) {
532 EXPECT_OK(proc.rootIface->sendString("a"));
533 }
Steven Morelandc6046982021-04-20 00:49:42 +0000534 }));
535 }
536
537 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700538
539 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000540}
541
Frederick Mayleb0221d12022-10-03 23:10:53 +0000542TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
543 if (!supportsFdTransport()) {
544 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
545 }
546 if (clientOrServerSingleThreaded()) {
547 GTEST_SKIP() << "This test requires multiple threads";
548 }
549
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000550 constexpr size_t kNumServerThreads = 3;
551
Frederick Mayleb0221d12022-10-03 23:10:53 +0000552 // This test forces a oneway transaction to be queued by issuing two
553 // `blockingSendFdOneway` calls, then drains the queue by issuing two
554 // `blockingRecvFd` calls.
555 //
556 // For more details about the queuing semantics see
557 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
558
559 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000560 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000561 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
562 .serverSupportedFileDescriptorTransportModes =
563 {RpcSession::FileDescriptorTransportMode::UNIX},
564 });
565
566 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
567 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
568 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
569 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
570
571 android::os::ParcelFileDescriptor fdA;
572 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
573 std::string result;
574 CHECK(android::base::ReadFdToString(fdA.get(), &result));
575 EXPECT_EQ(result, "a");
576
577 android::os::ParcelFileDescriptor fdB;
578 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
579 CHECK(android::base::ReadFdToString(fdB.get(), &result));
580 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000581
582 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000583}
584
Andrei Homescua858b0e2022-08-01 23:43:09 +0000585TEST_P(BinderRpc, OnewayCallQueueing) {
586 if (clientOrServerSingleThreaded()) {
587 GTEST_SKIP() << "This test requires multiple threads";
588 }
589
Steven Moreland5553ac42020-11-11 02:14:45 +0000590 constexpr size_t kNumSleeps = 10;
591 constexpr size_t kNumExtraServerThreads = 4;
592 constexpr size_t kSleepMs = 50;
593
594 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000595 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000596
597 EXPECT_OK(proc.rootIface->lock());
598
Steven Moreland1c678802021-09-17 16:48:47 -0700599 size_t epochMsBefore = epochMillis();
600
601 // all these *Async commands should be queued on the server sequentially,
602 // even though there are multiple threads.
603 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000604 proc.rootIface->sleepMsAsync(kSleepMs);
605 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000606 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
607
Steven Moreland1c678802021-09-17 16:48:47 -0700608 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000609 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700610
Steven Moreland5553ac42020-11-11 02:14:45 +0000611 size_t epochMsAfter = epochMillis();
612
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000613 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000614
Steven Moreland925ba0a2021-09-17 18:06:32 -0700615 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000616}
617
Andrei Homescua858b0e2022-08-01 23:43:09 +0000618TEST_P(BinderRpc, OnewayCallExhaustion) {
619 if (clientOrServerSingleThreaded()) {
620 GTEST_SKIP() << "This test requires multiple threads";
621 }
622
Steven Morelandd45be622021-06-04 02:19:37 +0000623 constexpr size_t kNumClients = 2;
624 constexpr size_t kTooLongMs = 1000;
625
Steven Moreland4313d7e2021-07-15 23:41:22 +0000626 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000627
628 // Build up oneway calls on the second session to make sure it terminates
629 // and shuts down. The first session should be unaffected (proc destructor
630 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000631 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000632
633 std::vector<std::thread> threads;
634 for (size_t i = 0; i < kNumClients; i++) {
635 // one of these threads will get stuck queueing a transaction once the
636 // socket fills up, the other will be able to fill up transactions on
637 // this object
638 threads.push_back(std::thread([&] {
639 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
640 }
641 }));
642 }
643 for (auto& t : threads) t.join();
644
645 Status status = iface->sleepMsAsync(kTooLongMs);
646 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
647
Steven Moreland798e0d12021-07-14 23:19:25 +0000648 // now that it has died, wait for the remote session to shutdown
649 std::vector<int32_t> remoteCounts;
650 do {
651 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
652 } while (remoteCounts.size() == kNumClients);
653
Steven Morelandd45be622021-06-04 02:19:37 +0000654 // the second session should be shutdown in the other process by the time we
655 // are able to join above (it'll only be hung up once it finishes processing
656 // any pending commands). We need to erase this session from the record
657 // here, so that the destructor for our session won't check that this
658 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000659 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000660}
661
Devin Moore66d5b7a2022-07-07 21:42:10 +0000662TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000663 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000664 GTEST_SKIP() << "This test requires multiple threads";
665 }
666 class MyDeathRec : public IBinder::DeathRecipient {
667 public:
668 void binderDied(const wp<IBinder>& /* who */) override {
669 dead = true;
670 mCv.notify_one();
671 }
672 std::mutex mMtx;
673 std::condition_variable mCv;
674 bool dead = false;
675 };
676
677 // Death recipient needs to have an incoming connection to be called
678 auto proc = createRpcTestSocketServerProcess(
679 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
680
681 auto dr = sp<MyDeathRec>::make();
682 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
683
684 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
685 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
686 }
687
688 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000689 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000690
691 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000692 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000693 proc.expectAlreadyShutdown = true;
694}
695
696TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000697 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000698 GTEST_SKIP() << "This test requires multiple threads";
699 }
700 class MyDeathRec : public IBinder::DeathRecipient {
701 public:
702 void binderDied(const wp<IBinder>& /* who */) override {
703 dead = true;
704 mCv.notify_one();
705 }
706 std::mutex mMtx;
707 std::condition_variable mCv;
708 bool dead = false;
709 };
710
711 // Death recipient needs to have an incoming connection to be called
712 auto proc = createRpcTestSocketServerProcess(
713 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
714
715 auto dr = sp<MyDeathRec>::make();
716 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
717
718 // Explicitly calling shutDownAndWait will cause the death recipients
719 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000720 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000721
722 std::unique_lock<std::mutex> lock(dr->mMtx);
723 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000724 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000725 }
726 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
727
Andrei Homescu96834632022-10-14 00:49:49 +0000728 proc.proc->terminate();
729 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000730 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
731 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
732 });
733 proc.expectAlreadyShutdown = true;
734}
735
Steven Moreland5ec743f2023-01-18 01:02:06 +0000736TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000737 if (socketType() == SocketType::TIPC) {
738 // This should work, but Trusty takes too long to restart the service
739 GTEST_SKIP() << "Service death test not supported on Trusty";
740 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000741 class MyDeathRec : public IBinder::DeathRecipient {
742 public:
743 void binderDied(const wp<IBinder>& /* who */) override {}
744 };
745
746 auto proc = createRpcTestSocketServerProcess(
747 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
748
749 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000750 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000751}
752
753TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000754 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000755 GTEST_SKIP() << "This test requires multiple threads";
756 }
757 class MyDeathRec : public IBinder::DeathRecipient {
758 public:
759 void binderDied(const wp<IBinder>& /* who */) override {
760 GTEST_FAIL() << "This should not be called after unlinkToDeath";
761 }
762 };
763
764 // Death recipient needs to have an incoming connection to be called
765 auto proc = createRpcTestSocketServerProcess(
766 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
767
768 auto dr = sp<MyDeathRec>::make();
769 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
770 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
771
772 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
773 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
774 }
775
776 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000777 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000778 proc.expectAlreadyShutdown = true;
779}
780
Steven Morelandc1635952021-04-01 16:20:47 +0000781TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000782 if (socketType() == SocketType::TIPC) {
783 // This should work, but Trusty takes too long to restart the service
784 GTEST_SKIP() << "Service death test not supported on Trusty";
785 }
786
Steven Moreland5553ac42020-11-11 02:14:45 +0000787 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000788 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000789
790 // make sure there is some state during crash
791 // 1. we hold their binder
792 sp<IBinderRpcSession> session;
793 EXPECT_OK(proc.rootIface->openSession("happy", &session));
794 // 2. they hold our binder
795 sp<IBinder> binder = new BBinder();
796 EXPECT_OK(proc.rootIface->holdBinder(binder));
797
798 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
799 << "Do death cleanup: " << doDeathCleanup;
800
Andrei Homescu96834632022-10-14 00:49:49 +0000801 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000802 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
803 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
804 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000805 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000806 }
807}
808
Steven Morelandd7302072021-05-15 01:32:04 +0000809TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000810 // This test only works if the current process shared the internal state of
811 // ProcessState with the service across the call to fork(). Both the static
812 // libraries and libbinder.so have their own separate copies of all the
813 // globals, so the test only works when the test client and service both use
814 // libbinder.so (when using static libraries, even a client and service
815 // using the same kind of static library should have separate copies of the
816 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000817 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000818 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
819 "at build time.";
820 }
821
Steven Moreland4313d7e2021-07-15 23:41:22 +0000822 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000823
Andrei Homescu2a298012022-06-15 01:08:54 +0000824 // we can't allocate IPCThreadState so actually the first time should
825 // succeed :(
826 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000827
828 // second time! we catch the error :)
829 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
830
Andrei Homescu96834632022-10-14 00:49:49 +0000831 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000832 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
833 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
834 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000835 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000836}
837
Frederick Mayle69a0c992022-05-26 20:38:39 +0000838TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000839 if (socketType() == SocketType::TIPC) {
840 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
841 }
842
Frederick Mayle69a0c992022-05-26 20:38:39 +0000843 auto proc = createRpcTestSocketServerProcess({
844 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
845 .serverSupportedFileDescriptorTransportModes =
846 {RpcSession::FileDescriptorTransportMode::UNIX},
847 .allowConnectFailure = true,
848 });
Andrei Homescu96834632022-10-14 00:49:49 +0000849 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
850 proc.proc->terminate();
851 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000852 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
853 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
854 });
855 proc.expectAlreadyShutdown = true;
856}
857
858TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
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::UNIX,
865 .serverSupportedFileDescriptorTransportModes =
866 {RpcSession::FileDescriptorTransportMode::NONE},
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, FileDescriptorTransportOptionalUnix) {
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::NONE,
885 .serverSupportedFileDescriptorTransportModes =
886 {RpcSession::FileDescriptorTransportMode::NONE,
887 RpcSession::FileDescriptorTransportMode::UNIX},
888 });
889
890 android::os::ParcelFileDescriptor out;
891 auto status = proc.rootIface->echoAsFile("hello", &out);
892 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
893}
894
895TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000896 if (socketType() == SocketType::TIPC) {
897 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
898 }
899
Frederick Mayle69a0c992022-05-26 20:38:39 +0000900 auto proc = createRpcTestSocketServerProcess({
901 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
902 .serverSupportedFileDescriptorTransportModes =
903 {RpcSession::FileDescriptorTransportMode::UNIX},
904 });
905
906 android::os::ParcelFileDescriptor out;
907 auto status = proc.rootIface->echoAsFile("hello", &out);
908 if (!supportsFdTransport()) {
909 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
910 return;
911 }
912 ASSERT_TRUE(status.isOk()) << status;
913
914 std::string result;
915 CHECK(android::base::ReadFdToString(out.get(), &result));
916 EXPECT_EQ(result, "hello");
917}
918
919TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000920 if (socketType() == SocketType::TIPC) {
921 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
922 }
923
Frederick Mayle69a0c992022-05-26 20:38:39 +0000924 auto proc = createRpcTestSocketServerProcess({
925 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
926 .serverSupportedFileDescriptorTransportModes =
927 {RpcSession::FileDescriptorTransportMode::UNIX},
928 });
929
930 std::vector<android::os::ParcelFileDescriptor> files;
931 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
932 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
933 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
934 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
935
936 android::os::ParcelFileDescriptor out;
937 auto status = proc.rootIface->concatFiles(files, &out);
938 if (!supportsFdTransport()) {
939 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
940 return;
941 }
942 ASSERT_TRUE(status.isOk()) << status;
943
944 std::string result;
945 CHECK(android::base::ReadFdToString(out.get(), &result));
946 EXPECT_EQ(result, "123abcd");
947}
948
949TEST_P(BinderRpc, SendMaxFiles) {
950 if (!supportsFdTransport()) {
951 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
952 }
953
954 auto proc = createRpcTestSocketServerProcess({
955 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
956 .serverSupportedFileDescriptorTransportModes =
957 {RpcSession::FileDescriptorTransportMode::UNIX},
958 });
959
960 std::vector<android::os::ParcelFileDescriptor> files;
961 for (int i = 0; i < 253; i++) {
962 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
963 }
964
965 android::os::ParcelFileDescriptor out;
966 auto status = proc.rootIface->concatFiles(files, &out);
967 ASSERT_TRUE(status.isOk()) << status;
968
969 std::string result;
970 CHECK(android::base::ReadFdToString(out.get(), &result));
971 EXPECT_EQ(result, std::string(253, 'a'));
972}
973
974TEST_P(BinderRpc, SendTooManyFiles) {
975 if (!supportsFdTransport()) {
976 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
977 }
978
979 auto proc = createRpcTestSocketServerProcess({
980 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
981 .serverSupportedFileDescriptorTransportModes =
982 {RpcSession::FileDescriptorTransportMode::UNIX},
983 });
984
985 std::vector<android::os::ParcelFileDescriptor> files;
986 for (int i = 0; i < 254; i++) {
987 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
988 }
989
990 android::os::ParcelFileDescriptor out;
991 auto status = proc.rootIface->concatFiles(files, &out);
992 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
993}
994
Andrei Homescufc221502022-10-08 03:51:17 +0000995TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000996 if (socketType() == SocketType::TIPC) {
997 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
998 }
999
Andrei Homescufc221502022-10-08 03:51:17 +00001000 auto proc = createRpcTestSocketServerProcess({
1001 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1002 .serverSupportedFileDescriptorTransportModes =
1003 {RpcSession::FileDescriptorTransportMode::UNIX},
1004 });
1005
1006 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1007 ASSERT_NE(badFd, -1);
1008
1009 // Close the file descriptor so it becomes invalid for dup
1010 close(badFd);
1011
1012 Parcel p1;
1013 p1.markForBinder(proc.rootBinder);
1014 p1.writeInt32(3);
1015 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1016
1017 Parcel pRaw;
1018 pRaw.markForBinder(proc.rootBinder);
1019 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1020
1021 pRaw.setDataPosition(0);
1022 EXPECT_EQ(3, pRaw.readInt32());
1023 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1024}
1025
Andrei Homescu68a55612022-08-02 01:25:15 +00001026#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001027TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001028 if constexpr (!kEnableSharedLibs) {
1029 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1030 }
1031
Steven Moreland4313d7e2021-07-15 23:41:22 +00001032 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001033
1034 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1035 ASSERT_NE(binder, nullptr);
1036
1037 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1038}
1039
1040TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001041 if constexpr (!kEnableSharedLibs) {
1042 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1043 }
1044
Steven Moreland4313d7e2021-07-15 23:41:22 +00001045 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001046
1047 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1048 ASSERT_NE(binder, nullptr);
1049
1050 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1051 ASSERT_NE(ndkBinder, nullptr);
1052
1053 std::string out;
1054 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1055 ASSERT_TRUE(status.isOk()) << status.getDescription();
1056 ASSERT_EQ("aoeuaoeu", out);
1057}
Andrei Homescu68a55612022-08-02 01:25:15 +00001058#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001059
Steven Moreland5553ac42020-11-11 02:14:45 +00001060ssize_t countFds() {
1061 DIR* dir = opendir("/proc/self/fd/");
1062 if (dir == nullptr) return -1;
1063 ssize_t ret = 0;
1064 dirent* ent;
1065 while ((ent = readdir(dir)) != nullptr) ret++;
1066 closedir(dir);
1067 return ret;
1068}
1069
Andrei Homescua858b0e2022-08-01 23:43:09 +00001070TEST_P(BinderRpc, Fds) {
1071 if (serverSingleThreaded()) {
1072 GTEST_SKIP() << "This test requires multiple threads";
1073 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001074 if (socketType() == SocketType::TIPC) {
1075 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1076 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001077
Steven Moreland5553ac42020-11-11 02:14:45 +00001078 ssize_t beforeFds = countFds();
1079 ASSERT_GE(beforeFds, 0);
1080 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001081 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001082 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1083 }
1084 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1085}
1086
Steven Morelandda573042021-06-12 01:13:45 +00001087static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001088 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001089 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001090
Andrei Homescu992a4052022-06-28 21:26:18 +00001091 android::base::unique_fd serverFd(
1092 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1093 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1094
1095 sockaddr_vm serverAddr{
1096 .svm_family = AF_VSOCK,
1097 .svm_port = vsockPort,
1098 .svm_cid = VMADDR_CID_ANY,
1099 };
1100 int ret = TEMP_FAILURE_RETRY(
1101 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1102 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1103 strerror(errno));
1104
1105 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1106 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1107 strerror(errno));
1108
1109 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1110 // to see if the kernel supports it. It's safe to use a blocking
1111 // connect because vsock sockets have a 2 second connection timeout,
1112 // and they return ETIMEDOUT after that.
1113 android::base::unique_fd connectFd(
1114 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1115 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1116 strerror(errno));
1117
1118 bool success = false;
1119 sockaddr_vm connectAddr{
1120 .svm_family = AF_VSOCK,
1121 .svm_port = vsockPort,
1122 .svm_cid = VMADDR_CID_LOCAL,
1123 };
1124 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1125 sizeof(connectAddr)));
1126 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1127 android::base::unique_fd acceptFd;
1128 while (true) {
1129 pollfd pfd[]{
1130 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1131 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1132 };
1133 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1134 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1135
1136 if (pfd[0].revents & POLLIN) {
1137 sockaddr_vm acceptAddr;
1138 socklen_t acceptAddrLen = sizeof(acceptAddr);
1139 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1140 reinterpret_cast<sockaddr*>(&acceptAddr),
1141 &acceptAddrLen, SOCK_CLOEXEC));
1142 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1143 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1144 "Truncated address");
1145
1146 // Store the fd in acceptFd so we keep the connection alive
1147 // while polling connectFd
1148 acceptFd.reset(ret);
1149 }
1150
1151 if (pfd[1].revents & POLLOUT) {
1152 // Connect either succeeded or timed out
1153 int connectErrno;
1154 socklen_t connectErrnoLen = sizeof(connectErrno);
1155 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1156 &connectErrnoLen);
1157 LOG_ALWAYS_FATAL_IF(ret == -1,
1158 "Could not getsockopt() after connect() "
1159 "on non-blocking socket: %s.",
1160 strerror(errno));
1161
1162 // We're done, this is all we wanted
1163 success = connectErrno == 0;
1164 break;
1165 }
1166 }
1167 } else {
1168 success = ret == 0;
1169 }
1170
1171 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1172
1173 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001174}
1175
Yifan Hong1deca4b2021-09-10 16:16:44 -07001176static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001177 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1178 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001179
1180 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001181
1182 static bool hasVsockLoopback = testSupportVsockLoopback();
1183
1184 if (hasVsockLoopback) {
1185 ret.push_back(SocketType::VSOCK);
1186 }
1187
1188 return ret;
1189}
1190
Andrei Homescu68a55612022-08-02 01:25:15 +00001191static std::vector<SocketType> testTipcSocketTypes() {
1192#ifdef __ANDROID_VENDOR__
1193 auto port = trustyIpcPort(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1194 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
1195 if (tipcFd >= 0) {
1196 close(tipcFd);
1197 return {SocketType::TIPC};
1198 }
1199#endif // __ANDROID_VENDOR__
1200
1201 // TIPC is not supported on this device, most likely
1202 // because /dev/trusty-ipc-dev0 is missing
1203 return {};
1204}
1205
Yifan Hong702115c2021-06-24 15:39:18 -07001206INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1207 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001208 ::testing::ValuesIn(RpcSecurityValues()),
1209 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001210 ::testing::ValuesIn(testVersions()),
1211 ::testing::Values(false, true),
1212 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001213 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001214
Andrei Homescu68a55612022-08-02 01:25:15 +00001215INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc,
1216 ::testing::Combine(::testing::ValuesIn(testTipcSocketTypes()),
1217 ::testing::Values(RpcSecurity::RAW),
1218 ::testing::ValuesIn(testVersions()),
1219 ::testing::ValuesIn(testVersions()),
1220 ::testing::Values(true), ::testing::Values(true)),
1221 BinderRpc::PrintParamInfo);
1222
Yifan Hong702115c2021-06-24 15:39:18 -07001223class BinderRpcServerRootObject
1224 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001225
1226TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1227 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1228 auto setRootObject = [](bool isStrong) -> SetFn {
1229 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1230 };
1231
Yifan Hong702115c2021-06-24 15:39:18 -07001232 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1233 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001234 auto binder1 = sp<BBinder>::make();
1235 IBinder* binderRaw1 = binder1.get();
1236 setRootObject(isStrong1)(server.get(), binder1);
1237 EXPECT_EQ(binderRaw1, server->getRootObject());
1238 binder1.clear();
1239 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1240
1241 auto binder2 = sp<BBinder>::make();
1242 IBinder* binderRaw2 = binder2.get();
1243 setRootObject(isStrong2)(server.get(), binder2);
1244 EXPECT_EQ(binderRaw2, server->getRootObject());
1245 binder2.clear();
1246 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1247}
1248
1249INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001250 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1251 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001252
Yifan Hong1a235852021-05-13 16:07:47 -07001253class OneOffSignal {
1254public:
1255 // If notify() was previously called, or is called within |duration|, return true; else false.
1256 template <typename R, typename P>
1257 bool wait(std::chrono::duration<R, P> duration) {
1258 std::unique_lock<std::mutex> lock(mMutex);
1259 return mCv.wait_for(lock, duration, [this] { return mValue; });
1260 }
1261 void notify() {
1262 std::unique_lock<std::mutex> lock(mMutex);
1263 mValue = true;
1264 lock.unlock();
1265 mCv.notify_all();
1266 }
1267
1268private:
1269 std::mutex mMutex;
1270 std::condition_variable mCv;
1271 bool mValue = false;
1272};
1273
Yifan Hong194acf22021-06-29 18:44:56 -07001274TEST(BinderRpc, Java) {
1275#if !defined(__ANDROID__)
1276 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1277 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1278 "to binderHostDeviceTest. Hence, just disable this test on host.";
1279#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001280 if constexpr (!kEnableKernelIpc) {
1281 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1282 "at build time.";
1283 }
1284
Yifan Hong194acf22021-06-29 18:44:56 -07001285 sp<IServiceManager> sm = defaultServiceManager();
1286 ASSERT_NE(nullptr, sm);
1287 // Any Java service with non-empty getInterfaceDescriptor() would do.
1288 // Let's pick batteryproperties.
1289 auto binder = sm->checkService(String16("batteryproperties"));
1290 ASSERT_NE(nullptr, binder);
1291 auto descriptor = binder->getInterfaceDescriptor();
1292 ASSERT_GE(descriptor.size(), 0);
1293 ASSERT_EQ(OK, binder->pingBinder());
1294
1295 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001296 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001297 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001298 auto socket = rpcServer->releaseServer();
1299
1300 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001301 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1302
Yifan Honge3caaf22022-01-12 14:46:56 -08001303 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1304 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001305 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001306 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1307 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001308 << statusToString(setRpcClientDebugStatus);
1309 GTEST_SKIP();
1310 }
1311
1312 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001313
1314 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001315 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001316 auto rpcBinder = rpcSession->getRootObject();
1317 ASSERT_NE(nullptr, rpcBinder);
1318
1319 ASSERT_EQ(OK, rpcBinder->pingBinder());
1320
1321 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1322 << "getInterfaceDescriptor should not crash system_server";
1323 ASSERT_EQ(OK, rpcBinder->pingBinder());
1324}
1325
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001326class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1327public:
1328 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1329 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1330 std::to_string(std::get<1>(info.param));
1331 }
1332};
1333
1334TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1335 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1336 int sinkFd = sink.get();
1337 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1338 server->setProtocolVersion(std::get<1>(GetParam()));
1339 ASSERT_FALSE(server->hasServer());
1340 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1341 ASSERT_TRUE(server->hasServer());
1342 base::unique_fd retrieved = server->releaseServer();
1343 ASSERT_FALSE(server->hasServer());
1344 ASSERT_EQ(sinkFd, retrieved.get());
1345}
1346
1347TEST_P(BinderRpcServerOnly, Shutdown) {
1348 if constexpr (!kEnableRpcThreads) {
1349 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1350 }
1351
1352 auto addr = allocateSocketAddress();
1353 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1354 server->setProtocolVersion(std::get<1>(GetParam()));
1355 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1356 auto joinEnds = std::make_shared<OneOffSignal>();
1357
1358 // If things are broken and the thread never stops, don't block other tests. Because the thread
1359 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1360 // shared pointers are passed.
1361 std::thread([server, joinEnds] {
1362 server->join();
1363 joinEnds->notify();
1364 }).detach();
1365
1366 bool shutdown = false;
1367 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001368 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001369 if (server->shutdown()) shutdown = true;
1370 }
1371 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1372
1373 ASSERT_TRUE(joinEnds->wait(2s))
1374 << "After server->shutdown() returns true, join() did not stop after 2s";
1375}
1376
Frederick Mayledc07cf82022-05-26 20:30:12 +00001377INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1378 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1379 ::testing::ValuesIn(testVersions())),
1380 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001381
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001382class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001383public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001384 // Only parameterized only server version because `RpcSession` is bypassed
1385 // in the client half of the tests.
1386 using Param =
1387 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001388 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001389
1390 // A server that handles client socket connections.
1391 class Server {
1392 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001393 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1394
Yifan Hong1deca4b2021-09-10 16:16:44 -07001395 explicit Server() {}
1396 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001397 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001398 [[nodiscard]] AssertionResult setUp(
1399 const Param& param,
1400 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001401 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001402 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001403 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001404 switch (socketType) {
1405 case SocketType::PRECONNECTED: {
1406 return AssertionFailure() << "Not supported by this test";
1407 } break;
1408 case SocketType::UNIX: {
1409 auto addr = allocateSocketAddress();
1410 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1411 if (status != OK) {
1412 return AssertionFailure()
1413 << "setupUnixDomainServer: " << statusToString(status);
1414 }
1415 mConnectToServer = [addr] {
1416 return connectTo(UnixSocketAddress(addr.c_str()));
1417 };
1418 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001419 case SocketType::UNIX_BOOTSTRAP: {
1420 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1421 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1422 return AssertionFailure() << "Socketpair() failed";
1423 }
1424 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1425 std::move(bootstrapFdServer));
1426 if (status != OK) {
1427 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1428 << statusToString(status);
1429 }
1430 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1431 mAcceptConnection = &Server::recvmsgServerConnection;
1432 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1433 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001434 case SocketType::UNIX_RAW: {
1435 auto addr = allocateSocketAddress();
1436 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1437 if (status != OK) {
1438 return AssertionFailure()
1439 << "setupRawSocketServer: " << statusToString(status);
1440 }
1441 mConnectToServer = [addr] {
1442 return connectTo(UnixSocketAddress(addr.c_str()));
1443 };
1444 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001445 case SocketType::VSOCK: {
1446 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001447 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001448 if (status != OK) {
1449 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1450 }
1451 mConnectToServer = [port] {
1452 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1453 };
1454 } break;
1455 case SocketType::INET: {
1456 unsigned int port;
1457 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1458 if (status != OK) {
1459 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1460 }
1461 mConnectToServer = [port] {
1462 const char* addr = kLocalInetAddress;
1463 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1464 if (aiStart == nullptr) return base::unique_fd{};
1465 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1466 auto fd = connectTo(
1467 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1468 if (fd.ok()) return fd;
1469 }
1470 ALOGE("None of the socket address resolved for %s:%u can be connected",
1471 addr, port);
1472 return base::unique_fd{};
1473 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001474 } break;
1475 case SocketType::TIPC: {
1476 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1477 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001478 }
1479 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001480 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001481 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001482 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1483 mSetup = true;
1484 return AssertionSuccess();
1485 }
1486 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1487 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1488 return mCertVerifier;
1489 }
1490 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1491 void start() {
1492 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1493 mThread = std::make_unique<std::thread>(&Server::run, this);
1494 }
David Brazdil21c887c2022-09-23 12:25:18 +01001495
1496 base::unique_fd acceptServerConnection() {
1497 return base::unique_fd(TEMP_FAILURE_RETRY(
1498 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1499 }
1500
1501 base::unique_fd recvmsgServerConnection() {
1502 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1503 int buf;
1504 iovec iov{&buf, sizeof(buf)};
1505
1506 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1507 int savedErrno = errno;
1508 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1509 }
1510 if (fds.size() != 1) {
1511 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1512 }
1513 return std::move(std::get<base::unique_fd>(fds[0]));
1514 }
1515
Yifan Hong1deca4b2021-09-10 16:16:44 -07001516 void run() {
1517 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1518
1519 std::vector<std::thread> threads;
1520 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001521 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001522 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1523 }
1524
1525 for (auto& thread : threads) thread.join();
1526 }
1527 void handleOne(android::base::unique_fd acceptedFd) {
1528 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001529 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001530 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001531 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001532 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001533 }
Yifan Honge07d2732021-09-13 21:59:14 -07001534 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001535 shutdown();
1536 join();
1537 }
1538 void shutdown() { mFdTrigger->trigger(); }
1539
1540 void setPostConnect(
1541 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1542 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001543 }
1544
1545 private:
1546 std::unique_ptr<std::thread> mThread;
1547 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001548 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001549 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001550 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001551 std::unique_ptr<RpcTransportCtx> mCtx;
1552 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1553 std::make_shared<RpcCertificateVerifierSimple>();
1554 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001555 // The function invoked after connection and handshake. By default, it is
1556 // |defaultPostConnect| that sends |kMessage| to the client.
1557 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1558 Server::defaultPostConnect;
1559
1560 void join() {
1561 if (mThread != nullptr) {
1562 mThread->join();
1563 mThread = nullptr;
1564 }
1565 }
1566
1567 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1568 FdTrigger* fdTrigger) {
1569 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001570 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001571 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001572 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001573 if (status != OK) return AssertionFailure() << statusToString(status);
1574 return AssertionSuccess();
1575 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001576 };
1577
1578 class Client {
1579 public:
1580 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1581 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001582 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001583 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1584 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001585 mFdTrigger = FdTrigger::make();
1586 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1587 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1588 return AssertionSuccess();
1589 }
1590 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1591 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1592 return mCertVerifier;
1593 }
Yifan Hong67519322021-09-13 18:51:16 -07001594 // connect() and do handshake
1595 bool setUpTransport() {
1596 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001597 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001598 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1599 return mClientTransport != nullptr;
1600 }
1601 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1602 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1603 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001604 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001605 status_t readStatus =
1606 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001607 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001608 if (readStatus != OK) {
1609 return AssertionFailure() << statusToString(readStatus);
1610 }
1611 if (readMessage != expectedMessage) {
1612 return AssertionFailure()
1613 << "Expected " << expectedMessage << ", actual " << readMessage;
1614 }
1615 return AssertionSuccess();
1616 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001617 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001618 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001619 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1620 return;
1621 }
1622 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001623 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001624 }
1625
Pawan49d74cb2022-08-03 21:19:11 +00001626 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1627
Yifan Hong1deca4b2021-09-10 16:16:44 -07001628 private:
1629 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001630 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001631 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1632 std::unique_ptr<RpcTransportCtx> mCtx;
1633 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1634 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001635 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001636 };
1637
1638 // Make A trust B.
1639 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001640 static status_t trust(RpcSecurity rpcSecurity,
1641 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1642 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001643 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001644 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1645 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1646 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001647 }
1648
1649 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001650};
1651
1652class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1653public:
1654 using Server = RpcTransportTestUtils::Server;
1655 using Client = RpcTransportTestUtils::Client;
1656 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001657 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001658 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1659 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001660 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001661 return ret;
1662 }
1663 static std::vector<ParamType> getRpcTranportTestParams() {
1664 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001665 for (auto serverVersion : testVersions()) {
1666 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1667 for (auto rpcSecurity : RpcSecurityValues()) {
1668 switch (rpcSecurity) {
1669 case RpcSecurity::RAW: {
1670 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1671 } break;
1672 case RpcSecurity::TLS: {
1673 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1674 serverVersion);
1675 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1676 serverVersion);
1677 } break;
1678 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001679 }
1680 }
1681 }
1682 return ret;
1683 }
1684 template <typename A, typename B>
1685 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001686 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1687 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001688 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1689 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001690 void SetUp() override {
1691 if constexpr (!kEnableRpcThreads) {
1692 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1693 }
1694 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001695};
1696
1697TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001698 auto server = std::make_unique<Server>();
1699 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001700
1701 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001702 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001703
1704 ASSERT_EQ(OK, trust(&client, server));
1705 ASSERT_EQ(OK, trust(server, &client));
1706
1707 server->start();
1708 client.run();
1709}
1710
1711TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001712 auto server = std::make_unique<Server>();
1713 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001714
1715 std::vector<Client> clients;
1716 for (int i = 0; i < 2; i++) {
1717 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001718 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001719 ASSERT_EQ(OK, trust(&client, server));
1720 ASSERT_EQ(OK, trust(server, &client));
1721 }
1722
1723 server->start();
1724 for (auto& client : clients) client.run();
1725}
1726
1727TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001728 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1729 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001730
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001731 auto untrustedServer = std::make_unique<Server>();
1732 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001733
1734 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001735 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001736
1737 ASSERT_EQ(OK, trust(untrustedServer, &client));
1738
1739 untrustedServer->start();
1740
1741 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1742 // the client can't verify the server's identity.
1743 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1744 client.run(handshakeOk);
1745}
1746TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001747 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1748 (void)serverVersion;
1749
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001750 auto validServer = std::make_unique<Server>();
1751 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001752
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001753 auto maliciousServer = std::make_unique<Server>();
1754 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001755
1756 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001757 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001758
1759 ASSERT_EQ(OK, trust(&client, validServer));
1760 ASSERT_EQ(OK, trust(validServer, &client));
1761 ASSERT_EQ(OK, trust(maliciousServer, &client));
1762
1763 maliciousServer->start();
1764
1765 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1766 // the client can't verify the server's identity.
1767 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1768 client.run(handshakeOk);
1769}
1770
1771TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001772 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1773 (void)serverVersion;
1774
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001775 auto server = std::make_unique<Server>();
1776 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001777
1778 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001779 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001780
1781 ASSERT_EQ(OK, trust(&client, server));
1782
1783 server->start();
1784
1785 // For TLS, Client should be able to verify server's identity, so client should see
1786 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1787 // identity and should drop the connection, so client shouldn't be able to read anything.
1788 bool readOk = rpcSecurity != RpcSecurity::TLS;
1789 client.run(true, readOk);
1790}
1791
1792TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001793 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1794 (void)serverVersion;
1795
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001796 auto server = std::make_unique<Server>();
1797 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001798
1799 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001800 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001801 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001802 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001803
1804 ASSERT_EQ(OK, trust(&validClient, server));
1805 ASSERT_EQ(OK, trust(&maliciousClient, server));
1806
1807 server->start();
1808
1809 // See UntrustedClient.
1810 bool readOk = rpcSecurity != RpcSecurity::TLS;
1811 maliciousClient.run(true, readOk);
1812}
1813
Yifan Hong67519322021-09-13 18:51:16 -07001814TEST_P(RpcTransportTest, Trigger) {
1815 std::string msg2 = ", world!";
1816 std::mutex writeMutex;
1817 std::condition_variable writeCv;
1818 bool shouldContinueWriting = false;
1819 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001820 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001821 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001822 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1823 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001824 if (status != OK) return AssertionFailure() << statusToString(status);
1825
1826 {
1827 std::unique_lock<std::mutex> lock(writeMutex);
1828 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1829 return AssertionFailure() << "write barrier not cleared in time!";
1830 }
1831 }
1832
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001833 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001834 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1835 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001836 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001837 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001838 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001839 << statusToString(status);
1840 return AssertionSuccess();
1841 };
1842
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001843 auto server = std::make_unique<Server>();
1844 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001845
1846 // Set up client
1847 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001848 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001849
1850 // Exchange keys
1851 ASSERT_EQ(OK, trust(&client, server));
1852 ASSERT_EQ(OK, trust(server, &client));
1853
1854 server->setPostConnect(serverPostConnect);
1855
Yifan Hong67519322021-09-13 18:51:16 -07001856 server->start();
1857 // connect() to server and do handshake
1858 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001859 // read the first message. This ensures that server has finished handshake and start handling
1860 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001861 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001862 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1863 // write is on an FdTrigger that has been shut down.
1864 server->shutdown();
1865 // Continues server thread to write the second message.
1866 {
Yifan Hong22211f82021-09-14 12:32:25 -07001867 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001868 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001869 }
Yifan Hong22211f82021-09-14 12:32:25 -07001870 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001871 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001872 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001873 // On the client side, second read fails with DEAD_OBJECT
1874 ASSERT_FALSE(client.readMessage(msg2));
1875}
1876
Pawan49d74cb2022-08-03 21:19:11 +00001877TEST_P(RpcTransportTest, CheckWaitingForRead) {
1878 std::mutex readMutex;
1879 std::condition_variable readCv;
1880 bool shouldContinueReading = false;
1881 // Server will write data on transport once its started
1882 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1883 std::string message(RpcTransportTestUtils::kMessage);
1884 iovec messageIov{message.data(), message.size()};
1885 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1886 std::nullopt, nullptr);
1887 if (status != OK) return AssertionFailure() << statusToString(status);
1888
1889 {
1890 std::unique_lock<std::mutex> lock(readMutex);
1891 shouldContinueReading = true;
1892 lock.unlock();
1893 readCv.notify_all();
1894 }
1895 return AssertionSuccess();
1896 };
1897
1898 // Setup Server and client
1899 auto server = std::make_unique<Server>();
1900 ASSERT_TRUE(server->setUp(GetParam()));
1901
1902 Client client(server->getConnectToServerFn());
1903 ASSERT_TRUE(client.setUp(GetParam()));
1904
1905 ASSERT_EQ(OK, trust(&client, server));
1906 ASSERT_EQ(OK, trust(server, &client));
1907 server->setPostConnect(serverPostConnect);
1908
1909 server->start();
1910 ASSERT_TRUE(client.setUpTransport());
1911 {
1912 // Wait till server writes data
1913 std::unique_lock<std::mutex> lock(readMutex);
1914 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1915 }
1916
1917 // Since there is no read polling here, we will get polling count 0
1918 ASSERT_FALSE(client.isTransportWaiting());
1919 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1920 // Thread should increment polling count, read and decrement polling count
1921 // Again, polling count should be zero here
1922 ASSERT_FALSE(client.isTransportWaiting());
1923
1924 server->shutdown();
1925}
1926
Yifan Hong1deca4b2021-09-10 16:16:44 -07001927INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001928 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001929 RpcTransportTest::PrintParamInfo);
1930
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001931class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001932 : public testing::TestWithParam<
1933 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001934public:
1935 template <typename A, typename B>
1936 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001937 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1938 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001939 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1940 }
1941 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001942 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1943 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1944 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001945 };
1946};
1947
1948TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001949 if constexpr (!kEnableRpcThreads) {
1950 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1951 }
1952
Frederick Mayledc07cf82022-05-26 20:30:12 +00001953 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001954
1955 std::vector<uint8_t> pkeyData, certData;
1956 {
1957 auto pkey = makeKeyPairForSelfSignedCert();
1958 ASSERT_NE(nullptr, pkey);
1959 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1960 ASSERT_NE(nullptr, cert);
1961 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1962 certData = serializeCertificate(cert.get(), certificateFormat);
1963 }
1964
1965 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1966 auto desCert = deserializeCertificate(certData, certificateFormat);
1967 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001968 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1969 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001970
1971 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1972 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1973
1974 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1975 ASSERT_TRUE(client.setUp(utilsParam));
1976
1977 ASSERT_EQ(OK, trust(&client, server));
1978 ASSERT_EQ(OK, trust(server, &client));
1979
1980 server->start();
1981 client.run();
1982}
1983
1984INSTANTIATE_TEST_CASE_P(
1985 BinderRpc, RpcTransportTlsKeyTest,
1986 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1987 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001988 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1989 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001990 RpcTransportTlsKeyTest::PrintParamInfo);
1991
Steven Morelandc1635952021-04-01 16:20:47 +00001992} // namespace android
1993
1994int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001995 ::testing::InitGoogleTest(&argc, argv);
1996 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07001997
Steven Moreland5553ac42020-11-11 02:14:45 +00001998 return RUN_ALL_TESTS();
1999}