blob: 7cd34a3b5a8c4e6cef94b8f7860af7a05904409d [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 Moreland73aa6f82023-03-15 21:49:07 +0000468
469 // b/272429574 - below 500ms, the test fails
470 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700471}
472
Andrei Homescua858b0e2022-08-01 23:43:09 +0000473TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
474 if (clientOrServerSingleThreaded()) {
475 GTEST_SKIP() << "This test requires multiple threads";
476 }
477
Yifan Hong1f44f982021-10-08 17:16:47 -0700478 constexpr size_t kNumThreads = 20;
479 constexpr size_t kNumOutgoingConnections = 10;
480 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
481 auto proc = createRpcTestSocketServerProcess(
482 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000483
484 // b/272429574 - below 500ms, the test fails
485 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000486}
487
Andrei Homescua858b0e2022-08-01 23:43:09 +0000488TEST_P(BinderRpc, ThreadingStressTest) {
489 if (clientOrServerSingleThreaded()) {
490 GTEST_SKIP() << "This test requires multiple threads";
491 }
492
Steven Moreland27f620a2023-03-06 19:44:36 +0000493 constexpr size_t kNumClientThreads = 5;
494 constexpr size_t kNumServerThreads = 5;
495 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000496
Steven Moreland4313d7e2021-07-15 23:41:22 +0000497 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000498
499 std::vector<std::thread> threads;
500 for (size_t i = 0; i < kNumClientThreads; i++) {
501 threads.push_back(std::thread([&] {
502 for (size_t j = 0; j < kNumCalls; j++) {
503 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000504 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000505 EXPECT_EQ(proc.rootBinder, out);
506 }
507 }));
508 }
509
510 for (auto& t : threads) t.join();
511}
512
Steven Moreland925ba0a2021-09-17 18:06:32 -0700513static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
514 std::vector<std::thread> threads;
515 for (size_t i = 0; i < threadCount; i++) {
516 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
517 }
518 for (auto& t : threads) t.join();
519}
520
Andrei Homescua858b0e2022-08-01 23:43:09 +0000521TEST_P(BinderRpc, OnewayStressTest) {
522 if (clientOrServerSingleThreaded()) {
523 GTEST_SKIP() << "This test requires multiple threads";
524 }
525
Steven Morelandc6046982021-04-20 00:49:42 +0000526 constexpr size_t kNumClientThreads = 10;
527 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700528 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000529
Steven Moreland4313d7e2021-07-15 23:41:22 +0000530 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000531
532 std::vector<std::thread> threads;
533 for (size_t i = 0; i < kNumClientThreads; i++) {
534 threads.push_back(std::thread([&] {
535 for (size_t j = 0; j < kNumCalls; j++) {
536 EXPECT_OK(proc.rootIface->sendString("a"));
537 }
Steven Morelandc6046982021-04-20 00:49:42 +0000538 }));
539 }
540
541 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700542
543 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000544}
545
Frederick Mayleb0221d12022-10-03 23:10:53 +0000546TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
547 if (!supportsFdTransport()) {
548 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
549 }
550 if (clientOrServerSingleThreaded()) {
551 GTEST_SKIP() << "This test requires multiple threads";
552 }
553
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000554 constexpr size_t kNumServerThreads = 3;
555
Frederick Mayleb0221d12022-10-03 23:10:53 +0000556 // This test forces a oneway transaction to be queued by issuing two
557 // `blockingSendFdOneway` calls, then drains the queue by issuing two
558 // `blockingRecvFd` calls.
559 //
560 // For more details about the queuing semantics see
561 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
562
563 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000564 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000565 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
566 .serverSupportedFileDescriptorTransportModes =
567 {RpcSession::FileDescriptorTransportMode::UNIX},
568 });
569
570 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
571 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
572 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
573 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
574
575 android::os::ParcelFileDescriptor fdA;
576 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
577 std::string result;
578 CHECK(android::base::ReadFdToString(fdA.get(), &result));
579 EXPECT_EQ(result, "a");
580
581 android::os::ParcelFileDescriptor fdB;
582 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
583 CHECK(android::base::ReadFdToString(fdB.get(), &result));
584 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000585
586 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000587}
588
Andrei Homescua858b0e2022-08-01 23:43:09 +0000589TEST_P(BinderRpc, OnewayCallQueueing) {
590 if (clientOrServerSingleThreaded()) {
591 GTEST_SKIP() << "This test requires multiple threads";
592 }
593
Steven Moreland5553ac42020-11-11 02:14:45 +0000594 constexpr size_t kNumSleeps = 10;
595 constexpr size_t kNumExtraServerThreads = 4;
596 constexpr size_t kSleepMs = 50;
597
598 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000599 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000600
601 EXPECT_OK(proc.rootIface->lock());
602
Steven Moreland1c678802021-09-17 16:48:47 -0700603 size_t epochMsBefore = epochMillis();
604
605 // all these *Async commands should be queued on the server sequentially,
606 // even though there are multiple threads.
607 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000608 proc.rootIface->sleepMsAsync(kSleepMs);
609 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000610 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
611
Steven Moreland1c678802021-09-17 16:48:47 -0700612 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000613 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700614
Steven Moreland5553ac42020-11-11 02:14:45 +0000615 size_t epochMsAfter = epochMillis();
616
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000617 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000618
Steven Moreland925ba0a2021-09-17 18:06:32 -0700619 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000620}
621
Andrei Homescua858b0e2022-08-01 23:43:09 +0000622TEST_P(BinderRpc, OnewayCallExhaustion) {
623 if (clientOrServerSingleThreaded()) {
624 GTEST_SKIP() << "This test requires multiple threads";
625 }
626
Steven Morelandd45be622021-06-04 02:19:37 +0000627 constexpr size_t kNumClients = 2;
628 constexpr size_t kTooLongMs = 1000;
629
Steven Moreland4313d7e2021-07-15 23:41:22 +0000630 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000631
632 // Build up oneway calls on the second session to make sure it terminates
633 // and shuts down. The first session should be unaffected (proc destructor
634 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000635 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000636
637 std::vector<std::thread> threads;
638 for (size_t i = 0; i < kNumClients; i++) {
639 // one of these threads will get stuck queueing a transaction once the
640 // socket fills up, the other will be able to fill up transactions on
641 // this object
642 threads.push_back(std::thread([&] {
643 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
644 }
645 }));
646 }
647 for (auto& t : threads) t.join();
648
649 Status status = iface->sleepMsAsync(kTooLongMs);
650 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
651
Steven Moreland798e0d12021-07-14 23:19:25 +0000652 // now that it has died, wait for the remote session to shutdown
653 std::vector<int32_t> remoteCounts;
654 do {
655 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
656 } while (remoteCounts.size() == kNumClients);
657
Steven Morelandd45be622021-06-04 02:19:37 +0000658 // the second session should be shutdown in the other process by the time we
659 // are able to join above (it'll only be hung up once it finishes processing
660 // any pending commands). We need to erase this session from the record
661 // here, so that the destructor for our session won't check that this
662 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000663 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000664}
665
Devin Moore66d5b7a2022-07-07 21:42:10 +0000666TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000667 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000668 GTEST_SKIP() << "This test requires multiple threads";
669 }
670 class MyDeathRec : public IBinder::DeathRecipient {
671 public:
672 void binderDied(const wp<IBinder>& /* who */) override {
673 dead = true;
674 mCv.notify_one();
675 }
676 std::mutex mMtx;
677 std::condition_variable mCv;
678 bool dead = false;
679 };
680
681 // Death recipient needs to have an incoming connection to be called
682 auto proc = createRpcTestSocketServerProcess(
683 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
684
685 auto dr = sp<MyDeathRec>::make();
686 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
687
688 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
689 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
690 }
691
692 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000693 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000694
695 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000696 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000697 proc.expectAlreadyShutdown = true;
698}
699
700TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000701 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000702 GTEST_SKIP() << "This test requires multiple threads";
703 }
704 class MyDeathRec : public IBinder::DeathRecipient {
705 public:
706 void binderDied(const wp<IBinder>& /* who */) override {
707 dead = true;
708 mCv.notify_one();
709 }
710 std::mutex mMtx;
711 std::condition_variable mCv;
712 bool dead = false;
713 };
714
715 // Death recipient needs to have an incoming connection to be called
716 auto proc = createRpcTestSocketServerProcess(
717 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
718
719 auto dr = sp<MyDeathRec>::make();
720 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
721
722 // Explicitly calling shutDownAndWait will cause the death recipients
723 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000724 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000725
726 std::unique_lock<std::mutex> lock(dr->mMtx);
727 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000728 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000729 }
730 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
731
Andrei Homescu96834632022-10-14 00:49:49 +0000732 proc.proc->terminate();
733 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000734 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
735 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
736 });
737 proc.expectAlreadyShutdown = true;
738}
739
Steven Moreland5ec743f2023-01-18 01:02:06 +0000740TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000741 if (socketType() == SocketType::TIPC) {
742 // This should work, but Trusty takes too long to restart the service
743 GTEST_SKIP() << "Service death test not supported on Trusty";
744 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000745 class MyDeathRec : public IBinder::DeathRecipient {
746 public:
747 void binderDied(const wp<IBinder>& /* who */) override {}
748 };
749
750 auto proc = createRpcTestSocketServerProcess(
751 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
752
753 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000754 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000755}
756
757TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000758 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000759 GTEST_SKIP() << "This test requires multiple threads";
760 }
761 class MyDeathRec : public IBinder::DeathRecipient {
762 public:
763 void binderDied(const wp<IBinder>& /* who */) override {
764 GTEST_FAIL() << "This should not be called after unlinkToDeath";
765 }
766 };
767
768 // Death recipient needs to have an incoming connection to be called
769 auto proc = createRpcTestSocketServerProcess(
770 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
771
772 auto dr = sp<MyDeathRec>::make();
773 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
774 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
775
776 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
777 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
778 }
779
780 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000781 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000782 proc.expectAlreadyShutdown = true;
783}
784
Steven Morelandc1635952021-04-01 16:20:47 +0000785TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000786 if (socketType() == SocketType::TIPC) {
787 // This should work, but Trusty takes too long to restart the service
788 GTEST_SKIP() << "Service death test not supported on Trusty";
789 }
790
Steven Moreland5553ac42020-11-11 02:14:45 +0000791 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000792 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000793
794 // make sure there is some state during crash
795 // 1. we hold their binder
796 sp<IBinderRpcSession> session;
797 EXPECT_OK(proc.rootIface->openSession("happy", &session));
798 // 2. they hold our binder
799 sp<IBinder> binder = new BBinder();
800 EXPECT_OK(proc.rootIface->holdBinder(binder));
801
802 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
803 << "Do death cleanup: " << doDeathCleanup;
804
Andrei Homescu96834632022-10-14 00:49:49 +0000805 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000806 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
807 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
808 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000809 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000810 }
811}
812
Steven Morelandd7302072021-05-15 01:32:04 +0000813TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000814 // This test only works if the current process shared the internal state of
815 // ProcessState with the service across the call to fork(). Both the static
816 // libraries and libbinder.so have their own separate copies of all the
817 // globals, so the test only works when the test client and service both use
818 // libbinder.so (when using static libraries, even a client and service
819 // using the same kind of static library should have separate copies of the
820 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000821 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000822 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
823 "at build time.";
824 }
825
Steven Moreland4313d7e2021-07-15 23:41:22 +0000826 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000827
Andrei Homescu2a298012022-06-15 01:08:54 +0000828 // we can't allocate IPCThreadState so actually the first time should
829 // succeed :(
830 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000831
832 // second time! we catch the error :)
833 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
834
Andrei Homescu96834632022-10-14 00:49:49 +0000835 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000836 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
837 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
838 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000839 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000840}
841
Frederick Mayle69a0c992022-05-26 20:38:39 +0000842TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000843 if (socketType() == SocketType::TIPC) {
844 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
845 }
846
Frederick Mayle69a0c992022-05-26 20:38:39 +0000847 auto proc = createRpcTestSocketServerProcess({
848 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
849 .serverSupportedFileDescriptorTransportModes =
850 {RpcSession::FileDescriptorTransportMode::UNIX},
851 .allowConnectFailure = true,
852 });
Andrei Homescu96834632022-10-14 00:49:49 +0000853 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
854 proc.proc->terminate();
855 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000856 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
857 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
858 });
859 proc.expectAlreadyShutdown = true;
860}
861
862TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000863 if (socketType() == SocketType::TIPC) {
864 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
865 }
866
Frederick Mayle69a0c992022-05-26 20:38:39 +0000867 auto proc = createRpcTestSocketServerProcess({
868 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
869 .serverSupportedFileDescriptorTransportModes =
870 {RpcSession::FileDescriptorTransportMode::NONE},
871 .allowConnectFailure = true,
872 });
Andrei Homescu96834632022-10-14 00:49:49 +0000873 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
874 proc.proc->terminate();
875 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000876 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
877 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
878 });
879 proc.expectAlreadyShutdown = true;
880}
881
882TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000883 if (socketType() == SocketType::TIPC) {
884 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
885 }
886
Frederick Mayle69a0c992022-05-26 20:38:39 +0000887 auto proc = createRpcTestSocketServerProcess({
888 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
889 .serverSupportedFileDescriptorTransportModes =
890 {RpcSession::FileDescriptorTransportMode::NONE,
891 RpcSession::FileDescriptorTransportMode::UNIX},
892 });
893
894 android::os::ParcelFileDescriptor out;
895 auto status = proc.rootIface->echoAsFile("hello", &out);
896 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
897}
898
899TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000900 if (socketType() == SocketType::TIPC) {
901 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
902 }
903
Frederick Mayle69a0c992022-05-26 20:38:39 +0000904 auto proc = createRpcTestSocketServerProcess({
905 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
906 .serverSupportedFileDescriptorTransportModes =
907 {RpcSession::FileDescriptorTransportMode::UNIX},
908 });
909
910 android::os::ParcelFileDescriptor out;
911 auto status = proc.rootIface->echoAsFile("hello", &out);
912 if (!supportsFdTransport()) {
913 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
914 return;
915 }
916 ASSERT_TRUE(status.isOk()) << status;
917
918 std::string result;
919 CHECK(android::base::ReadFdToString(out.get(), &result));
920 EXPECT_EQ(result, "hello");
921}
922
923TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000924 if (socketType() == SocketType::TIPC) {
925 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
926 }
927
Frederick Mayle69a0c992022-05-26 20:38:39 +0000928 auto proc = createRpcTestSocketServerProcess({
929 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
930 .serverSupportedFileDescriptorTransportModes =
931 {RpcSession::FileDescriptorTransportMode::UNIX},
932 });
933
934 std::vector<android::os::ParcelFileDescriptor> files;
935 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
936 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
937 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
938 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
939
940 android::os::ParcelFileDescriptor out;
941 auto status = proc.rootIface->concatFiles(files, &out);
942 if (!supportsFdTransport()) {
943 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
944 return;
945 }
946 ASSERT_TRUE(status.isOk()) << status;
947
948 std::string result;
949 CHECK(android::base::ReadFdToString(out.get(), &result));
950 EXPECT_EQ(result, "123abcd");
951}
952
953TEST_P(BinderRpc, SendMaxFiles) {
954 if (!supportsFdTransport()) {
955 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
956 }
957
958 auto proc = createRpcTestSocketServerProcess({
959 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
960 .serverSupportedFileDescriptorTransportModes =
961 {RpcSession::FileDescriptorTransportMode::UNIX},
962 });
963
964 std::vector<android::os::ParcelFileDescriptor> files;
965 for (int i = 0; i < 253; i++) {
966 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
967 }
968
969 android::os::ParcelFileDescriptor out;
970 auto status = proc.rootIface->concatFiles(files, &out);
971 ASSERT_TRUE(status.isOk()) << status;
972
973 std::string result;
974 CHECK(android::base::ReadFdToString(out.get(), &result));
975 EXPECT_EQ(result, std::string(253, 'a'));
976}
977
978TEST_P(BinderRpc, SendTooManyFiles) {
979 if (!supportsFdTransport()) {
980 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
981 }
982
983 auto proc = createRpcTestSocketServerProcess({
984 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
985 .serverSupportedFileDescriptorTransportModes =
986 {RpcSession::FileDescriptorTransportMode::UNIX},
987 });
988
989 std::vector<android::os::ParcelFileDescriptor> files;
990 for (int i = 0; i < 254; i++) {
991 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
992 }
993
994 android::os::ParcelFileDescriptor out;
995 auto status = proc.rootIface->concatFiles(files, &out);
996 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
997}
998
Andrei Homescufc221502022-10-08 03:51:17 +0000999TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001000 if (socketType() == SocketType::TIPC) {
1001 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1002 }
1003
Andrei Homescufc221502022-10-08 03:51:17 +00001004 auto proc = createRpcTestSocketServerProcess({
1005 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1006 .serverSupportedFileDescriptorTransportModes =
1007 {RpcSession::FileDescriptorTransportMode::UNIX},
1008 });
1009
1010 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1011 ASSERT_NE(badFd, -1);
1012
1013 // Close the file descriptor so it becomes invalid for dup
1014 close(badFd);
1015
1016 Parcel p1;
1017 p1.markForBinder(proc.rootBinder);
1018 p1.writeInt32(3);
1019 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1020
1021 Parcel pRaw;
1022 pRaw.markForBinder(proc.rootBinder);
1023 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1024
1025 pRaw.setDataPosition(0);
1026 EXPECT_EQ(3, pRaw.readInt32());
1027 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1028}
1029
Andrei Homescu68a55612022-08-02 01:25:15 +00001030#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001031TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001032 if constexpr (!kEnableSharedLibs) {
1033 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1034 }
1035
Steven Moreland4313d7e2021-07-15 23:41:22 +00001036 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001037
1038 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1039 ASSERT_NE(binder, nullptr);
1040
1041 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1042}
1043
1044TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001045 if constexpr (!kEnableSharedLibs) {
1046 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1047 }
1048
Steven Moreland4313d7e2021-07-15 23:41:22 +00001049 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001050
1051 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1052 ASSERT_NE(binder, nullptr);
1053
1054 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1055 ASSERT_NE(ndkBinder, nullptr);
1056
1057 std::string out;
1058 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1059 ASSERT_TRUE(status.isOk()) << status.getDescription();
1060 ASSERT_EQ("aoeuaoeu", out);
1061}
Andrei Homescu68a55612022-08-02 01:25:15 +00001062#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001063
Steven Moreland5553ac42020-11-11 02:14:45 +00001064ssize_t countFds() {
1065 DIR* dir = opendir("/proc/self/fd/");
1066 if (dir == nullptr) return -1;
1067 ssize_t ret = 0;
1068 dirent* ent;
1069 while ((ent = readdir(dir)) != nullptr) ret++;
1070 closedir(dir);
1071 return ret;
1072}
1073
Andrei Homescua858b0e2022-08-01 23:43:09 +00001074TEST_P(BinderRpc, Fds) {
1075 if (serverSingleThreaded()) {
1076 GTEST_SKIP() << "This test requires multiple threads";
1077 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001078 if (socketType() == SocketType::TIPC) {
1079 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1080 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001081
Steven Moreland5553ac42020-11-11 02:14:45 +00001082 ssize_t beforeFds = countFds();
1083 ASSERT_GE(beforeFds, 0);
1084 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001085 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001086 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1087 }
1088 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1089}
1090
Steven Morelandda573042021-06-12 01:13:45 +00001091static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001092 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001093 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001094
Andrei Homescu992a4052022-06-28 21:26:18 +00001095 android::base::unique_fd serverFd(
1096 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1097 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1098
1099 sockaddr_vm serverAddr{
1100 .svm_family = AF_VSOCK,
1101 .svm_port = vsockPort,
1102 .svm_cid = VMADDR_CID_ANY,
1103 };
1104 int ret = TEMP_FAILURE_RETRY(
1105 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1106 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1107 strerror(errno));
1108
1109 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1110 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1111 strerror(errno));
1112
1113 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1114 // to see if the kernel supports it. It's safe to use a blocking
1115 // connect because vsock sockets have a 2 second connection timeout,
1116 // and they return ETIMEDOUT after that.
1117 android::base::unique_fd connectFd(
1118 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1119 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1120 strerror(errno));
1121
1122 bool success = false;
1123 sockaddr_vm connectAddr{
1124 .svm_family = AF_VSOCK,
1125 .svm_port = vsockPort,
1126 .svm_cid = VMADDR_CID_LOCAL,
1127 };
1128 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1129 sizeof(connectAddr)));
1130 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1131 android::base::unique_fd acceptFd;
1132 while (true) {
1133 pollfd pfd[]{
1134 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1135 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1136 };
1137 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1138 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1139
1140 if (pfd[0].revents & POLLIN) {
1141 sockaddr_vm acceptAddr;
1142 socklen_t acceptAddrLen = sizeof(acceptAddr);
1143 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1144 reinterpret_cast<sockaddr*>(&acceptAddr),
1145 &acceptAddrLen, SOCK_CLOEXEC));
1146 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1147 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1148 "Truncated address");
1149
1150 // Store the fd in acceptFd so we keep the connection alive
1151 // while polling connectFd
1152 acceptFd.reset(ret);
1153 }
1154
1155 if (pfd[1].revents & POLLOUT) {
1156 // Connect either succeeded or timed out
1157 int connectErrno;
1158 socklen_t connectErrnoLen = sizeof(connectErrno);
1159 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1160 &connectErrnoLen);
1161 LOG_ALWAYS_FATAL_IF(ret == -1,
1162 "Could not getsockopt() after connect() "
1163 "on non-blocking socket: %s.",
1164 strerror(errno));
1165
1166 // We're done, this is all we wanted
1167 success = connectErrno == 0;
1168 break;
1169 }
1170 }
1171 } else {
1172 success = ret == 0;
1173 }
1174
1175 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1176
1177 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001178}
1179
Yifan Hong1deca4b2021-09-10 16:16:44 -07001180static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001181 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1182 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001183
1184 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001185
1186 static bool hasVsockLoopback = testSupportVsockLoopback();
1187
1188 if (hasVsockLoopback) {
1189 ret.push_back(SocketType::VSOCK);
1190 }
1191
1192 return ret;
1193}
1194
Andrei Homescu68a55612022-08-02 01:25:15 +00001195static std::vector<SocketType> testTipcSocketTypes() {
1196#ifdef __ANDROID_VENDOR__
1197 auto port = trustyIpcPort(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1198 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
1199 if (tipcFd >= 0) {
1200 close(tipcFd);
1201 return {SocketType::TIPC};
1202 }
1203#endif // __ANDROID_VENDOR__
1204
1205 // TIPC is not supported on this device, most likely
1206 // because /dev/trusty-ipc-dev0 is missing
1207 return {};
1208}
1209
Yifan Hong702115c2021-06-24 15:39:18 -07001210INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1211 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001212 ::testing::ValuesIn(RpcSecurityValues()),
1213 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001214 ::testing::ValuesIn(testVersions()),
1215 ::testing::Values(false, true),
1216 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001217 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001218
Andrei Homescu68a55612022-08-02 01:25:15 +00001219INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc,
1220 ::testing::Combine(::testing::ValuesIn(testTipcSocketTypes()),
1221 ::testing::Values(RpcSecurity::RAW),
1222 ::testing::ValuesIn(testVersions()),
1223 ::testing::ValuesIn(testVersions()),
1224 ::testing::Values(true), ::testing::Values(true)),
1225 BinderRpc::PrintParamInfo);
1226
Yifan Hong702115c2021-06-24 15:39:18 -07001227class BinderRpcServerRootObject
1228 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001229
1230TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1231 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1232 auto setRootObject = [](bool isStrong) -> SetFn {
1233 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1234 };
1235
Yifan Hong702115c2021-06-24 15:39:18 -07001236 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1237 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001238 auto binder1 = sp<BBinder>::make();
1239 IBinder* binderRaw1 = binder1.get();
1240 setRootObject(isStrong1)(server.get(), binder1);
1241 EXPECT_EQ(binderRaw1, server->getRootObject());
1242 binder1.clear();
1243 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1244
1245 auto binder2 = sp<BBinder>::make();
1246 IBinder* binderRaw2 = binder2.get();
1247 setRootObject(isStrong2)(server.get(), binder2);
1248 EXPECT_EQ(binderRaw2, server->getRootObject());
1249 binder2.clear();
1250 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1251}
1252
1253INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001254 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1255 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001256
Yifan Hong1a235852021-05-13 16:07:47 -07001257class OneOffSignal {
1258public:
1259 // If notify() was previously called, or is called within |duration|, return true; else false.
1260 template <typename R, typename P>
1261 bool wait(std::chrono::duration<R, P> duration) {
1262 std::unique_lock<std::mutex> lock(mMutex);
1263 return mCv.wait_for(lock, duration, [this] { return mValue; });
1264 }
1265 void notify() {
1266 std::unique_lock<std::mutex> lock(mMutex);
1267 mValue = true;
1268 lock.unlock();
1269 mCv.notify_all();
1270 }
1271
1272private:
1273 std::mutex mMutex;
1274 std::condition_variable mCv;
1275 bool mValue = false;
1276};
1277
Yifan Hong194acf22021-06-29 18:44:56 -07001278TEST(BinderRpc, Java) {
1279#if !defined(__ANDROID__)
1280 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1281 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1282 "to binderHostDeviceTest. Hence, just disable this test on host.";
1283#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001284 if constexpr (!kEnableKernelIpc) {
1285 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1286 "at build time.";
1287 }
1288
Yifan Hong194acf22021-06-29 18:44:56 -07001289 sp<IServiceManager> sm = defaultServiceManager();
1290 ASSERT_NE(nullptr, sm);
1291 // Any Java service with non-empty getInterfaceDescriptor() would do.
1292 // Let's pick batteryproperties.
1293 auto binder = sm->checkService(String16("batteryproperties"));
1294 ASSERT_NE(nullptr, binder);
1295 auto descriptor = binder->getInterfaceDescriptor();
1296 ASSERT_GE(descriptor.size(), 0);
1297 ASSERT_EQ(OK, binder->pingBinder());
1298
1299 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001300 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001301 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001302 auto socket = rpcServer->releaseServer();
1303
1304 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001305 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1306
Yifan Honge3caaf22022-01-12 14:46:56 -08001307 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1308 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001309 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001310 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1311 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001312 << statusToString(setRpcClientDebugStatus);
1313 GTEST_SKIP();
1314 }
1315
1316 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001317
1318 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001319 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001320 auto rpcBinder = rpcSession->getRootObject();
1321 ASSERT_NE(nullptr, rpcBinder);
1322
1323 ASSERT_EQ(OK, rpcBinder->pingBinder());
1324
1325 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1326 << "getInterfaceDescriptor should not crash system_server";
1327 ASSERT_EQ(OK, rpcBinder->pingBinder());
1328}
1329
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001330class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1331public:
1332 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1333 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1334 std::to_string(std::get<1>(info.param));
1335 }
1336};
1337
1338TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1339 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1340 int sinkFd = sink.get();
1341 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1342 server->setProtocolVersion(std::get<1>(GetParam()));
1343 ASSERT_FALSE(server->hasServer());
1344 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1345 ASSERT_TRUE(server->hasServer());
1346 base::unique_fd retrieved = server->releaseServer();
1347 ASSERT_FALSE(server->hasServer());
1348 ASSERT_EQ(sinkFd, retrieved.get());
1349}
1350
1351TEST_P(BinderRpcServerOnly, Shutdown) {
1352 if constexpr (!kEnableRpcThreads) {
1353 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1354 }
1355
1356 auto addr = allocateSocketAddress();
1357 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1358 server->setProtocolVersion(std::get<1>(GetParam()));
1359 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1360 auto joinEnds = std::make_shared<OneOffSignal>();
1361
1362 // If things are broken and the thread never stops, don't block other tests. Because the thread
1363 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1364 // shared pointers are passed.
1365 std::thread([server, joinEnds] {
1366 server->join();
1367 joinEnds->notify();
1368 }).detach();
1369
1370 bool shutdown = false;
1371 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001372 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001373 if (server->shutdown()) shutdown = true;
1374 }
1375 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1376
1377 ASSERT_TRUE(joinEnds->wait(2s))
1378 << "After server->shutdown() returns true, join() did not stop after 2s";
1379}
1380
Frederick Mayledc07cf82022-05-26 20:30:12 +00001381INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1382 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1383 ::testing::ValuesIn(testVersions())),
1384 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001385
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001386class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001387public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001388 // Only parameterized only server version because `RpcSession` is bypassed
1389 // in the client half of the tests.
1390 using Param =
1391 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001392 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001393
1394 // A server that handles client socket connections.
1395 class Server {
1396 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001397 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1398
Yifan Hong1deca4b2021-09-10 16:16:44 -07001399 explicit Server() {}
1400 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001401 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001402 [[nodiscard]] AssertionResult setUp(
1403 const Param& param,
1404 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001405 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001406 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001407 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001408 switch (socketType) {
1409 case SocketType::PRECONNECTED: {
1410 return AssertionFailure() << "Not supported by this test";
1411 } break;
1412 case SocketType::UNIX: {
1413 auto addr = allocateSocketAddress();
1414 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1415 if (status != OK) {
1416 return AssertionFailure()
1417 << "setupUnixDomainServer: " << statusToString(status);
1418 }
1419 mConnectToServer = [addr] {
1420 return connectTo(UnixSocketAddress(addr.c_str()));
1421 };
1422 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001423 case SocketType::UNIX_BOOTSTRAP: {
1424 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1425 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1426 return AssertionFailure() << "Socketpair() failed";
1427 }
1428 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1429 std::move(bootstrapFdServer));
1430 if (status != OK) {
1431 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1432 << statusToString(status);
1433 }
1434 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1435 mAcceptConnection = &Server::recvmsgServerConnection;
1436 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1437 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001438 case SocketType::UNIX_RAW: {
1439 auto addr = allocateSocketAddress();
1440 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1441 if (status != OK) {
1442 return AssertionFailure()
1443 << "setupRawSocketServer: " << statusToString(status);
1444 }
1445 mConnectToServer = [addr] {
1446 return connectTo(UnixSocketAddress(addr.c_str()));
1447 };
1448 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001449 case SocketType::VSOCK: {
1450 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001451 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001452 if (status != OK) {
1453 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1454 }
1455 mConnectToServer = [port] {
1456 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1457 };
1458 } break;
1459 case SocketType::INET: {
1460 unsigned int port;
1461 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1462 if (status != OK) {
1463 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1464 }
1465 mConnectToServer = [port] {
1466 const char* addr = kLocalInetAddress;
1467 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1468 if (aiStart == nullptr) return base::unique_fd{};
1469 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1470 auto fd = connectTo(
1471 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1472 if (fd.ok()) return fd;
1473 }
1474 ALOGE("None of the socket address resolved for %s:%u can be connected",
1475 addr, port);
1476 return base::unique_fd{};
1477 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001478 } break;
1479 case SocketType::TIPC: {
1480 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1481 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001482 }
1483 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001484 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001485 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001486 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1487 mSetup = true;
1488 return AssertionSuccess();
1489 }
1490 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1491 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1492 return mCertVerifier;
1493 }
1494 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1495 void start() {
1496 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1497 mThread = std::make_unique<std::thread>(&Server::run, this);
1498 }
David Brazdil21c887c2022-09-23 12:25:18 +01001499
1500 base::unique_fd acceptServerConnection() {
1501 return base::unique_fd(TEMP_FAILURE_RETRY(
1502 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1503 }
1504
1505 base::unique_fd recvmsgServerConnection() {
1506 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1507 int buf;
1508 iovec iov{&buf, sizeof(buf)};
1509
1510 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1511 int savedErrno = errno;
1512 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1513 }
1514 if (fds.size() != 1) {
1515 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1516 }
1517 return std::move(std::get<base::unique_fd>(fds[0]));
1518 }
1519
Yifan Hong1deca4b2021-09-10 16:16:44 -07001520 void run() {
1521 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1522
1523 std::vector<std::thread> threads;
1524 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001525 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001526 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1527 }
1528
1529 for (auto& thread : threads) thread.join();
1530 }
1531 void handleOne(android::base::unique_fd acceptedFd) {
1532 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001533 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001534 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001535 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001536 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001537 }
Yifan Honge07d2732021-09-13 21:59:14 -07001538 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001539 shutdown();
1540 join();
1541 }
1542 void shutdown() { mFdTrigger->trigger(); }
1543
1544 void setPostConnect(
1545 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1546 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001547 }
1548
1549 private:
1550 std::unique_ptr<std::thread> mThread;
1551 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001552 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001553 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001554 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001555 std::unique_ptr<RpcTransportCtx> mCtx;
1556 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1557 std::make_shared<RpcCertificateVerifierSimple>();
1558 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001559 // The function invoked after connection and handshake. By default, it is
1560 // |defaultPostConnect| that sends |kMessage| to the client.
1561 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1562 Server::defaultPostConnect;
1563
1564 void join() {
1565 if (mThread != nullptr) {
1566 mThread->join();
1567 mThread = nullptr;
1568 }
1569 }
1570
1571 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1572 FdTrigger* fdTrigger) {
1573 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001574 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001575 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001576 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001577 if (status != OK) return AssertionFailure() << statusToString(status);
1578 return AssertionSuccess();
1579 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001580 };
1581
1582 class Client {
1583 public:
1584 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1585 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001586 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001587 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1588 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001589 mFdTrigger = FdTrigger::make();
1590 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1591 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1592 return AssertionSuccess();
1593 }
1594 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1595 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1596 return mCertVerifier;
1597 }
Yifan Hong67519322021-09-13 18:51:16 -07001598 // connect() and do handshake
1599 bool setUpTransport() {
1600 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001601 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001602 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1603 return mClientTransport != nullptr;
1604 }
1605 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1606 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1607 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001608 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001609 status_t readStatus =
1610 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001611 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001612 if (readStatus != OK) {
1613 return AssertionFailure() << statusToString(readStatus);
1614 }
1615 if (readMessage != expectedMessage) {
1616 return AssertionFailure()
1617 << "Expected " << expectedMessage << ", actual " << readMessage;
1618 }
1619 return AssertionSuccess();
1620 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001621 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001622 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001623 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1624 return;
1625 }
1626 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001627 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001628 }
1629
Pawan49d74cb2022-08-03 21:19:11 +00001630 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1631
Yifan Hong1deca4b2021-09-10 16:16:44 -07001632 private:
1633 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001634 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001635 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1636 std::unique_ptr<RpcTransportCtx> mCtx;
1637 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1638 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001639 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001640 };
1641
1642 // Make A trust B.
1643 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001644 static status_t trust(RpcSecurity rpcSecurity,
1645 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1646 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001647 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001648 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1649 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1650 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001651 }
1652
1653 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001654};
1655
1656class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1657public:
1658 using Server = RpcTransportTestUtils::Server;
1659 using Client = RpcTransportTestUtils::Client;
1660 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001661 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001662 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1663 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001664 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001665 return ret;
1666 }
1667 static std::vector<ParamType> getRpcTranportTestParams() {
1668 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001669 for (auto serverVersion : testVersions()) {
1670 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1671 for (auto rpcSecurity : RpcSecurityValues()) {
1672 switch (rpcSecurity) {
1673 case RpcSecurity::RAW: {
1674 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1675 } break;
1676 case RpcSecurity::TLS: {
1677 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1678 serverVersion);
1679 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1680 serverVersion);
1681 } break;
1682 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001683 }
1684 }
1685 }
1686 return ret;
1687 }
1688 template <typename A, typename B>
1689 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001690 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1691 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001692 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1693 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001694 void SetUp() override {
1695 if constexpr (!kEnableRpcThreads) {
1696 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1697 }
1698 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001699};
1700
1701TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001702 auto server = std::make_unique<Server>();
1703 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001704
1705 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001706 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001707
1708 ASSERT_EQ(OK, trust(&client, server));
1709 ASSERT_EQ(OK, trust(server, &client));
1710
1711 server->start();
1712 client.run();
1713}
1714
1715TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001716 auto server = std::make_unique<Server>();
1717 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001718
1719 std::vector<Client> clients;
1720 for (int i = 0; i < 2; i++) {
1721 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001722 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001723 ASSERT_EQ(OK, trust(&client, server));
1724 ASSERT_EQ(OK, trust(server, &client));
1725 }
1726
1727 server->start();
1728 for (auto& client : clients) client.run();
1729}
1730
1731TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001732 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1733 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001734
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001735 auto untrustedServer = std::make_unique<Server>();
1736 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001737
1738 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001739 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001740
1741 ASSERT_EQ(OK, trust(untrustedServer, &client));
1742
1743 untrustedServer->start();
1744
1745 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1746 // the client can't verify the server's identity.
1747 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1748 client.run(handshakeOk);
1749}
1750TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001751 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1752 (void)serverVersion;
1753
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001754 auto validServer = std::make_unique<Server>();
1755 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001756
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001757 auto maliciousServer = std::make_unique<Server>();
1758 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001759
1760 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001761 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001762
1763 ASSERT_EQ(OK, trust(&client, validServer));
1764 ASSERT_EQ(OK, trust(validServer, &client));
1765 ASSERT_EQ(OK, trust(maliciousServer, &client));
1766
1767 maliciousServer->start();
1768
1769 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1770 // the client can't verify the server's identity.
1771 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1772 client.run(handshakeOk);
1773}
1774
1775TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001776 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1777 (void)serverVersion;
1778
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001779 auto server = std::make_unique<Server>();
1780 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001781
1782 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001783 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001784
1785 ASSERT_EQ(OK, trust(&client, server));
1786
1787 server->start();
1788
1789 // For TLS, Client should be able to verify server's identity, so client should see
1790 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1791 // identity and should drop the connection, so client shouldn't be able to read anything.
1792 bool readOk = rpcSecurity != RpcSecurity::TLS;
1793 client.run(true, readOk);
1794}
1795
1796TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001797 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1798 (void)serverVersion;
1799
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001800 auto server = std::make_unique<Server>();
1801 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001802
1803 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001804 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001805 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001806 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001807
1808 ASSERT_EQ(OK, trust(&validClient, server));
1809 ASSERT_EQ(OK, trust(&maliciousClient, server));
1810
1811 server->start();
1812
1813 // See UntrustedClient.
1814 bool readOk = rpcSecurity != RpcSecurity::TLS;
1815 maliciousClient.run(true, readOk);
1816}
1817
Yifan Hong67519322021-09-13 18:51:16 -07001818TEST_P(RpcTransportTest, Trigger) {
1819 std::string msg2 = ", world!";
1820 std::mutex writeMutex;
1821 std::condition_variable writeCv;
1822 bool shouldContinueWriting = false;
1823 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001824 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001825 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001826 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1827 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001828 if (status != OK) return AssertionFailure() << statusToString(status);
1829
1830 {
1831 std::unique_lock<std::mutex> lock(writeMutex);
1832 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1833 return AssertionFailure() << "write barrier not cleared in time!";
1834 }
1835 }
1836
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001837 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001838 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1839 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001840 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001841 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001842 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001843 << statusToString(status);
1844 return AssertionSuccess();
1845 };
1846
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001847 auto server = std::make_unique<Server>();
1848 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001849
1850 // Set up client
1851 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001852 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001853
1854 // Exchange keys
1855 ASSERT_EQ(OK, trust(&client, server));
1856 ASSERT_EQ(OK, trust(server, &client));
1857
1858 server->setPostConnect(serverPostConnect);
1859
Yifan Hong67519322021-09-13 18:51:16 -07001860 server->start();
1861 // connect() to server and do handshake
1862 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001863 // read the first message. This ensures that server has finished handshake and start handling
1864 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001865 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001866 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1867 // write is on an FdTrigger that has been shut down.
1868 server->shutdown();
1869 // Continues server thread to write the second message.
1870 {
Yifan Hong22211f82021-09-14 12:32:25 -07001871 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001872 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001873 }
Yifan Hong22211f82021-09-14 12:32:25 -07001874 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001875 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001876 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001877 // On the client side, second read fails with DEAD_OBJECT
1878 ASSERT_FALSE(client.readMessage(msg2));
1879}
1880
Pawan49d74cb2022-08-03 21:19:11 +00001881TEST_P(RpcTransportTest, CheckWaitingForRead) {
1882 std::mutex readMutex;
1883 std::condition_variable readCv;
1884 bool shouldContinueReading = false;
1885 // Server will write data on transport once its started
1886 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1887 std::string message(RpcTransportTestUtils::kMessage);
1888 iovec messageIov{message.data(), message.size()};
1889 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1890 std::nullopt, nullptr);
1891 if (status != OK) return AssertionFailure() << statusToString(status);
1892
1893 {
1894 std::unique_lock<std::mutex> lock(readMutex);
1895 shouldContinueReading = true;
1896 lock.unlock();
1897 readCv.notify_all();
1898 }
1899 return AssertionSuccess();
1900 };
1901
1902 // Setup Server and client
1903 auto server = std::make_unique<Server>();
1904 ASSERT_TRUE(server->setUp(GetParam()));
1905
1906 Client client(server->getConnectToServerFn());
1907 ASSERT_TRUE(client.setUp(GetParam()));
1908
1909 ASSERT_EQ(OK, trust(&client, server));
1910 ASSERT_EQ(OK, trust(server, &client));
1911 server->setPostConnect(serverPostConnect);
1912
1913 server->start();
1914 ASSERT_TRUE(client.setUpTransport());
1915 {
1916 // Wait till server writes data
1917 std::unique_lock<std::mutex> lock(readMutex);
1918 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1919 }
1920
1921 // Since there is no read polling here, we will get polling count 0
1922 ASSERT_FALSE(client.isTransportWaiting());
1923 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1924 // Thread should increment polling count, read and decrement polling count
1925 // Again, polling count should be zero here
1926 ASSERT_FALSE(client.isTransportWaiting());
1927
1928 server->shutdown();
1929}
1930
Yifan Hong1deca4b2021-09-10 16:16:44 -07001931INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001932 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001933 RpcTransportTest::PrintParamInfo);
1934
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001935class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001936 : public testing::TestWithParam<
1937 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001938public:
1939 template <typename A, typename B>
1940 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001941 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1942 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001943 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1944 }
1945 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001946 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1947 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1948 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001949 };
1950};
1951
1952TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001953 if constexpr (!kEnableRpcThreads) {
1954 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1955 }
1956
Frederick Mayledc07cf82022-05-26 20:30:12 +00001957 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001958
1959 std::vector<uint8_t> pkeyData, certData;
1960 {
1961 auto pkey = makeKeyPairForSelfSignedCert();
1962 ASSERT_NE(nullptr, pkey);
1963 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1964 ASSERT_NE(nullptr, cert);
1965 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1966 certData = serializeCertificate(cert.get(), certificateFormat);
1967 }
1968
1969 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1970 auto desCert = deserializeCertificate(certData, certificateFormat);
1971 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001972 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1973 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001974
1975 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1976 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1977
1978 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1979 ASSERT_TRUE(client.setUp(utilsParam));
1980
1981 ASSERT_EQ(OK, trust(&client, server));
1982 ASSERT_EQ(OK, trust(server, &client));
1983
1984 server->start();
1985 client.run();
1986}
1987
1988INSTANTIATE_TEST_CASE_P(
1989 BinderRpc, RpcTransportTlsKeyTest,
1990 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1991 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001992 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1993 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001994 RpcTransportTlsKeyTest::PrintParamInfo);
1995
Steven Morelandc1635952021-04-01 16:20:47 +00001996} // namespace android
1997
1998int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001999 ::testing::InitGoogleTest(&argc, argv);
2000 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002001
Steven Moreland5553ac42020-11-11 02:14:45 +00002002 return RUN_ALL_TESTS();
2003}