blob: a39e14fb105301a46186b6d69fedd2a5a36c1084 [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andrei Homescu9d8adb12022-08-02 04:38:30 +000017#include <aidl/IBinderRpcTest.h>
Frederick Maylea12b0962022-06-25 01:13:22 +000018#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000019
Steven Morelandc1635952021-04-01 16:20:47 +000020#include <chrono>
21#include <cstdlib>
22#include <iostream>
23#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000024#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000025
Andrei Homescu2a298012022-06-15 01:08:54 +000026#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070027#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000029#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000030
Andrei Homescud65666d2023-03-03 07:28:02 +000031#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000032#include <binder/RpcTransportTipcAndroid.h>
33#include <trusty/tipc.h>
Andrei Homescud65666d2023-03-03 07:28:02 +000034#endif // BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000035
Andrei Homescu2a298012022-06-15 01:08:54 +000036#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000037#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000038
Yifan Hong1a235852021-05-13 16:07:47 -070039using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070040using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070041using testing::AssertionFailure;
42using testing::AssertionResult;
43using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070044
Steven Moreland5553ac42020-11-11 02:14:45 +000045namespace android {
46
Andrei Homescu12106de2022-04-27 04:42:21 +000047#ifdef BINDER_TEST_NO_SHARED_LIBS
48constexpr bool kEnableSharedLibs = false;
49#else
50constexpr bool kEnableSharedLibs = true;
51#endif
52
Andrei Homescud65666d2023-03-03 07:28:02 +000053#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000054constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
55#endif
56
Frederick Maylea12b0962022-06-25 01:13:22 +000057static std::string WaitStatusToString(int wstatus) {
58 if (WIFEXITED(wstatus)) {
59 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
60 }
61 if (WIFSIGNALED(wstatus)) {
62 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
63 }
64 return base::StringPrintf("unexpected state %d", wstatus);
65}
66
Steven Moreland276d8df2022-09-28 23:56:39 +000067static void debugBacktrace(pid_t pid) {
68 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
69 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
70}
71
Steven Moreland5553ac42020-11-11 02:14:45 +000072class Process {
73public:
Andrei Homescu96834632022-10-14 00:49:49 +000074 Process(Process&& other)
75 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
76 mReadEnd(std::move(other.mReadEnd)),
77 mWriteEnd(std::move(other.mWriteEnd)) {
78 // The default move constructor doesn't clear mPid after moving it,
79 // which we need to do because the destructor checks for mPid!=0
80 mPid = other.mPid;
81 other.mPid = 0;
82 }
Yifan Hong1deca4b2021-09-10 16:16:44 -070083 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
84 android::base::borrowed_fd /* readEnd */)>& f) {
85 android::base::unique_fd childWriteEnd;
86 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +000087 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
88 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +000089 if (0 == (mPid = fork())) {
90 // racey: assume parent doesn't crash before this is set
91 prctl(PR_SET_PDEATHSIG, SIGHUP);
92
Yifan Hong1deca4b2021-09-10 16:16:44 -070093 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +000094
95 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +000096 }
97 }
98 ~Process() {
99 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000100 int wstatus;
101 waitpid(mPid, &wstatus, 0);
102 if (mCustomExitStatusCheck) {
103 mCustomExitStatusCheck(wstatus);
104 } else {
105 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
106 << "server process failed: " << WaitStatusToString(wstatus);
107 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000108 }
109 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700110 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700111 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000112
Frederick Maylea12b0962022-06-25 01:13:22 +0000113 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
114 mCustomExitStatusCheck = std::move(f);
115 }
116
Frederick Mayle69a0c992022-05-26 20:38:39 +0000117 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
118 void terminate() { kill(mPid, SIGTERM); }
119
Steven Moreland276d8df2022-09-28 23:56:39 +0000120 pid_t getPid() { return mPid; }
121
Steven Moreland5553ac42020-11-11 02:14:45 +0000122private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000123 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000124 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700125 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700126 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000127};
128
129static std::string allocateSocketAddress() {
130 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000131 std::string temp = getenv("TMPDIR") ?: "/tmp";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000132 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700133 unlink(ret.c_str());
134 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000135};
136
Steven Morelandda573042021-06-12 01:13:45 +0000137static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000138 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000139 return vsockPort++;
140}
141
Alice Wang893a9912022-10-24 10:44:09 +0000142static base::unique_fd initUnixSocket(std::string addr) {
143 auto socket_addr = UnixSocketAddress(addr.c_str());
144 base::unique_fd fd(
145 TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
146 CHECK(fd.ok());
147 CHECK_EQ(0, TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize())));
148 return fd;
149}
150
Andrei Homescu96834632022-10-14 00:49:49 +0000151// Destructors need to be defined, even if pure virtual
152ProcessSession::~ProcessSession() {}
153
154class LinuxProcessSession : public ProcessSession {
155public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000156 // reference to process hosting a socket server
157 Process host;
158
Andrei Homescu96834632022-10-14 00:49:49 +0000159 LinuxProcessSession(LinuxProcessSession&&) = default;
160 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
161 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000162 for (auto& session : sessions) {
163 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000164 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000165
Steven 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
Andrei Homescud65666d2023-03-03 07:28:02 +0000215#ifndef BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100216static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
217 base::unique_fd sockClient, sockServer;
218 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
219 int savedErrno = errno;
220 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
221 }
222
223 int zero = 0;
224 iovec iov{&zero, sizeof(zero)};
225 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
226 fds.emplace_back(std::move(sockServer));
227
228 if (sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
229 int savedErrno = errno;
230 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
231 }
232 return std::move(sockClient);
233}
Andrei Homescud65666d2023-03-03 07:28:02 +0000234#endif // BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100235
Andrei Homescu96834632022-10-14 00:49:49 +0000236std::string BinderRpc::PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
237 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
238 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
239 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
240 if (singleThreaded) {
241 ret += "_single_threaded";
Steven Moreland5602a1a2023-03-06 19:25:46 +0000242 } else {
243 ret += "_multi_threaded";
Andrei Homescu96834632022-10-14 00:49:49 +0000244 }
245 if (noKernel) {
246 ret += "_no_kernel";
Steven Moreland5602a1a2023-03-06 19:25:46 +0000247 } else {
248 ret += "_with_kernel";
Andrei Homescu96834632022-10-14 00:49:49 +0000249 }
250 return ret;
251}
Andrei Homescu2a298012022-06-15 01:08:54 +0000252
Andrei Homescu96834632022-10-14 00:49:49 +0000253// This creates a new process serving an interface on a certain number of
254// threads.
255std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
256 const BinderRpcOptions& options) {
257 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Frederick Mayle69a0c992022-05-26 20:38:39 +0000258
Andrei Homescu96834632022-10-14 00:49:49 +0000259 SocketType socketType = std::get<0>(GetParam());
260 RpcSecurity rpcSecurity = std::get<1>(GetParam());
261 uint32_t clientVersion = std::get<2>(GetParam());
262 uint32_t serverVersion = std::get<3>(GetParam());
263 bool singleThreaded = std::get<4>(GetParam());
264 bool noKernel = std::get<5>(GetParam());
265
266 std::string path = android::base::GetExecutableDirectory();
267 auto servicePath = android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
268 singleThreaded ? "_single_threaded" : "",
269 noKernel ? "_no_kernel" : "");
270
Alice Wang1ef010b2022-11-14 09:09:25 +0000271 base::unique_fd bootstrapClientFd, socketFd;
272
Alice Wang893a9912022-10-24 10:44:09 +0000273 auto addr = allocateSocketAddress();
274 // Initializes the socket before the fork/exec.
275 if (socketType == SocketType::UNIX_RAW) {
276 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000277 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
278 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
279 // This is because we cannot pass ParcelFileDescriptor over a pipe.
280 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
281 int savedErrno = errno;
282 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
283 }
Alice Wang893a9912022-10-24 10:44:09 +0000284 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000285
Andrei Homescu96834632022-10-14 00:49:49 +0000286 auto ret = std::make_unique<LinuxProcessSession>(
287 Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000288 if (socketType == SocketType::TIPC) {
289 // Trusty has a single persistent service
290 return;
291 }
292
Andrei Homescu96834632022-10-14 00:49:49 +0000293 auto writeFd = std::to_string(writeEnd.get());
294 auto readFd = std::to_string(readEnd.get());
295 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
296 NULL);
297 }));
298
299 BinderRpcTestServerConfig serverConfig;
300 serverConfig.numThreads = options.numThreads;
301 serverConfig.socketType = static_cast<int32_t>(socketType);
302 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
303 serverConfig.serverVersion = serverVersion;
304 serverConfig.vsockPort = allocateVsockPort();
Alice Wang893a9912022-10-24 10:44:09 +0000305 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000306 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000307 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
308 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
309 static_cast<int32_t>(mode));
310 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000311 if (socketType != SocketType::TIPC) {
312 writeToFd(ret->host.writeEnd(), serverConfig);
313 }
Andrei Homescu96834632022-10-14 00:49:49 +0000314
315 std::vector<sp<RpcSession>> sessions;
316 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
317 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000318 std::unique_ptr<RpcTransportCtxFactory> factory;
319 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000320#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000321 factory = RpcTransportCtxFactoryTipcAndroid::make();
322#else
323 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
324#endif
325 } else {
326 factory = newFactory(rpcSecurity, certVerifier);
327 }
328 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100329 }
330
Andrei Homescu68a55612022-08-02 01:25:15 +0000331 BinderRpcTestServerInfo serverInfo;
332 if (socketType != SocketType::TIPC) {
333 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
334 BinderRpcTestClientInfo clientInfo;
335 for (const auto& session : sessions) {
336 auto& parcelableCert = clientInfo.certs.emplace_back();
337 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
338 }
339 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000340
Andrei Homescu68a55612022-08-02 01:25:15 +0000341 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
342 if (socketType == SocketType::INET) {
343 CHECK_NE(0, serverInfo.port);
344 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000345
Andrei Homescu68a55612022-08-02 01:25:15 +0000346 if (rpcSecurity == RpcSecurity::TLS) {
347 const auto& serverCert = serverInfo.cert.data;
348 CHECK_EQ(OK,
349 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
350 serverCert));
351 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700352 }
353
Andrei Homescu96834632022-10-14 00:49:49 +0000354 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000355
Andrei Homescu96834632022-10-14 00:49:49 +0000356 for (const auto& session : sessions) {
357 CHECK(session->setProtocolVersion(clientVersion));
358 session->setMaxIncomingThreads(options.numIncomingConnections);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000359 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000360 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000361
Andrei Homescu96834632022-10-14 00:49:49 +0000362 switch (socketType) {
363 case SocketType::PRECONNECTED:
364 status = session->setupPreconnectedClient({}, [=]() {
365 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
366 });
Frederick Mayle69a0c992022-05-26 20:38:39 +0000367 break;
Alice Wang893a9912022-10-24 10:44:09 +0000368 case SocketType::UNIX_RAW:
Andrei Homescu96834632022-10-14 00:49:49 +0000369 case SocketType::UNIX:
370 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
371 break;
372 case SocketType::UNIX_BOOTSTRAP:
373 status = session->setupUnixDomainSocketBootstrapClient(
374 base::unique_fd(dup(bootstrapClientFd.get())));
375 break;
376 case SocketType::VSOCK:
377 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
378 break;
379 case SocketType::INET:
380 status = session->setupInetClient("127.0.0.1", serverInfo.port);
381 break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000382 case SocketType::TIPC:
383 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000384#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000385 auto port = trustyIpcPort(serverVersion);
386 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
387 return tipcFd >= 0 ? android::base::unique_fd(tipcFd)
388 : android::base::unique_fd();
389#else
390 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
391 return android::base::unique_fd();
392#endif
393 });
394 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000395 default:
396 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000397 }
Andrei Homescu96834632022-10-14 00:49:49 +0000398 if (options.allowConnectFailure && status != OK) {
399 ret->sessions.clear();
400 break;
401 }
402 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
403 ret->sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000404 }
Andrei Homescu96834632022-10-14 00:49:49 +0000405 return ret;
406}
Steven Morelandc1635952021-04-01 16:20:47 +0000407
Andrei Homescua858b0e2022-08-01 23:43:09 +0000408TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
409 if (clientOrServerSingleThreaded()) {
410 GTEST_SKIP() << "This test requires multiple threads";
411 }
412
Steven Moreland5553ac42020-11-11 02:14:45 +0000413 constexpr size_t kNumThreads = 10;
414
Steven Moreland4313d7e2021-07-15 23:41:22 +0000415 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000416
417 EXPECT_OK(proc.rootIface->lock());
418
419 // block all but one thread taking locks
420 std::vector<std::thread> ts;
421 for (size_t i = 0; i < kNumThreads - 1; i++) {
422 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
423 }
424
Steven Morelandd6d816f2022-12-23 01:37:17 +0000425 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000426
427 // other calls still work
428 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
429
Steven Morelandd6d816f2022-12-23 01:37:17 +0000430 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000431 size_t epochMsBefore = epochMillis();
432 // after this, we should never see a response within this time
433 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
434
435 // this call should be blocked for blockTimeMs
436 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
437
438 size_t epochMsAfter = epochMillis();
439 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
440
441 for (auto& t : ts) t.join();
442}
443
Steven Moreland27f620a2023-03-06 19:44:36 +0000444static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000445 size_t epochMsBefore = epochMillis();
446
447 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700448 for (size_t i = 0; i < numCalls; i++) {
449 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000450 }
451
452 for (auto& t : ts) t.join();
453
454 size_t epochMsAfter = epochMillis();
455
Yifan Hong1f44f982021-10-08 17:16:47 -0700456 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000457
458 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700459 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
460}
461
Andrei Homescua858b0e2022-08-01 23:43:09 +0000462TEST_P(BinderRpc, ThreadPoolOverSaturated) {
463 if (clientOrServerSingleThreaded()) {
464 GTEST_SKIP() << "This test requires multiple threads";
465 }
466
Yifan Hong1f44f982021-10-08 17:16:47 -0700467 constexpr size_t kNumThreads = 10;
468 constexpr size_t kNumCalls = kNumThreads + 3;
469 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland27f620a2023-03-06 19:44:36 +0000470 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 250 /*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 Moreland27f620a2023-03-06 19:44:36 +0000483 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 250 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000484}
485
Andrei Homescua858b0e2022-08-01 23:43:09 +0000486TEST_P(BinderRpc, ThreadingStressTest) {
487 if (clientOrServerSingleThreaded()) {
488 GTEST_SKIP() << "This test requires multiple threads";
489 }
490
Steven Moreland27f620a2023-03-06 19:44:36 +0000491 constexpr size_t kNumClientThreads = 5;
492 constexpr size_t kNumServerThreads = 5;
493 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000494
Steven Moreland4313d7e2021-07-15 23:41:22 +0000495 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000496
497 std::vector<std::thread> threads;
498 for (size_t i = 0; i < kNumClientThreads; i++) {
499 threads.push_back(std::thread([&] {
500 for (size_t j = 0; j < kNumCalls; j++) {
501 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000502 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000503 EXPECT_EQ(proc.rootBinder, out);
504 }
505 }));
506 }
507
508 for (auto& t : threads) t.join();
509}
510
Steven Moreland925ba0a2021-09-17 18:06:32 -0700511static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
512 std::vector<std::thread> threads;
513 for (size_t i = 0; i < threadCount; i++) {
514 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
515 }
516 for (auto& t : threads) t.join();
517}
518
Andrei Homescua858b0e2022-08-01 23:43:09 +0000519TEST_P(BinderRpc, OnewayStressTest) {
520 if (clientOrServerSingleThreaded()) {
521 GTEST_SKIP() << "This test requires multiple threads";
522 }
523
Steven Morelandc6046982021-04-20 00:49:42 +0000524 constexpr size_t kNumClientThreads = 10;
525 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700526 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000527
Steven Moreland4313d7e2021-07-15 23:41:22 +0000528 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000529
530 std::vector<std::thread> threads;
531 for (size_t i = 0; i < kNumClientThreads; i++) {
532 threads.push_back(std::thread([&] {
533 for (size_t j = 0; j < kNumCalls; j++) {
534 EXPECT_OK(proc.rootIface->sendString("a"));
535 }
Steven Morelandc6046982021-04-20 00:49:42 +0000536 }));
537 }
538
539 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700540
541 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000542}
543
Frederick Mayleb0221d12022-10-03 23:10:53 +0000544TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
545 if (!supportsFdTransport()) {
546 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
547 }
548 if (clientOrServerSingleThreaded()) {
549 GTEST_SKIP() << "This test requires multiple threads";
550 }
551
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000552 constexpr size_t kNumServerThreads = 3;
553
Frederick Mayleb0221d12022-10-03 23:10:53 +0000554 // This test forces a oneway transaction to be queued by issuing two
555 // `blockingSendFdOneway` calls, then drains the queue by issuing two
556 // `blockingRecvFd` calls.
557 //
558 // For more details about the queuing semantics see
559 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
560
561 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000562 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000563 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
564 .serverSupportedFileDescriptorTransportModes =
565 {RpcSession::FileDescriptorTransportMode::UNIX},
566 });
567
568 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
569 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
570 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
571 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
572
573 android::os::ParcelFileDescriptor fdA;
574 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
575 std::string result;
576 CHECK(android::base::ReadFdToString(fdA.get(), &result));
577 EXPECT_EQ(result, "a");
578
579 android::os::ParcelFileDescriptor fdB;
580 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
581 CHECK(android::base::ReadFdToString(fdB.get(), &result));
582 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000583
584 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000585}
586
Andrei Homescua858b0e2022-08-01 23:43:09 +0000587TEST_P(BinderRpc, OnewayCallQueueing) {
588 if (clientOrServerSingleThreaded()) {
589 GTEST_SKIP() << "This test requires multiple threads";
590 }
591
Steven Moreland5553ac42020-11-11 02:14:45 +0000592 constexpr size_t kNumSleeps = 10;
593 constexpr size_t kNumExtraServerThreads = 4;
594 constexpr size_t kSleepMs = 50;
595
596 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000597 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000598
599 EXPECT_OK(proc.rootIface->lock());
600
Steven Moreland1c678802021-09-17 16:48:47 -0700601 size_t epochMsBefore = epochMillis();
602
603 // all these *Async commands should be queued on the server sequentially,
604 // even though there are multiple threads.
605 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000606 proc.rootIface->sleepMsAsync(kSleepMs);
607 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000608 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
609
Steven Moreland1c678802021-09-17 16:48:47 -0700610 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000611 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700612
Steven Moreland5553ac42020-11-11 02:14:45 +0000613 size_t epochMsAfter = epochMillis();
614
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000615 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000616
Steven Moreland925ba0a2021-09-17 18:06:32 -0700617 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000618}
619
Andrei Homescua858b0e2022-08-01 23:43:09 +0000620TEST_P(BinderRpc, OnewayCallExhaustion) {
621 if (clientOrServerSingleThreaded()) {
622 GTEST_SKIP() << "This test requires multiple threads";
623 }
624
Steven Morelandd45be622021-06-04 02:19:37 +0000625 constexpr size_t kNumClients = 2;
626 constexpr size_t kTooLongMs = 1000;
627
Steven Moreland4313d7e2021-07-15 23:41:22 +0000628 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000629
630 // Build up oneway calls on the second session to make sure it terminates
631 // and shuts down. The first session should be unaffected (proc destructor
632 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000633 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000634
635 std::vector<std::thread> threads;
636 for (size_t i = 0; i < kNumClients; i++) {
637 // one of these threads will get stuck queueing a transaction once the
638 // socket fills up, the other will be able to fill up transactions on
639 // this object
640 threads.push_back(std::thread([&] {
641 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
642 }
643 }));
644 }
645 for (auto& t : threads) t.join();
646
647 Status status = iface->sleepMsAsync(kTooLongMs);
648 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
649
Steven Moreland798e0d12021-07-14 23:19:25 +0000650 // now that it has died, wait for the remote session to shutdown
651 std::vector<int32_t> remoteCounts;
652 do {
653 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
654 } while (remoteCounts.size() == kNumClients);
655
Steven Morelandd45be622021-06-04 02:19:37 +0000656 // the second session should be shutdown in the other process by the time we
657 // are able to join above (it'll only be hung up once it finishes processing
658 // any pending commands). We need to erase this session from the record
659 // here, so that the destructor for our session won't check that this
660 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000661 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000662}
663
Devin Moore66d5b7a2022-07-07 21:42:10 +0000664TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000665 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000666 GTEST_SKIP() << "This test requires multiple threads";
667 }
668 class MyDeathRec : public IBinder::DeathRecipient {
669 public:
670 void binderDied(const wp<IBinder>& /* who */) override {
671 dead = true;
672 mCv.notify_one();
673 }
674 std::mutex mMtx;
675 std::condition_variable mCv;
676 bool dead = false;
677 };
678
679 // Death recipient needs to have an incoming connection to be called
680 auto proc = createRpcTestSocketServerProcess(
681 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
682
683 auto dr = sp<MyDeathRec>::make();
684 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
685
686 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
687 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
688 }
689
690 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000691 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000692
693 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000694 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000695 proc.expectAlreadyShutdown = true;
696}
697
698TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000699 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000700 GTEST_SKIP() << "This test requires multiple threads";
701 }
702 class MyDeathRec : public IBinder::DeathRecipient {
703 public:
704 void binderDied(const wp<IBinder>& /* who */) override {
705 dead = true;
706 mCv.notify_one();
707 }
708 std::mutex mMtx;
709 std::condition_variable mCv;
710 bool dead = false;
711 };
712
713 // Death recipient needs to have an incoming connection to be called
714 auto proc = createRpcTestSocketServerProcess(
715 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
716
717 auto dr = sp<MyDeathRec>::make();
718 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
719
720 // Explicitly calling shutDownAndWait will cause the death recipients
721 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000722 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000723
724 std::unique_lock<std::mutex> lock(dr->mMtx);
725 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000726 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000727 }
728 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
729
Andrei Homescu96834632022-10-14 00:49:49 +0000730 proc.proc->terminate();
731 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000732 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
733 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
734 });
735 proc.expectAlreadyShutdown = true;
736}
737
Steven Moreland5ec743f2023-01-18 01:02:06 +0000738TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000739 if (socketType() == SocketType::TIPC) {
740 // This should work, but Trusty takes too long to restart the service
741 GTEST_SKIP() << "Service death test not supported on Trusty";
742 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000743 class MyDeathRec : public IBinder::DeathRecipient {
744 public:
745 void binderDied(const wp<IBinder>& /* who */) override {}
746 };
747
748 auto proc = createRpcTestSocketServerProcess(
749 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
750
751 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000752 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000753}
754
755TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000756 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000757 GTEST_SKIP() << "This test requires multiple threads";
758 }
759 class MyDeathRec : public IBinder::DeathRecipient {
760 public:
761 void binderDied(const wp<IBinder>& /* who */) override {
762 GTEST_FAIL() << "This should not be called after unlinkToDeath";
763 }
764 };
765
766 // Death recipient needs to have an incoming connection to be called
767 auto proc = createRpcTestSocketServerProcess(
768 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
769
770 auto dr = sp<MyDeathRec>::make();
771 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
772 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
773
774 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
775 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
776 }
777
778 // need to wait for the session to shutdown so we don't "Leak session"
Andrei Homescu96834632022-10-14 00:49:49 +0000779 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000780 proc.expectAlreadyShutdown = true;
781}
782
Steven Morelandc1635952021-04-01 16:20:47 +0000783TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000784 if (socketType() == SocketType::TIPC) {
785 // This should work, but Trusty takes too long to restart the service
786 GTEST_SKIP() << "Service death test not supported on Trusty";
787 }
788
Steven Moreland5553ac42020-11-11 02:14:45 +0000789 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000790 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000791
792 // make sure there is some state during crash
793 // 1. we hold their binder
794 sp<IBinderRpcSession> session;
795 EXPECT_OK(proc.rootIface->openSession("happy", &session));
796 // 2. they hold our binder
797 sp<IBinder> binder = new BBinder();
798 EXPECT_OK(proc.rootIface->holdBinder(binder));
799
800 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
801 << "Do death cleanup: " << doDeathCleanup;
802
Andrei Homescu96834632022-10-14 00:49:49 +0000803 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000804 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
805 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
806 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000807 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000808 }
809}
810
Steven Morelandd7302072021-05-15 01:32:04 +0000811TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000812 // This test only works if the current process shared the internal state of
813 // ProcessState with the service across the call to fork(). Both the static
814 // libraries and libbinder.so have their own separate copies of all the
815 // globals, so the test only works when the test client and service both use
816 // libbinder.so (when using static libraries, even a client and service
817 // using the same kind of static library should have separate copies of the
818 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000819 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000820 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
821 "at build time.";
822 }
823
Steven Moreland4313d7e2021-07-15 23:41:22 +0000824 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000825
Andrei Homescu2a298012022-06-15 01:08:54 +0000826 // we can't allocate IPCThreadState so actually the first time should
827 // succeed :(
828 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000829
830 // second time! we catch the error :)
831 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
832
Andrei Homescu96834632022-10-14 00:49:49 +0000833 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000834 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
835 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
836 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000837 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000838}
839
Frederick Mayle69a0c992022-05-26 20:38:39 +0000840TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000841 if (socketType() == SocketType::TIPC) {
842 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
843 }
844
Frederick Mayle69a0c992022-05-26 20:38:39 +0000845 auto proc = createRpcTestSocketServerProcess({
846 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
847 .serverSupportedFileDescriptorTransportModes =
848 {RpcSession::FileDescriptorTransportMode::UNIX},
849 .allowConnectFailure = true,
850 });
Andrei Homescu96834632022-10-14 00:49:49 +0000851 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
852 proc.proc->terminate();
853 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000854 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
855 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
856 });
857 proc.expectAlreadyShutdown = true;
858}
859
860TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000861 if (socketType() == SocketType::TIPC) {
862 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
863 }
864
Frederick Mayle69a0c992022-05-26 20:38:39 +0000865 auto proc = createRpcTestSocketServerProcess({
866 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
867 .serverSupportedFileDescriptorTransportModes =
868 {RpcSession::FileDescriptorTransportMode::NONE},
869 .allowConnectFailure = true,
870 });
Andrei Homescu96834632022-10-14 00:49:49 +0000871 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
872 proc.proc->terminate();
873 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000874 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
875 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
876 });
877 proc.expectAlreadyShutdown = true;
878}
879
880TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000881 if (socketType() == SocketType::TIPC) {
882 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
883 }
884
Frederick Mayle69a0c992022-05-26 20:38:39 +0000885 auto proc = createRpcTestSocketServerProcess({
886 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
887 .serverSupportedFileDescriptorTransportModes =
888 {RpcSession::FileDescriptorTransportMode::NONE,
889 RpcSession::FileDescriptorTransportMode::UNIX},
890 });
891
892 android::os::ParcelFileDescriptor out;
893 auto status = proc.rootIface->echoAsFile("hello", &out);
894 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
895}
896
897TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000898 if (socketType() == SocketType::TIPC) {
899 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
900 }
901
Frederick Mayle69a0c992022-05-26 20:38:39 +0000902 auto proc = createRpcTestSocketServerProcess({
903 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
904 .serverSupportedFileDescriptorTransportModes =
905 {RpcSession::FileDescriptorTransportMode::UNIX},
906 });
907
908 android::os::ParcelFileDescriptor out;
909 auto status = proc.rootIface->echoAsFile("hello", &out);
910 if (!supportsFdTransport()) {
911 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
912 return;
913 }
914 ASSERT_TRUE(status.isOk()) << status;
915
916 std::string result;
917 CHECK(android::base::ReadFdToString(out.get(), &result));
918 EXPECT_EQ(result, "hello");
919}
920
921TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000922 if (socketType() == SocketType::TIPC) {
923 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
924 }
925
Frederick Mayle69a0c992022-05-26 20:38:39 +0000926 auto proc = createRpcTestSocketServerProcess({
927 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
928 .serverSupportedFileDescriptorTransportModes =
929 {RpcSession::FileDescriptorTransportMode::UNIX},
930 });
931
932 std::vector<android::os::ParcelFileDescriptor> files;
933 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
934 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
935 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
936 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
937
938 android::os::ParcelFileDescriptor out;
939 auto status = proc.rootIface->concatFiles(files, &out);
940 if (!supportsFdTransport()) {
941 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
942 return;
943 }
944 ASSERT_TRUE(status.isOk()) << status;
945
946 std::string result;
947 CHECK(android::base::ReadFdToString(out.get(), &result));
948 EXPECT_EQ(result, "123abcd");
949}
950
951TEST_P(BinderRpc, SendMaxFiles) {
952 if (!supportsFdTransport()) {
953 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
954 }
955
956 auto proc = createRpcTestSocketServerProcess({
957 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
958 .serverSupportedFileDescriptorTransportModes =
959 {RpcSession::FileDescriptorTransportMode::UNIX},
960 });
961
962 std::vector<android::os::ParcelFileDescriptor> files;
963 for (int i = 0; i < 253; i++) {
964 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
965 }
966
967 android::os::ParcelFileDescriptor out;
968 auto status = proc.rootIface->concatFiles(files, &out);
969 ASSERT_TRUE(status.isOk()) << status;
970
971 std::string result;
972 CHECK(android::base::ReadFdToString(out.get(), &result));
973 EXPECT_EQ(result, std::string(253, 'a'));
974}
975
976TEST_P(BinderRpc, SendTooManyFiles) {
977 if (!supportsFdTransport()) {
978 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
979 }
980
981 auto proc = createRpcTestSocketServerProcess({
982 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
983 .serverSupportedFileDescriptorTransportModes =
984 {RpcSession::FileDescriptorTransportMode::UNIX},
985 });
986
987 std::vector<android::os::ParcelFileDescriptor> files;
988 for (int i = 0; i < 254; i++) {
989 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
990 }
991
992 android::os::ParcelFileDescriptor out;
993 auto status = proc.rootIface->concatFiles(files, &out);
994 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
995}
996
Andrei Homescufc221502022-10-08 03:51:17 +0000997TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000998 if (socketType() == SocketType::TIPC) {
999 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1000 }
1001
Andrei Homescufc221502022-10-08 03:51:17 +00001002 auto proc = createRpcTestSocketServerProcess({
1003 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1004 .serverSupportedFileDescriptorTransportModes =
1005 {RpcSession::FileDescriptorTransportMode::UNIX},
1006 });
1007
1008 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1009 ASSERT_NE(badFd, -1);
1010
1011 // Close the file descriptor so it becomes invalid for dup
1012 close(badFd);
1013
1014 Parcel p1;
1015 p1.markForBinder(proc.rootBinder);
1016 p1.writeInt32(3);
1017 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1018
1019 Parcel pRaw;
1020 pRaw.markForBinder(proc.rootBinder);
1021 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1022
1023 pRaw.setDataPosition(0);
1024 EXPECT_EQ(3, pRaw.readInt32());
1025 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1026}
1027
Andrei Homescu68a55612022-08-02 01:25:15 +00001028#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001029TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001030 if constexpr (!kEnableSharedLibs) {
1031 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1032 }
1033
Steven Moreland4313d7e2021-07-15 23:41:22 +00001034 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001035
1036 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1037 ASSERT_NE(binder, nullptr);
1038
1039 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1040}
1041
1042TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001043 if constexpr (!kEnableSharedLibs) {
1044 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1045 }
1046
Steven Moreland4313d7e2021-07-15 23:41:22 +00001047 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001048
1049 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1050 ASSERT_NE(binder, nullptr);
1051
1052 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1053 ASSERT_NE(ndkBinder, nullptr);
1054
1055 std::string out;
1056 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1057 ASSERT_TRUE(status.isOk()) << status.getDescription();
1058 ASSERT_EQ("aoeuaoeu", out);
1059}
Andrei Homescu68a55612022-08-02 01:25:15 +00001060#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001061
Steven Moreland5553ac42020-11-11 02:14:45 +00001062ssize_t countFds() {
1063 DIR* dir = opendir("/proc/self/fd/");
1064 if (dir == nullptr) return -1;
1065 ssize_t ret = 0;
1066 dirent* ent;
1067 while ((ent = readdir(dir)) != nullptr) ret++;
1068 closedir(dir);
1069 return ret;
1070}
1071
Andrei Homescua858b0e2022-08-01 23:43:09 +00001072TEST_P(BinderRpc, Fds) {
1073 if (serverSingleThreaded()) {
1074 GTEST_SKIP() << "This test requires multiple threads";
1075 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001076 if (socketType() == SocketType::TIPC) {
1077 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1078 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001079
Steven Moreland5553ac42020-11-11 02:14:45 +00001080 ssize_t beforeFds = countFds();
1081 ASSERT_GE(beforeFds, 0);
1082 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001083 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001084 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1085 }
1086 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1087}
1088
Andrei Homescud65666d2023-03-03 07:28:02 +00001089#ifdef BINDER_RPC_TO_TRUSTY_TEST
1090INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc,
1091 ::testing::Combine(::testing::Values(SocketType::TIPC),
1092 ::testing::Values(RpcSecurity::RAW),
1093 ::testing::ValuesIn(testVersions()),
1094 ::testing::ValuesIn(testVersions()),
1095 ::testing::Values(true), ::testing::Values(true)),
1096 BinderRpc::PrintParamInfo);
1097#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandda573042021-06-12 01:13:45 +00001098static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001099 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001100 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001101
Andrei Homescu992a4052022-06-28 21:26:18 +00001102 android::base::unique_fd serverFd(
1103 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1104 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1105
1106 sockaddr_vm serverAddr{
1107 .svm_family = AF_VSOCK,
1108 .svm_port = vsockPort,
1109 .svm_cid = VMADDR_CID_ANY,
1110 };
1111 int ret = TEMP_FAILURE_RETRY(
1112 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1113 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1114 strerror(errno));
1115
1116 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1117 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1118 strerror(errno));
1119
1120 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1121 // to see if the kernel supports it. It's safe to use a blocking
1122 // connect because vsock sockets have a 2 second connection timeout,
1123 // and they return ETIMEDOUT after that.
1124 android::base::unique_fd connectFd(
1125 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1126 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1127 strerror(errno));
1128
1129 bool success = false;
1130 sockaddr_vm connectAddr{
1131 .svm_family = AF_VSOCK,
1132 .svm_port = vsockPort,
1133 .svm_cid = VMADDR_CID_LOCAL,
1134 };
1135 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1136 sizeof(connectAddr)));
1137 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1138 android::base::unique_fd acceptFd;
1139 while (true) {
1140 pollfd pfd[]{
1141 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1142 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1143 };
1144 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1145 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1146
1147 if (pfd[0].revents & POLLIN) {
1148 sockaddr_vm acceptAddr;
1149 socklen_t acceptAddrLen = sizeof(acceptAddr);
1150 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1151 reinterpret_cast<sockaddr*>(&acceptAddr),
1152 &acceptAddrLen, SOCK_CLOEXEC));
1153 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1154 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1155 "Truncated address");
1156
1157 // Store the fd in acceptFd so we keep the connection alive
1158 // while polling connectFd
1159 acceptFd.reset(ret);
1160 }
1161
1162 if (pfd[1].revents & POLLOUT) {
1163 // Connect either succeeded or timed out
1164 int connectErrno;
1165 socklen_t connectErrnoLen = sizeof(connectErrno);
1166 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1167 &connectErrnoLen);
1168 LOG_ALWAYS_FATAL_IF(ret == -1,
1169 "Could not getsockopt() after connect() "
1170 "on non-blocking socket: %s.",
1171 strerror(errno));
1172
1173 // We're done, this is all we wanted
1174 success = connectErrno == 0;
1175 break;
1176 }
1177 }
1178 } else {
1179 success = ret == 0;
1180 }
1181
1182 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1183
1184 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001185}
1186
Yifan Hong1deca4b2021-09-10 16:16:44 -07001187static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001188 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1189 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001190
1191 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001192
1193 static bool hasVsockLoopback = testSupportVsockLoopback();
1194
1195 if (hasVsockLoopback) {
1196 ret.push_back(SocketType::VSOCK);
1197 }
1198
1199 return ret;
1200}
1201
Yifan Hong702115c2021-06-24 15:39:18 -07001202INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1203 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001204 ::testing::ValuesIn(RpcSecurityValues()),
1205 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001206 ::testing::ValuesIn(testVersions()),
1207 ::testing::Values(false, true),
1208 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001209 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001210
Yifan Hong702115c2021-06-24 15:39:18 -07001211class BinderRpcServerRootObject
1212 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001213
1214TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1215 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1216 auto setRootObject = [](bool isStrong) -> SetFn {
1217 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1218 };
1219
Yifan Hong702115c2021-06-24 15:39:18 -07001220 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1221 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001222 auto binder1 = sp<BBinder>::make();
1223 IBinder* binderRaw1 = binder1.get();
1224 setRootObject(isStrong1)(server.get(), binder1);
1225 EXPECT_EQ(binderRaw1, server->getRootObject());
1226 binder1.clear();
1227 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1228
1229 auto binder2 = sp<BBinder>::make();
1230 IBinder* binderRaw2 = binder2.get();
1231 setRootObject(isStrong2)(server.get(), binder2);
1232 EXPECT_EQ(binderRaw2, server->getRootObject());
1233 binder2.clear();
1234 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1235}
1236
1237INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001238 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1239 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001240
Yifan Hong1a235852021-05-13 16:07:47 -07001241class OneOffSignal {
1242public:
1243 // If notify() was previously called, or is called within |duration|, return true; else false.
1244 template <typename R, typename P>
1245 bool wait(std::chrono::duration<R, P> duration) {
1246 std::unique_lock<std::mutex> lock(mMutex);
1247 return mCv.wait_for(lock, duration, [this] { return mValue; });
1248 }
1249 void notify() {
1250 std::unique_lock<std::mutex> lock(mMutex);
1251 mValue = true;
1252 lock.unlock();
1253 mCv.notify_all();
1254 }
1255
1256private:
1257 std::mutex mMutex;
1258 std::condition_variable mCv;
1259 bool mValue = false;
1260};
1261
Yifan Hong194acf22021-06-29 18:44:56 -07001262TEST(BinderRpc, Java) {
1263#if !defined(__ANDROID__)
1264 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1265 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1266 "to binderHostDeviceTest. Hence, just disable this test on host.";
1267#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001268 if constexpr (!kEnableKernelIpc) {
1269 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1270 "at build time.";
1271 }
1272
Yifan Hong194acf22021-06-29 18:44:56 -07001273 sp<IServiceManager> sm = defaultServiceManager();
1274 ASSERT_NE(nullptr, sm);
1275 // Any Java service with non-empty getInterfaceDescriptor() would do.
1276 // Let's pick batteryproperties.
1277 auto binder = sm->checkService(String16("batteryproperties"));
1278 ASSERT_NE(nullptr, binder);
1279 auto descriptor = binder->getInterfaceDescriptor();
1280 ASSERT_GE(descriptor.size(), 0);
1281 ASSERT_EQ(OK, binder->pingBinder());
1282
1283 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001284 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001285 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001286 auto socket = rpcServer->releaseServer();
1287
1288 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001289 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1290
Yifan Honge3caaf22022-01-12 14:46:56 -08001291 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1292 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001293 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001294 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1295 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001296 << statusToString(setRpcClientDebugStatus);
1297 GTEST_SKIP();
1298 }
1299
1300 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001301
1302 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001303 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001304 auto rpcBinder = rpcSession->getRootObject();
1305 ASSERT_NE(nullptr, rpcBinder);
1306
1307 ASSERT_EQ(OK, rpcBinder->pingBinder());
1308
1309 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1310 << "getInterfaceDescriptor should not crash system_server";
1311 ASSERT_EQ(OK, rpcBinder->pingBinder());
1312}
1313
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001314class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1315public:
1316 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1317 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1318 std::to_string(std::get<1>(info.param));
1319 }
1320};
1321
1322TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1323 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1324 int sinkFd = sink.get();
1325 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1326 server->setProtocolVersion(std::get<1>(GetParam()));
1327 ASSERT_FALSE(server->hasServer());
1328 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1329 ASSERT_TRUE(server->hasServer());
1330 base::unique_fd retrieved = server->releaseServer();
1331 ASSERT_FALSE(server->hasServer());
1332 ASSERT_EQ(sinkFd, retrieved.get());
1333}
1334
1335TEST_P(BinderRpcServerOnly, Shutdown) {
1336 if constexpr (!kEnableRpcThreads) {
1337 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1338 }
1339
1340 auto addr = allocateSocketAddress();
1341 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1342 server->setProtocolVersion(std::get<1>(GetParam()));
1343 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1344 auto joinEnds = std::make_shared<OneOffSignal>();
1345
1346 // If things are broken and the thread never stops, don't block other tests. Because the thread
1347 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1348 // shared pointers are passed.
1349 std::thread([server, joinEnds] {
1350 server->join();
1351 joinEnds->notify();
1352 }).detach();
1353
1354 bool shutdown = false;
1355 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001356 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001357 if (server->shutdown()) shutdown = true;
1358 }
1359 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1360
1361 ASSERT_TRUE(joinEnds->wait(2s))
1362 << "After server->shutdown() returns true, join() did not stop after 2s";
1363}
1364
Frederick Mayledc07cf82022-05-26 20:30:12 +00001365INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1366 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1367 ::testing::ValuesIn(testVersions())),
1368 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001369
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001370class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001371public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001372 // Only parameterized only server version because `RpcSession` is bypassed
1373 // in the client half of the tests.
1374 using Param =
1375 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001376 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001377
1378 // A server that handles client socket connections.
1379 class Server {
1380 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001381 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1382
Yifan Hong1deca4b2021-09-10 16:16:44 -07001383 explicit Server() {}
1384 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001385 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001386 [[nodiscard]] AssertionResult setUp(
1387 const Param& param,
1388 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001389 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001390 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001391 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001392 switch (socketType) {
1393 case SocketType::PRECONNECTED: {
1394 return AssertionFailure() << "Not supported by this test";
1395 } break;
1396 case SocketType::UNIX: {
1397 auto addr = allocateSocketAddress();
1398 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1399 if (status != OK) {
1400 return AssertionFailure()
1401 << "setupUnixDomainServer: " << statusToString(status);
1402 }
1403 mConnectToServer = [addr] {
1404 return connectTo(UnixSocketAddress(addr.c_str()));
1405 };
1406 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001407 case SocketType::UNIX_BOOTSTRAP: {
1408 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1409 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1410 return AssertionFailure() << "Socketpair() failed";
1411 }
1412 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1413 std::move(bootstrapFdServer));
1414 if (status != OK) {
1415 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1416 << statusToString(status);
1417 }
1418 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1419 mAcceptConnection = &Server::recvmsgServerConnection;
1420 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1421 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001422 case SocketType::UNIX_RAW: {
1423 auto addr = allocateSocketAddress();
1424 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1425 if (status != OK) {
1426 return AssertionFailure()
1427 << "setupRawSocketServer: " << statusToString(status);
1428 }
1429 mConnectToServer = [addr] {
1430 return connectTo(UnixSocketAddress(addr.c_str()));
1431 };
1432 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001433 case SocketType::VSOCK: {
1434 auto port = allocateVsockPort();
David Brazdila47dfda2022-11-22 22:52:19 +00001435 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001436 if (status != OK) {
1437 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1438 }
1439 mConnectToServer = [port] {
1440 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1441 };
1442 } break;
1443 case SocketType::INET: {
1444 unsigned int port;
1445 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1446 if (status != OK) {
1447 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1448 }
1449 mConnectToServer = [port] {
1450 const char* addr = kLocalInetAddress;
1451 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1452 if (aiStart == nullptr) return base::unique_fd{};
1453 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1454 auto fd = connectTo(
1455 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1456 if (fd.ok()) return fd;
1457 }
1458 ALOGE("None of the socket address resolved for %s:%u can be connected",
1459 addr, port);
1460 return base::unique_fd{};
1461 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001462 } break;
1463 case SocketType::TIPC: {
1464 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1465 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001466 }
1467 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001468 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001469 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001470 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1471 mSetup = true;
1472 return AssertionSuccess();
1473 }
1474 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1475 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1476 return mCertVerifier;
1477 }
1478 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1479 void start() {
1480 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1481 mThread = std::make_unique<std::thread>(&Server::run, this);
1482 }
David Brazdil21c887c2022-09-23 12:25:18 +01001483
1484 base::unique_fd acceptServerConnection() {
1485 return base::unique_fd(TEMP_FAILURE_RETRY(
1486 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1487 }
1488
1489 base::unique_fd recvmsgServerConnection() {
1490 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1491 int buf;
1492 iovec iov{&buf, sizeof(buf)};
1493
1494 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1495 int savedErrno = errno;
1496 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1497 }
1498 if (fds.size() != 1) {
1499 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1500 }
1501 return std::move(std::get<base::unique_fd>(fds[0]));
1502 }
1503
Yifan Hong1deca4b2021-09-10 16:16:44 -07001504 void run() {
1505 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1506
1507 std::vector<std::thread> threads;
1508 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001509 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001510 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1511 }
1512
1513 for (auto& thread : threads) thread.join();
1514 }
1515 void handleOne(android::base::unique_fd acceptedFd) {
1516 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001517 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001518 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001519 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001520 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001521 }
Yifan Honge07d2732021-09-13 21:59:14 -07001522 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001523 shutdown();
1524 join();
1525 }
1526 void shutdown() { mFdTrigger->trigger(); }
1527
1528 void setPostConnect(
1529 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1530 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001531 }
1532
1533 private:
1534 std::unique_ptr<std::thread> mThread;
1535 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001536 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001537 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001538 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001539 std::unique_ptr<RpcTransportCtx> mCtx;
1540 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1541 std::make_shared<RpcCertificateVerifierSimple>();
1542 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001543 // The function invoked after connection and handshake. By default, it is
1544 // |defaultPostConnect| that sends |kMessage| to the client.
1545 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1546 Server::defaultPostConnect;
1547
1548 void join() {
1549 if (mThread != nullptr) {
1550 mThread->join();
1551 mThread = nullptr;
1552 }
1553 }
1554
1555 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1556 FdTrigger* fdTrigger) {
1557 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001558 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001559 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001560 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001561 if (status != OK) return AssertionFailure() << statusToString(status);
1562 return AssertionSuccess();
1563 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001564 };
1565
1566 class Client {
1567 public:
1568 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1569 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001570 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001571 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1572 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001573 mFdTrigger = FdTrigger::make();
1574 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1575 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1576 return AssertionSuccess();
1577 }
1578 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1579 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1580 return mCertVerifier;
1581 }
Yifan Hong67519322021-09-13 18:51:16 -07001582 // connect() and do handshake
1583 bool setUpTransport() {
1584 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001585 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001586 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1587 return mClientTransport != nullptr;
1588 }
1589 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1590 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1591 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001592 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001593 status_t readStatus =
1594 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001595 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001596 if (readStatus != OK) {
1597 return AssertionFailure() << statusToString(readStatus);
1598 }
1599 if (readMessage != expectedMessage) {
1600 return AssertionFailure()
1601 << "Expected " << expectedMessage << ", actual " << readMessage;
1602 }
1603 return AssertionSuccess();
1604 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001605 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001606 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001607 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1608 return;
1609 }
1610 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001611 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001612 }
1613
Pawan49d74cb2022-08-03 21:19:11 +00001614 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1615
Yifan Hong1deca4b2021-09-10 16:16:44 -07001616 private:
1617 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001618 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001619 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1620 std::unique_ptr<RpcTransportCtx> mCtx;
1621 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1622 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001623 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001624 };
1625
1626 // Make A trust B.
1627 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001628 static status_t trust(RpcSecurity rpcSecurity,
1629 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1630 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001631 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001632 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1633 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1634 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001635 }
1636
1637 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001638};
1639
1640class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1641public:
1642 using Server = RpcTransportTestUtils::Server;
1643 using Client = RpcTransportTestUtils::Client;
1644 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001645 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001646 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1647 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001648 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001649 return ret;
1650 }
1651 static std::vector<ParamType> getRpcTranportTestParams() {
1652 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001653 for (auto serverVersion : testVersions()) {
1654 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1655 for (auto rpcSecurity : RpcSecurityValues()) {
1656 switch (rpcSecurity) {
1657 case RpcSecurity::RAW: {
1658 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1659 } break;
1660 case RpcSecurity::TLS: {
1661 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1662 serverVersion);
1663 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1664 serverVersion);
1665 } break;
1666 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001667 }
1668 }
1669 }
1670 return ret;
1671 }
1672 template <typename A, typename B>
1673 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001674 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1675 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001676 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1677 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001678 void SetUp() override {
1679 if constexpr (!kEnableRpcThreads) {
1680 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1681 }
1682 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001683};
1684
1685TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001686 auto server = std::make_unique<Server>();
1687 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001688
1689 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001690 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001691
1692 ASSERT_EQ(OK, trust(&client, server));
1693 ASSERT_EQ(OK, trust(server, &client));
1694
1695 server->start();
1696 client.run();
1697}
1698
1699TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001700 auto server = std::make_unique<Server>();
1701 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001702
1703 std::vector<Client> clients;
1704 for (int i = 0; i < 2; i++) {
1705 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001706 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001707 ASSERT_EQ(OK, trust(&client, server));
1708 ASSERT_EQ(OK, trust(server, &client));
1709 }
1710
1711 server->start();
1712 for (auto& client : clients) client.run();
1713}
1714
1715TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001716 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1717 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001718
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001719 auto untrustedServer = std::make_unique<Server>();
1720 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001721
1722 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001723 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001724
1725 ASSERT_EQ(OK, trust(untrustedServer, &client));
1726
1727 untrustedServer->start();
1728
1729 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1730 // the client can't verify the server's identity.
1731 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1732 client.run(handshakeOk);
1733}
1734TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001735 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1736 (void)serverVersion;
1737
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001738 auto validServer = std::make_unique<Server>();
1739 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001740
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001741 auto maliciousServer = std::make_unique<Server>();
1742 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001743
1744 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001745 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001746
1747 ASSERT_EQ(OK, trust(&client, validServer));
1748 ASSERT_EQ(OK, trust(validServer, &client));
1749 ASSERT_EQ(OK, trust(maliciousServer, &client));
1750
1751 maliciousServer->start();
1752
1753 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1754 // the client can't verify the server's identity.
1755 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1756 client.run(handshakeOk);
1757}
1758
1759TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001760 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1761 (void)serverVersion;
1762
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001763 auto server = std::make_unique<Server>();
1764 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001765
1766 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001767 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001768
1769 ASSERT_EQ(OK, trust(&client, server));
1770
1771 server->start();
1772
1773 // For TLS, Client should be able to verify server's identity, so client should see
1774 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1775 // identity and should drop the connection, so client shouldn't be able to read anything.
1776 bool readOk = rpcSecurity != RpcSecurity::TLS;
1777 client.run(true, readOk);
1778}
1779
1780TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001781 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1782 (void)serverVersion;
1783
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001784 auto server = std::make_unique<Server>();
1785 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001786
1787 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001788 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001789 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001790 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001791
1792 ASSERT_EQ(OK, trust(&validClient, server));
1793 ASSERT_EQ(OK, trust(&maliciousClient, server));
1794
1795 server->start();
1796
1797 // See UntrustedClient.
1798 bool readOk = rpcSecurity != RpcSecurity::TLS;
1799 maliciousClient.run(true, readOk);
1800}
1801
Yifan Hong67519322021-09-13 18:51:16 -07001802TEST_P(RpcTransportTest, Trigger) {
1803 std::string msg2 = ", world!";
1804 std::mutex writeMutex;
1805 std::condition_variable writeCv;
1806 bool shouldContinueWriting = false;
1807 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001808 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001809 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001810 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1811 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001812 if (status != OK) return AssertionFailure() << statusToString(status);
1813
1814 {
1815 std::unique_lock<std::mutex> lock(writeMutex);
1816 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1817 return AssertionFailure() << "write barrier not cleared in time!";
1818 }
1819 }
1820
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001821 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001822 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1823 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001824 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001825 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001826 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001827 << statusToString(status);
1828 return AssertionSuccess();
1829 };
1830
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001831 auto server = std::make_unique<Server>();
1832 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001833
1834 // Set up client
1835 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001836 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001837
1838 // Exchange keys
1839 ASSERT_EQ(OK, trust(&client, server));
1840 ASSERT_EQ(OK, trust(server, &client));
1841
1842 server->setPostConnect(serverPostConnect);
1843
Yifan Hong67519322021-09-13 18:51:16 -07001844 server->start();
1845 // connect() to server and do handshake
1846 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001847 // read the first message. This ensures that server has finished handshake and start handling
1848 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001849 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001850 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1851 // write is on an FdTrigger that has been shut down.
1852 server->shutdown();
1853 // Continues server thread to write the second message.
1854 {
Yifan Hong22211f82021-09-14 12:32:25 -07001855 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001856 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001857 }
Yifan Hong22211f82021-09-14 12:32:25 -07001858 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001859 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001860 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001861 // On the client side, second read fails with DEAD_OBJECT
1862 ASSERT_FALSE(client.readMessage(msg2));
1863}
1864
Pawan49d74cb2022-08-03 21:19:11 +00001865TEST_P(RpcTransportTest, CheckWaitingForRead) {
1866 std::mutex readMutex;
1867 std::condition_variable readCv;
1868 bool shouldContinueReading = false;
1869 // Server will write data on transport once its started
1870 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1871 std::string message(RpcTransportTestUtils::kMessage);
1872 iovec messageIov{message.data(), message.size()};
1873 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1874 std::nullopt, nullptr);
1875 if (status != OK) return AssertionFailure() << statusToString(status);
1876
1877 {
1878 std::unique_lock<std::mutex> lock(readMutex);
1879 shouldContinueReading = true;
1880 lock.unlock();
1881 readCv.notify_all();
1882 }
1883 return AssertionSuccess();
1884 };
1885
1886 // Setup Server and client
1887 auto server = std::make_unique<Server>();
1888 ASSERT_TRUE(server->setUp(GetParam()));
1889
1890 Client client(server->getConnectToServerFn());
1891 ASSERT_TRUE(client.setUp(GetParam()));
1892
1893 ASSERT_EQ(OK, trust(&client, server));
1894 ASSERT_EQ(OK, trust(server, &client));
1895 server->setPostConnect(serverPostConnect);
1896
1897 server->start();
1898 ASSERT_TRUE(client.setUpTransport());
1899 {
1900 // Wait till server writes data
1901 std::unique_lock<std::mutex> lock(readMutex);
1902 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
1903 }
1904
1905 // Since there is no read polling here, we will get polling count 0
1906 ASSERT_FALSE(client.isTransportWaiting());
1907 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1908 // Thread should increment polling count, read and decrement polling count
1909 // Again, polling count should be zero here
1910 ASSERT_FALSE(client.isTransportWaiting());
1911
1912 server->shutdown();
1913}
1914
Yifan Hong1deca4b2021-09-10 16:16:44 -07001915INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001916 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001917 RpcTransportTest::PrintParamInfo);
1918
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001919class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00001920 : public testing::TestWithParam<
1921 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001922public:
1923 template <typename A, typename B>
1924 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001925 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
1926 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001927 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1928 }
1929 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001930 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
1931 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1932 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001933 };
1934};
1935
1936TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001937 if constexpr (!kEnableRpcThreads) {
1938 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1939 }
1940
Frederick Mayledc07cf82022-05-26 20:30:12 +00001941 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001942
1943 std::vector<uint8_t> pkeyData, certData;
1944 {
1945 auto pkey = makeKeyPairForSelfSignedCert();
1946 ASSERT_NE(nullptr, pkey);
1947 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1948 ASSERT_NE(nullptr, cert);
1949 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1950 certData = serializeCertificate(cert.get(), certificateFormat);
1951 }
1952
1953 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1954 auto desCert = deserializeCertificate(certData, certificateFormat);
1955 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001956 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
1957 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001958
1959 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1960 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1961
1962 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1963 ASSERT_TRUE(client.setUp(utilsParam));
1964
1965 ASSERT_EQ(OK, trust(&client, server));
1966 ASSERT_EQ(OK, trust(server, &client));
1967
1968 server->start();
1969 client.run();
1970}
1971
1972INSTANTIATE_TEST_CASE_P(
1973 BinderRpc, RpcTransportTlsKeyTest,
1974 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1975 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001976 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
1977 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001978 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00001979#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001980
Steven Morelandc1635952021-04-01 16:20:47 +00001981} // namespace android
1982
1983int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001984 ::testing::InitGoogleTest(&argc, argv);
1985 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07001986
Steven Moreland5553ac42020-11-11 02:14:45 +00001987 return RUN_ALL_TESTS();
1988}