blob: 8afb4031fbcb19afc5a183836e31740fb80e22a7 [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
Frederick Maylea12b0962022-06-25 01:13:22 +000017#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000018#include <gtest/gtest.h>
19
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 Homescu2a298012022-06-15 01:08:54 +000031#include "binderRpcTestCommon.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000032
Yifan Hong1a235852021-05-13 16:07:47 -070033using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070034using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070035using testing::AssertionFailure;
36using testing::AssertionResult;
37using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070038
Steven Moreland5553ac42020-11-11 02:14:45 +000039namespace android {
40
Andrei Homescu12106de2022-04-27 04:42:21 +000041#ifdef BINDER_TEST_NO_SHARED_LIBS
42constexpr bool kEnableSharedLibs = false;
43#else
44constexpr bool kEnableSharedLibs = true;
45#endif
46
Steven Morelandbf57bce2021-07-26 15:26:12 -070047static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
48 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Frederick Mayle69a0c992022-05-26 20:38:39 +000049
Steven Moreland1fda67b2021-04-02 18:35:50 +000050TEST(BinderRpcParcel, EntireParcelFormatted) {
51 Parcel p;
52 p.writeInt32(3);
53
54 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
55}
56
Frederick Mayledc07cf82022-05-26 20:30:12 +000057class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
Yifan Hong702115c2021-06-24 15:39:18 -070058public:
59 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +000060 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
61 std::to_string(std::get<1>(info.param));
Yifan Hong702115c2021-06-24 15:39:18 -070062 }
63};
64
Frederick Mayledc07cf82022-05-26 20:30:12 +000065TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -070066 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
67 int sinkFd = sink.get();
Frederick Mayledc07cf82022-05-26 20:30:12 +000068 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
69 server->setProtocolVersion(std::get<1>(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -070070 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -070071 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -070072 ASSERT_TRUE(server->hasServer());
73 base::unique_fd retrieved = server->releaseServer();
74 ASSERT_FALSE(server->hasServer());
75 ASSERT_EQ(sinkFd, retrieved.get());
76}
77
Steven Morelandbf57bce2021-07-26 15:26:12 -070078TEST(BinderRpc, CannotUseNextWireVersion) {
79 auto session = RpcSession::make();
80 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
81 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
82 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
83 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
84}
85
86TEST(BinderRpc, CanUseExperimentalWireVersion) {
87 auto session = RpcSession::make();
88 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
89}
90
Steven Moreland5553ac42020-11-11 02:14:45 +000091using android::binder::Status;
92
93#define EXPECT_OK(status) \
94 do { \
95 Status stat = (status); \
96 EXPECT_TRUE(stat.isOk()) << stat; \
97 } while (false)
98
Frederick Maylea12b0962022-06-25 01:13:22 +000099static std::string WaitStatusToString(int wstatus) {
100 if (WIFEXITED(wstatus)) {
101 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
102 }
103 if (WIFSIGNALED(wstatus)) {
104 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
105 }
106 return base::StringPrintf("unexpected state %d", wstatus);
107}
108
Steven Moreland5553ac42020-11-11 02:14:45 +0000109class Process {
110public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700111 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700112 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
113 android::base::borrowed_fd /* readEnd */)>& f) {
114 android::base::unique_fd childWriteEnd;
115 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +0000116 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
117 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000118 if (0 == (mPid = fork())) {
119 // racey: assume parent doesn't crash before this is set
120 prctl(PR_SET_PDEATHSIG, SIGHUP);
121
Yifan Hong1deca4b2021-09-10 16:16:44 -0700122 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000123
124 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000125 }
126 }
127 ~Process() {
128 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000129 int wstatus;
130 waitpid(mPid, &wstatus, 0);
131 if (mCustomExitStatusCheck) {
132 mCustomExitStatusCheck(wstatus);
133 } else {
134 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
135 << "server process failed: " << WaitStatusToString(wstatus);
136 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000137 }
138 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700139 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700140 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000141
Frederick Maylea12b0962022-06-25 01:13:22 +0000142 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
143 mCustomExitStatusCheck = std::move(f);
144 }
145
Frederick Mayle69a0c992022-05-26 20:38:39 +0000146 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
147 void terminate() { kill(mPid, SIGTERM); }
148
Steven Moreland5553ac42020-11-11 02:14:45 +0000149private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000150 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000151 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700152 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700153 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000154};
155
156static std::string allocateSocketAddress() {
157 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000158 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700159 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
160 unlink(ret.c_str());
161 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000162};
163
Steven Morelandda573042021-06-12 01:13:45 +0000164static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000165 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000166 return vsockPort++;
167}
168
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000169struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000170 // reference to process hosting a socket server
171 Process host;
172
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000173 struct SessionInfo {
174 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000175 sp<IBinder> root;
176 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000177
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000178 // client session objects associated with other process
179 // each one represents a separate session
180 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000181
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000182 ProcessSession(ProcessSession&&) = default;
183 ~ProcessSession() {
184 for (auto& session : sessions) {
185 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000186 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000187
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000188 for (auto& info : sessions) {
189 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000190
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000191 EXPECT_NE(nullptr, session);
192 EXPECT_NE(nullptr, session->state());
193 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000194
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000195 wp<RpcSession> weakSession = session;
196 session = nullptr;
197 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000198 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000199 }
200};
201
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000202// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000203// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000204struct BinderRpcTestProcessSession {
205 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000206
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000207 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000208 sp<IBinder> rootBinder;
209
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000210 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000211 sp<IBinderRpcTest> rootIface;
212
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000213 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000214 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000215
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000216 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
217 ~BinderRpcTestProcessSession() {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000218 if (!expectAlreadyShutdown) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000219 EXPECT_NE(nullptr, rootIface);
220 if (rootIface == nullptr) return;
221
Steven Moreland736664b2021-05-01 04:27:25 +0000222 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000223 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000224 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000225 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000226 for (auto remoteCount : remoteCounts) {
227 EXPECT_EQ(remoteCount, 1);
228 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000229
Steven Moreland798e0d12021-07-14 23:19:25 +0000230 // even though it is on another thread, shutdown races with
231 // the transaction reply being written
232 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
233 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
234 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000235 }
236
237 rootIface = nullptr;
238 rootBinder = nullptr;
239 }
240};
241
Yifan Hong1deca4b2021-09-10 16:16:44 -0700242static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700243 base::unique_fd serverFd(
244 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
245 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700246 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
247 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700248
249 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
250 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700251 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
252 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700253 }
254 return serverFd;
255}
256
Andrei Homescu2a298012022-06-15 01:08:54 +0000257using RunServiceFn = void (*)(android::base::borrowed_fd writeEnd,
258 android::base::borrowed_fd readEnd);
259
260class BinderRpc : public ::testing::TestWithParam<
261 std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t, bool, bool>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000262public:
Frederick Mayle69a0c992022-05-26 20:38:39 +0000263 SocketType socketType() const { return std::get<0>(GetParam()); }
264 RpcSecurity rpcSecurity() const { return std::get<1>(GetParam()); }
265 uint32_t clientVersion() const { return std::get<2>(GetParam()); }
266 uint32_t serverVersion() const { return std::get<3>(GetParam()); }
Andrei Homescu2a298012022-06-15 01:08:54 +0000267 bool singleThreaded() const { return std::get<4>(GetParam()); }
268 bool noKernel() const { return std::get<5>(GetParam()); }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000269
270 // Whether the test params support sending FDs in parcels.
271 bool supportsFdTransport() const {
272 return clientVersion() >= 1 && serverVersion() >= 1 && rpcSecurity() != RpcSecurity::TLS &&
273 (socketType() == SocketType::PRECONNECTED || socketType() == SocketType::UNIX);
274 }
275
Yifan Hong702115c2021-06-24 15:39:18 -0700276 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000277 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
278 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
Frederick Mayledc07cf82022-05-26 20:30:12 +0000279 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Andrei Homescu2a298012022-06-15 01:08:54 +0000280 if (singleThreaded) {
281 ret += "_single_threaded";
282 }
283 if (noKernel) {
284 ret += "_no_kernel";
285 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700286 return ret;
287 }
288
Steven Morelandc1635952021-04-01 16:20:47 +0000289 // This creates a new process serving an interface on a certain number of
290 // threads.
Andrei Homescu2a298012022-06-15 01:08:54 +0000291 ProcessSession createRpcTestSocketServerProcessEtc(const BinderRpcOptions& options) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000292 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000293
Yifan Hong702115c2021-06-24 15:39:18 -0700294 SocketType socketType = std::get<0>(GetParam());
295 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000296 uint32_t clientVersion = std::get<2>(GetParam());
297 uint32_t serverVersion = std::get<3>(GetParam());
Andrei Homescu2a298012022-06-15 01:08:54 +0000298 bool singleThreaded = std::get<4>(GetParam());
299 bool noKernel = std::get<5>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000300
Andrei Homescu2a298012022-06-15 01:08:54 +0000301 std::string path = android::base::GetExecutableDirectory();
302 auto servicePath =
303 android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
304 singleThreaded ? "_single_threaded" : "",
305 noKernel ? "_no_kernel" : "");
Steven Morelandc1635952021-04-01 16:20:47 +0000306
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000307 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000308 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700309 android::base::borrowed_fd readEnd) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000310 auto writeFd = std::to_string(writeEnd.get());
311 auto readFd = std::to_string(readEnd.get());
312 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
313 NULL);
Steven Morelandc1635952021-04-01 16:20:47 +0000314 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000315 };
316
Andrei Homescu2a298012022-06-15 01:08:54 +0000317 BinderRpcTestServerConfig serverConfig;
318 serverConfig.numThreads = options.numThreads;
319 serverConfig.socketType = static_cast<int32_t>(socketType);
320 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
321 serverConfig.serverVersion = serverVersion;
322 serverConfig.vsockPort = allocateVsockPort();
323 serverConfig.addr = allocateSocketAddress();
324 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
325 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
326 static_cast<int32_t>(mode));
327 }
328 writeToFd(ret.host.writeEnd(), serverConfig);
329
Yifan Hong1deca4b2021-09-10 16:16:44 -0700330 std::vector<sp<RpcSession>> sessions;
331 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
332 for (size_t i = 0; i < options.numSessions; i++) {
333 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
334 }
335
336 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
337 BinderRpcTestClientInfo clientInfo;
338 for (const auto& session : sessions) {
339 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700340 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700341 }
342 writeToFd(ret.host.writeEnd(), clientInfo);
343
344 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700345 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700346 CHECK_NE(0, serverInfo.port);
347 }
348
349 if (rpcSecurity == RpcSecurity::TLS) {
350 const auto& serverCert = serverInfo.cert.data;
351 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700352 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
353 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700354 }
355
Steven Moreland2372f9d2021-08-05 15:42:01 -0700356 status_t status;
357
Yifan Hong1deca4b2021-09-10 16:16:44 -0700358 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000359 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700360 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700361 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000362 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Moreland659416d2021-05-11 00:47:50 +0000363
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000364 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700365 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700366 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000367 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700368 });
Steven Moreland4198a122021-08-03 17:37:58 -0700369 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000370 case SocketType::UNIX:
Andrei Homescu2a298012022-06-15 01:08:54 +0000371 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000372 break;
373 case SocketType::VSOCK:
Andrei Homescu2a298012022-06-15 01:08:54 +0000374 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000375 break;
376 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700377 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000378 break;
379 default:
380 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000381 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000382 if (options.allowConnectFailure && status != OK) {
383 ret.sessions.clear();
384 break;
385 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700386 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000387 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000388 }
Steven Morelandc1635952021-04-01 16:20:47 +0000389 return ret;
390 }
391
Andrei Homescu2a298012022-06-15 01:08:54 +0000392 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const BinderRpcOptions& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000393 BinderRpcTestProcessSession ret{
Andrei Homescu2a298012022-06-15 01:08:54 +0000394 .proc = createRpcTestSocketServerProcessEtc(options),
Steven Morelandc1635952021-04-01 16:20:47 +0000395 };
396
Frederick Mayle69a0c992022-05-26 20:38:39 +0000397 ret.rootBinder = ret.proc.sessions.empty() ? nullptr : ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000398 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
399
400 return ret;
401 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700402
403 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
404 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000405};
406
Andrei Homescu12106de2022-04-27 04:42:21 +0000407// Test fixture for tests that start multiple threads.
408// This includes tests with one thread but multiple sessions,
409// since a server uses one thread per session.
410class BinderRpcThreads : public BinderRpc {
411public:
412 void SetUp() override {
413 if constexpr (!kEnableRpcThreads) {
414 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
415 }
416 }
417};
418
Steven Morelandc1635952021-04-01 16:20:47 +0000419TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000420 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000421 ASSERT_NE(proc.rootBinder, nullptr);
422 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
423}
424
Steven Moreland4cf688f2021-03-31 01:48:58 +0000425TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000426 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000427 ASSERT_NE(proc.rootBinder, nullptr);
428 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
429}
430
Andrei Homescu12106de2022-04-27 04:42:21 +0000431TEST_P(BinderRpcThreads, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000432 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000433 for (auto session : proc.proc.sessions) {
434 ASSERT_NE(nullptr, session.root);
435 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000436 }
437}
438
Andrei Homescu12106de2022-04-27 04:42:21 +0000439TEST_P(BinderRpcThreads, SeparateRootObject) {
Steven Moreland51c44a92021-10-14 16:50:35 -0700440 SocketType type = std::get<0>(GetParam());
441 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
442 // we can't get port numbers for unix sockets
443 return;
444 }
445
446 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
447
448 int port1 = 0;
449 EXPECT_OK(proc.rootIface->getClientPort(&port1));
450
451 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
452 int port2;
453 EXPECT_OK(rootIface2->getClientPort(&port2));
454
455 // we should have a different IBinderRpcTest object created for each
456 // session, because we use setPerSessionRootObject
457 EXPECT_NE(port1, port2);
458}
459
Steven Morelandc1635952021-04-01 16:20:47 +0000460TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000461 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000462 Parcel data;
463 Parcel reply;
464 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
465}
466
Steven Moreland67753c32021-04-02 18:45:19 +0000467TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700468 auto proc1 = createRpcTestSocketServerProcess({});
469 auto proc2 = createRpcTestSocketServerProcess({});
470
471 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000472
473 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700474 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000475 p1.writeInt32(3);
476
Frederick Maylea4ed5672022-06-17 22:03:38 +0000477 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700478 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
479
Steven Moreland67753c32021-04-02 18:45:19 +0000480 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700481 p2.markForBinder(proc2.rootBinder);
482 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000483
484 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
485 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
486}
487
Steven Morelandc1635952021-04-01 16:20:47 +0000488TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000489 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000490 Parcel data;
491 data.markForBinder(proc.rootBinder);
492 Parcel reply;
493 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
494}
495
Steven Morelandc1635952021-04-01 16:20:47 +0000496TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000497 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000498 EXPECT_OK(proc.rootIface->sendString("asdf"));
499}
500
Steven Morelandc1635952021-04-01 16:20:47 +0000501TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000502 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000503 std::string doubled;
504 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
505 EXPECT_EQ("cool cool ", doubled);
506}
507
Steven Morelandc1635952021-04-01 16:20:47 +0000508TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000509 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000510 std::string single = std::string(1024, 'a');
511 std::string doubled;
512 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
513 EXPECT_EQ(single + single, doubled);
514}
515
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000516TEST_P(BinderRpc, InvalidNullBinderReturn) {
517 auto proc = createRpcTestSocketServerProcess({});
518
519 sp<IBinder> outBinder;
520 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
521}
522
Steven Morelandc1635952021-04-01 16:20:47 +0000523TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000524 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000525
526 int32_t pingResult;
527 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
528 EXPECT_EQ(OK, pingResult);
529
530 EXPECT_EQ(0, MyBinderRpcSession::gNum);
531}
532
Steven Morelandc1635952021-04-01 16:20:47 +0000533TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000534 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000535
536 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
537 sp<IBinder> outBinder;
538 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
539 EXPECT_EQ(inBinder, outBinder);
540
541 wp<IBinder> weak = inBinder;
542 inBinder = nullptr;
543 outBinder = nullptr;
544
545 // Force reading a reply, to process any pending dec refs from the other
546 // process (the other process will process dec refs there before processing
547 // the ping here).
548 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
549
550 EXPECT_EQ(nullptr, weak.promote());
551
552 EXPECT_EQ(0, MyBinderRpcSession::gNum);
553}
554
Steven Morelandc1635952021-04-01 16:20:47 +0000555TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000556 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000557
558 sp<IBinderRpcSession> session;
559 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
560
561 sp<IBinder> inBinder = IInterface::asBinder(session);
562 sp<IBinder> outBinder;
563 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
564 EXPECT_EQ(inBinder, outBinder);
565
566 wp<IBinder> weak = inBinder;
567 session = nullptr;
568 inBinder = nullptr;
569 outBinder = nullptr;
570
571 // Force reading a reply, to process any pending dec refs from the other
572 // process (the other process will process dec refs there before processing
573 // the ping here).
574 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
575
576 EXPECT_EQ(nullptr, weak.promote());
577}
578
Steven Morelandc1635952021-04-01 16:20:47 +0000579TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000580 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000581
582 sp<IBinder> outBinder;
583 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
584 EXPECT_EQ(nullptr, outBinder);
585}
586
Steven Morelandc1635952021-04-01 16:20:47 +0000587TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000588 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000589
590 IBinder* ptr = nullptr;
591 {
592 sp<IBinder> binder = new BBinder();
593 ptr = binder.get();
594 EXPECT_OK(proc.rootIface->holdBinder(binder));
595 }
596
597 sp<IBinder> held;
598 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
599
600 EXPECT_EQ(held.get(), ptr);
601
602 // stop holding binder, because we test to make sure references are cleaned
603 // up
604 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
605 // and flush ref counts
606 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
607}
608
609// START TESTS FOR LIMITATIONS OF SOCKET BINDER
610// These are behavioral differences form regular binder, where certain usecases
611// aren't supported.
612
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000613TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000614 auto proc1 = createRpcTestSocketServerProcess({});
615 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000616
617 sp<IBinder> outBinder;
618 EXPECT_EQ(INVALID_OPERATION,
619 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
620}
621
Andrei Homescu12106de2022-04-27 04:42:21 +0000622TEST_P(BinderRpcThreads, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000623 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000624
625 sp<IBinder> outBinder;
626 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000627 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000628 .transactionError());
629}
630
Steven Morelandc1635952021-04-01 16:20:47 +0000631TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000632 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000633 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
634 "at build time.";
635 }
636
Steven Moreland4313d7e2021-07-15 23:41:22 +0000637 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000638
639 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
640 sp<IBinder> outBinder;
641 EXPECT_EQ(INVALID_OPERATION,
642 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
643}
644
Steven Morelandc1635952021-04-01 16:20:47 +0000645TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000646 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000647 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
648 "at build time.";
649 }
650
Steven Moreland4313d7e2021-07-15 23:41:22 +0000651 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000652
653 // for historical reasons, IServiceManager interface only returns the
654 // exception code
655 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
656 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
657}
658
659// END TESTS FOR LIMITATIONS OF SOCKET BINDER
660
Steven Morelandc1635952021-04-01 16:20:47 +0000661TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000662 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000663
664 sp<IBinder> outBinder;
665 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
666 EXPECT_EQ(proc.rootBinder, outBinder);
667}
668
Steven Morelandc1635952021-04-01 16:20:47 +0000669TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000670 auto proc = createRpcTestSocketServerProcess({
671 // Enable FD support because it uses more stack space and so represents
672 // something closer to a worst case scenario.
673 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
674 .serverSupportedFileDescriptorTransportModes =
675 {RpcSession::FileDescriptorTransportMode::UNIX},
676 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000677
678 auto nastyNester = sp<MyBinderRpcTest>::make();
679 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
680
681 wp<IBinder> weak = nastyNester;
682 nastyNester = nullptr;
683 EXPECT_EQ(nullptr, weak.promote());
684}
685
Steven Morelandc1635952021-04-01 16:20:47 +0000686TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000687 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000688
689 sp<IBinder> a;
690 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
691
692 sp<IBinder> b;
693 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
694
695 EXPECT_EQ(a, b);
696}
697
Steven Morelandc1635952021-04-01 16:20:47 +0000698TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000699 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000700
701 sp<IBinder> a;
702 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
703 wp<IBinder> weak = a;
704 a = nullptr;
705
706 sp<IBinder> b;
707 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
708
709 // this is the wrong behavior, since BpBinder
710 // doesn't implement onIncStrongAttempted
711 // but make sure there is no crash
712 EXPECT_EQ(nullptr, weak.promote());
713
714 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
715
716 // In order to fix this:
717 // - need to have incStrongAttempted reflected across IPC boundary (wait for
718 // response to promote - round trip...)
719 // - sendOnLastWeakRef, to delete entries out of RpcState table
720 EXPECT_EQ(b, weak.promote());
721}
722
723#define expectSessions(expected, iface) \
724 do { \
725 int session; \
726 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
727 EXPECT_EQ(expected, session); \
728 } while (false)
729
Steven Morelandc1635952021-04-01 16:20:47 +0000730TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000731 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000732
733 sp<IBinderRpcSession> session;
734 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
735 std::string out;
736 EXPECT_OK(session->getName(&out));
737 EXPECT_EQ("aoeu", out);
738
739 expectSessions(1, proc.rootIface);
740 session = nullptr;
741 expectSessions(0, proc.rootIface);
742}
743
Steven Morelandc1635952021-04-01 16:20:47 +0000744TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000745 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000746
747 std::vector<sp<IBinderRpcSession>> sessions;
748
749 for (size_t i = 0; i < 15; i++) {
750 expectSessions(i, proc.rootIface);
751 sp<IBinderRpcSession> session;
752 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
753 sessions.push_back(session);
754 }
755 expectSessions(sessions.size(), proc.rootIface);
756 for (size_t i = 0; i < sessions.size(); i++) {
757 std::string out;
758 EXPECT_OK(sessions.at(i)->getName(&out));
759 EXPECT_EQ(std::to_string(i), out);
760 }
761 expectSessions(sessions.size(), proc.rootIface);
762
763 while (!sessions.empty()) {
764 sessions.pop_back();
765 expectSessions(sessions.size(), proc.rootIface);
766 }
767 expectSessions(0, proc.rootIface);
768}
769
770size_t epochMillis() {
771 using std::chrono::duration_cast;
772 using std::chrono::milliseconds;
773 using std::chrono::seconds;
774 using std::chrono::system_clock;
775 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
776}
777
Andrei Homescu12106de2022-04-27 04:42:21 +0000778TEST_P(BinderRpcThreads, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000779 constexpr size_t kNumThreads = 10;
780
Steven Moreland4313d7e2021-07-15 23:41:22 +0000781 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000782
783 EXPECT_OK(proc.rootIface->lock());
784
785 // block all but one thread taking locks
786 std::vector<std::thread> ts;
787 for (size_t i = 0; i < kNumThreads - 1; i++) {
788 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
789 }
790
791 usleep(100000); // give chance for calls on other threads
792
793 // other calls still work
794 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
795
796 constexpr size_t blockTimeMs = 500;
797 size_t epochMsBefore = epochMillis();
798 // after this, we should never see a response within this time
799 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
800
801 // this call should be blocked for blockTimeMs
802 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
803
804 size_t epochMsAfter = epochMillis();
805 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
806
807 for (auto& t : ts) t.join();
808}
809
Yifan Hong1f44f982021-10-08 17:16:47 -0700810void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
811 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000812 size_t epochMsBefore = epochMillis();
813
814 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700815 for (size_t i = 0; i < numCalls; i++) {
816 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000817 }
818
819 for (auto& t : ts) t.join();
820
821 size_t epochMsAfter = epochMillis();
822
Yifan Hong1f44f982021-10-08 17:16:47 -0700823 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000824
825 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700826 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
827}
828
Andrei Homescu12106de2022-04-27 04:42:21 +0000829TEST_P(BinderRpcThreads, ThreadPoolOverSaturated) {
Yifan Hong1f44f982021-10-08 17:16:47 -0700830 constexpr size_t kNumThreads = 10;
831 constexpr size_t kNumCalls = kNumThreads + 3;
832 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
833 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
834}
835
Andrei Homescu12106de2022-04-27 04:42:21 +0000836TEST_P(BinderRpcThreads, ThreadPoolLimitOutgoing) {
Yifan Hong1f44f982021-10-08 17:16:47 -0700837 constexpr size_t kNumThreads = 20;
838 constexpr size_t kNumOutgoingConnections = 10;
839 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
840 auto proc = createRpcTestSocketServerProcess(
841 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
842 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000843}
844
Andrei Homescu12106de2022-04-27 04:42:21 +0000845TEST_P(BinderRpcThreads, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000846 constexpr size_t kNumClientThreads = 10;
847 constexpr size_t kNumServerThreads = 10;
848 constexpr size_t kNumCalls = 100;
849
Steven Moreland4313d7e2021-07-15 23:41:22 +0000850 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000851
852 std::vector<std::thread> threads;
853 for (size_t i = 0; i < kNumClientThreads; i++) {
854 threads.push_back(std::thread([&] {
855 for (size_t j = 0; j < kNumCalls; j++) {
856 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000857 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000858 EXPECT_EQ(proc.rootBinder, out);
859 }
860 }));
861 }
862
863 for (auto& t : threads) t.join();
864}
865
Steven Moreland925ba0a2021-09-17 18:06:32 -0700866static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
867 std::vector<std::thread> threads;
868 for (size_t i = 0; i < threadCount; i++) {
869 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
870 }
871 for (auto& t : threads) t.join();
872}
873
Andrei Homescu12106de2022-04-27 04:42:21 +0000874TEST_P(BinderRpcThreads, OnewayStressTest) {
Steven Morelandc6046982021-04-20 00:49:42 +0000875 constexpr size_t kNumClientThreads = 10;
876 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700877 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000878
Steven Moreland4313d7e2021-07-15 23:41:22 +0000879 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000880
881 std::vector<std::thread> threads;
882 for (size_t i = 0; i < kNumClientThreads; i++) {
883 threads.push_back(std::thread([&] {
884 for (size_t j = 0; j < kNumCalls; j++) {
885 EXPECT_OK(proc.rootIface->sendString("a"));
886 }
Steven Morelandc6046982021-04-20 00:49:42 +0000887 }));
888 }
889
890 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700891
892 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000893}
894
Steven Morelandc1635952021-04-01 16:20:47 +0000895TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000896 constexpr size_t kReallyLongTimeMs = 100;
897 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
898
Steven Moreland4313d7e2021-07-15 23:41:22 +0000899 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000900
901 size_t epochMsBefore = epochMillis();
902
903 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
904
905 size_t epochMsAfter = epochMillis();
906 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
907}
908
Andrei Homescu12106de2022-04-27 04:42:21 +0000909TEST_P(BinderRpcThreads, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000910 constexpr size_t kNumSleeps = 10;
911 constexpr size_t kNumExtraServerThreads = 4;
912 constexpr size_t kSleepMs = 50;
913
914 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000915 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000916
917 EXPECT_OK(proc.rootIface->lock());
918
Steven Moreland1c678802021-09-17 16:48:47 -0700919 size_t epochMsBefore = epochMillis();
920
921 // all these *Async commands should be queued on the server sequentially,
922 // even though there are multiple threads.
923 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000924 proc.rootIface->sleepMsAsync(kSleepMs);
925 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000926 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
927
Steven Moreland1c678802021-09-17 16:48:47 -0700928 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000929 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700930
Steven Moreland5553ac42020-11-11 02:14:45 +0000931 size_t epochMsAfter = epochMillis();
932
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000933 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000934
Steven Moreland925ba0a2021-09-17 18:06:32 -0700935 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000936}
937
Andrei Homescu12106de2022-04-27 04:42:21 +0000938TEST_P(BinderRpcThreads, OnewayCallExhaustion) {
Steven Morelandd45be622021-06-04 02:19:37 +0000939 constexpr size_t kNumClients = 2;
940 constexpr size_t kTooLongMs = 1000;
941
Steven Moreland4313d7e2021-07-15 23:41:22 +0000942 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000943
944 // Build up oneway calls on the second session to make sure it terminates
945 // and shuts down. The first session should be unaffected (proc destructor
946 // checks the first session).
947 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
948
949 std::vector<std::thread> threads;
950 for (size_t i = 0; i < kNumClients; i++) {
951 // one of these threads will get stuck queueing a transaction once the
952 // socket fills up, the other will be able to fill up transactions on
953 // this object
954 threads.push_back(std::thread([&] {
955 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
956 }
957 }));
958 }
959 for (auto& t : threads) t.join();
960
961 Status status = iface->sleepMsAsync(kTooLongMs);
962 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
963
Steven Moreland798e0d12021-07-14 23:19:25 +0000964 // now that it has died, wait for the remote session to shutdown
965 std::vector<int32_t> remoteCounts;
966 do {
967 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
968 } while (remoteCounts.size() == kNumClients);
969
Steven Morelandd45be622021-06-04 02:19:37 +0000970 // the second session should be shutdown in the other process by the time we
971 // are able to join above (it'll only be hung up once it finishes processing
972 // any pending commands). We need to erase this session from the record
973 // here, so that the destructor for our session won't check that this
974 // session is valid, but we still want it to test the other session.
975 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
976}
977
Steven Moreland659416d2021-05-11 00:47:50 +0000978TEST_P(BinderRpc, Callbacks) {
979 const static std::string kTestString = "good afternoon!";
980
Andrei Homescu2a298012022-06-15 01:08:54 +0000981 bool bothSingleThreaded = !kEnableRpcThreads || singleThreaded();
982
Steven Morelandc7d40132021-06-10 03:42:11 +0000983 for (bool callIsOneway : {true, false}) {
984 for (bool callbackIsOneway : {true, false}) {
985 for (bool delayed : {true, false}) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000986 if (bothSingleThreaded && (callIsOneway || callbackIsOneway || delayed)) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000987 // we have no incoming connections to receive the callback
988 continue;
989 }
990
Andrei Homescu2a298012022-06-15 01:08:54 +0000991 size_t numIncomingConnections = bothSingleThreaded ? 0 : 1;
Steven Moreland4313d7e2021-07-15 23:41:22 +0000992 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +0000993 {.numThreads = 1,
994 .numSessions = 1,
Andrei Homescu2a298012022-06-15 01:08:54 +0000995 .numIncomingConnections = numIncomingConnections});
Steven Morelandc7d40132021-06-10 03:42:11 +0000996 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +0000997
Steven Morelandc7d40132021-06-10 03:42:11 +0000998 if (callIsOneway) {
999 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1000 kTestString));
1001 } else {
1002 EXPECT_OK(
1003 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1004 }
Steven Moreland659416d2021-05-11 00:47:50 +00001005
Steven Moreland03ecce62022-05-13 23:22:05 +00001006 // if both transactions are synchronous and the response is sent back on the
1007 // same thread, everything should have happened in a nested call. Otherwise,
1008 // the callback will be processed on another thread.
1009 if (callIsOneway || callbackIsOneway || delayed) {
1010 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001011 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001012 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1013 }
Steven Moreland659416d2021-05-11 00:47:50 +00001014
Steven Morelandc7d40132021-06-10 03:42:11 +00001015 EXPECT_EQ(cb->mValues.size(), 1)
1016 << "callIsOneway: " << callIsOneway
1017 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1018 if (cb->mValues.empty()) continue;
1019 EXPECT_EQ(cb->mValues.at(0), kTestString)
1020 << "callIsOneway: " << callIsOneway
1021 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001022
Steven Morelandc7d40132021-06-10 03:42:11 +00001023 // since we are severing the connection, we need to go ahead and
1024 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001025 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1026 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1027 }
Steven Moreland659416d2021-05-11 00:47:50 +00001028
Steven Moreland1b304292021-07-15 22:59:34 +00001029 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001030 // need to manually shut it down
1031 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Morelandc7d40132021-06-10 03:42:11 +00001032 proc.expectAlreadyShutdown = true;
1033 }
Steven Moreland659416d2021-05-11 00:47:50 +00001034 }
1035 }
1036}
1037
Steven Moreland195edb82021-06-08 02:44:39 +00001038TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001039 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001040 auto cb = sp<MyBinderRpcCallback>::make();
1041
1042 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1043 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1044}
1045
Steven Morelandc1635952021-04-01 16:20:47 +00001046TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001047 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001048 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001049
1050 // make sure there is some state during crash
1051 // 1. we hold their binder
1052 sp<IBinderRpcSession> session;
1053 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1054 // 2. they hold our binder
1055 sp<IBinder> binder = new BBinder();
1056 EXPECT_OK(proc.rootIface->holdBinder(binder));
1057
1058 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1059 << "Do death cleanup: " << doDeathCleanup;
1060
Frederick Maylea12b0962022-06-25 01:13:22 +00001061 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1062 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1063 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1064 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001065 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001066 }
1067}
1068
Steven Morelandd7302072021-05-15 01:32:04 +00001069TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001070 // This test only works if the current process shared the internal state of
1071 // ProcessState with the service across the call to fork(). Both the static
1072 // libraries and libbinder.so have their own separate copies of all the
1073 // globals, so the test only works when the test client and service both use
1074 // libbinder.so (when using static libraries, even a client and service
1075 // using the same kind of static library should have separate copies of the
1076 // variables).
1077 if (!kEnableSharedLibs || singleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001078 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1079 "at build time.";
1080 }
1081
Steven Moreland4313d7e2021-07-15 23:41:22 +00001082 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001083
Andrei Homescu2a298012022-06-15 01:08:54 +00001084 // we can't allocate IPCThreadState so actually the first time should
1085 // succeed :(
1086 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001087
1088 // second time! we catch the error :)
1089 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1090
Frederick Maylea12b0962022-06-25 01:13:22 +00001091 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1092 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1093 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1094 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001095 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001096}
1097
Frederick Mayle69a0c992022-05-26 20:38:39 +00001098TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1099 auto proc = createRpcTestSocketServerProcess({
1100 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1101 .serverSupportedFileDescriptorTransportModes =
1102 {RpcSession::FileDescriptorTransportMode::UNIX},
1103 .allowConnectFailure = true,
1104 });
1105 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1106 proc.proc.host.terminate();
1107 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1108 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1109 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1110 });
1111 proc.expectAlreadyShutdown = true;
1112}
1113
1114TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1115 auto proc = createRpcTestSocketServerProcess({
1116 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1117 .serverSupportedFileDescriptorTransportModes =
1118 {RpcSession::FileDescriptorTransportMode::NONE},
1119 .allowConnectFailure = true,
1120 });
1121 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1122 proc.proc.host.terminate();
1123 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1124 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1125 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1126 });
1127 proc.expectAlreadyShutdown = true;
1128}
1129
1130TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1131 auto proc = createRpcTestSocketServerProcess({
1132 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1133 .serverSupportedFileDescriptorTransportModes =
1134 {RpcSession::FileDescriptorTransportMode::NONE,
1135 RpcSession::FileDescriptorTransportMode::UNIX},
1136 });
1137
1138 android::os::ParcelFileDescriptor out;
1139 auto status = proc.rootIface->echoAsFile("hello", &out);
1140 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1141}
1142
1143TEST_P(BinderRpc, ReceiveFile) {
1144 auto proc = createRpcTestSocketServerProcess({
1145 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1146 .serverSupportedFileDescriptorTransportModes =
1147 {RpcSession::FileDescriptorTransportMode::UNIX},
1148 });
1149
1150 android::os::ParcelFileDescriptor out;
1151 auto status = proc.rootIface->echoAsFile("hello", &out);
1152 if (!supportsFdTransport()) {
1153 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1154 return;
1155 }
1156 ASSERT_TRUE(status.isOk()) << status;
1157
1158 std::string result;
1159 CHECK(android::base::ReadFdToString(out.get(), &result));
1160 EXPECT_EQ(result, "hello");
1161}
1162
1163TEST_P(BinderRpc, SendFiles) {
1164 auto proc = createRpcTestSocketServerProcess({
1165 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1166 .serverSupportedFileDescriptorTransportModes =
1167 {RpcSession::FileDescriptorTransportMode::UNIX},
1168 });
1169
1170 std::vector<android::os::ParcelFileDescriptor> files;
1171 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1172 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1173 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1174 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1175
1176 android::os::ParcelFileDescriptor out;
1177 auto status = proc.rootIface->concatFiles(files, &out);
1178 if (!supportsFdTransport()) {
1179 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1180 return;
1181 }
1182 ASSERT_TRUE(status.isOk()) << status;
1183
1184 std::string result;
1185 CHECK(android::base::ReadFdToString(out.get(), &result));
1186 EXPECT_EQ(result, "123abcd");
1187}
1188
1189TEST_P(BinderRpc, SendMaxFiles) {
1190 if (!supportsFdTransport()) {
1191 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1192 }
1193
1194 auto proc = createRpcTestSocketServerProcess({
1195 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1196 .serverSupportedFileDescriptorTransportModes =
1197 {RpcSession::FileDescriptorTransportMode::UNIX},
1198 });
1199
1200 std::vector<android::os::ParcelFileDescriptor> files;
1201 for (int i = 0; i < 253; i++) {
1202 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1203 }
1204
1205 android::os::ParcelFileDescriptor out;
1206 auto status = proc.rootIface->concatFiles(files, &out);
1207 ASSERT_TRUE(status.isOk()) << status;
1208
1209 std::string result;
1210 CHECK(android::base::ReadFdToString(out.get(), &result));
1211 EXPECT_EQ(result, std::string(253, 'a'));
1212}
1213
1214TEST_P(BinderRpc, SendTooManyFiles) {
1215 if (!supportsFdTransport()) {
1216 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1217 }
1218
1219 auto proc = createRpcTestSocketServerProcess({
1220 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1221 .serverSupportedFileDescriptorTransportModes =
1222 {RpcSession::FileDescriptorTransportMode::UNIX},
1223 });
1224
1225 std::vector<android::os::ParcelFileDescriptor> files;
1226 for (int i = 0; i < 254; i++) {
1227 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1228 }
1229
1230 android::os::ParcelFileDescriptor out;
1231 auto status = proc.rootIface->concatFiles(files, &out);
1232 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1233}
1234
Steven Moreland37aff182021-03-26 02:04:16 +00001235TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001236 if constexpr (!kEnableSharedLibs) {
1237 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1238 }
1239
Steven Moreland4313d7e2021-07-15 23:41:22 +00001240 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001241
1242 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1243 ASSERT_NE(binder, nullptr);
1244
1245 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1246}
1247
1248TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001249 if constexpr (!kEnableSharedLibs) {
1250 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1251 }
1252
Steven Moreland4313d7e2021-07-15 23:41:22 +00001253 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001254
1255 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1256 ASSERT_NE(binder, nullptr);
1257
1258 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1259 ASSERT_NE(ndkBinder, nullptr);
1260
1261 std::string out;
1262 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1263 ASSERT_TRUE(status.isOk()) << status.getDescription();
1264 ASSERT_EQ("aoeuaoeu", out);
1265}
1266
Steven Moreland5553ac42020-11-11 02:14:45 +00001267ssize_t countFds() {
1268 DIR* dir = opendir("/proc/self/fd/");
1269 if (dir == nullptr) return -1;
1270 ssize_t ret = 0;
1271 dirent* ent;
1272 while ((ent = readdir(dir)) != nullptr) ret++;
1273 closedir(dir);
1274 return ret;
1275}
1276
Andrei Homescu12106de2022-04-27 04:42:21 +00001277TEST_P(BinderRpcThreads, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001278 ssize_t beforeFds = countFds();
1279 ASSERT_GE(beforeFds, 0);
1280 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001281 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001282 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1283 }
1284 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1285}
1286
Devin Moore800b2252021-10-15 16:22:57 +00001287TEST_P(BinderRpc, AidlDelegatorTest) {
1288 auto proc = createRpcTestSocketServerProcess({});
1289 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1290 ASSERT_NE(nullptr, myDelegator);
1291
1292 std::string doubled;
1293 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1294 EXPECT_EQ("cool cool ", doubled);
1295}
1296
Steven Morelandda573042021-06-12 01:13:45 +00001297static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001298 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001299 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001300
Andrei Homescu992a4052022-06-28 21:26:18 +00001301 android::base::unique_fd serverFd(
1302 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1303 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1304
1305 sockaddr_vm serverAddr{
1306 .svm_family = AF_VSOCK,
1307 .svm_port = vsockPort,
1308 .svm_cid = VMADDR_CID_ANY,
1309 };
1310 int ret = TEMP_FAILURE_RETRY(
1311 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1312 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1313 strerror(errno));
1314
1315 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1316 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1317 strerror(errno));
1318
1319 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1320 // to see if the kernel supports it. It's safe to use a blocking
1321 // connect because vsock sockets have a 2 second connection timeout,
1322 // and they return ETIMEDOUT after that.
1323 android::base::unique_fd connectFd(
1324 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1325 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1326 strerror(errno));
1327
1328 bool success = false;
1329 sockaddr_vm connectAddr{
1330 .svm_family = AF_VSOCK,
1331 .svm_port = vsockPort,
1332 .svm_cid = VMADDR_CID_LOCAL,
1333 };
1334 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1335 sizeof(connectAddr)));
1336 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1337 android::base::unique_fd acceptFd;
1338 while (true) {
1339 pollfd pfd[]{
1340 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1341 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1342 };
1343 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1344 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1345
1346 if (pfd[0].revents & POLLIN) {
1347 sockaddr_vm acceptAddr;
1348 socklen_t acceptAddrLen = sizeof(acceptAddr);
1349 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1350 reinterpret_cast<sockaddr*>(&acceptAddr),
1351 &acceptAddrLen, SOCK_CLOEXEC));
1352 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1353 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1354 "Truncated address");
1355
1356 // Store the fd in acceptFd so we keep the connection alive
1357 // while polling connectFd
1358 acceptFd.reset(ret);
1359 }
1360
1361 if (pfd[1].revents & POLLOUT) {
1362 // Connect either succeeded or timed out
1363 int connectErrno;
1364 socklen_t connectErrnoLen = sizeof(connectErrno);
1365 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1366 &connectErrnoLen);
1367 LOG_ALWAYS_FATAL_IF(ret == -1,
1368 "Could not getsockopt() after connect() "
1369 "on non-blocking socket: %s.",
1370 strerror(errno));
1371
1372 // We're done, this is all we wanted
1373 success = connectErrno == 0;
1374 break;
1375 }
1376 }
1377 } else {
1378 success = ret == 0;
1379 }
1380
1381 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1382
1383 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001384}
1385
Yifan Hong1deca4b2021-09-10 16:16:44 -07001386static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1387 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1388
1389 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001390
1391 static bool hasVsockLoopback = testSupportVsockLoopback();
1392
1393 if (hasVsockLoopback) {
1394 ret.push_back(SocketType::VSOCK);
1395 }
1396
1397 return ret;
1398}
1399
Frederick Mayledc07cf82022-05-26 20:30:12 +00001400static std::vector<uint32_t> testVersions() {
1401 std::vector<uint32_t> versions;
1402 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1403 versions.push_back(i);
1404 }
1405 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1406 return versions;
1407}
1408
Yifan Hong702115c2021-06-24 15:39:18 -07001409INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1410 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001411 ::testing::ValuesIn(RpcSecurityValues()),
1412 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001413 ::testing::ValuesIn(testVersions()),
1414 ::testing::Values(false, true),
1415 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001416 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001417
Andrei Homescu12106de2022-04-27 04:42:21 +00001418INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpcThreads,
1419 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1420 ::testing::ValuesIn(RpcSecurityValues()),
1421 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001422 ::testing::ValuesIn(testVersions()),
1423 ::testing::Values(false),
1424 ::testing::Values(false, true)),
Andrei Homescu12106de2022-04-27 04:42:21 +00001425 BinderRpc::PrintParamInfo);
1426
Yifan Hong702115c2021-06-24 15:39:18 -07001427class BinderRpcServerRootObject
1428 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001429
1430TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1431 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1432 auto setRootObject = [](bool isStrong) -> SetFn {
1433 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1434 };
1435
Yifan Hong702115c2021-06-24 15:39:18 -07001436 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1437 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001438 auto binder1 = sp<BBinder>::make();
1439 IBinder* binderRaw1 = binder1.get();
1440 setRootObject(isStrong1)(server.get(), binder1);
1441 EXPECT_EQ(binderRaw1, server->getRootObject());
1442 binder1.clear();
1443 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1444
1445 auto binder2 = sp<BBinder>::make();
1446 IBinder* binderRaw2 = binder2.get();
1447 setRootObject(isStrong2)(server.get(), binder2);
1448 EXPECT_EQ(binderRaw2, server->getRootObject());
1449 binder2.clear();
1450 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1451}
1452
1453INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001454 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1455 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001456
Yifan Hong1a235852021-05-13 16:07:47 -07001457class OneOffSignal {
1458public:
1459 // If notify() was previously called, or is called within |duration|, return true; else false.
1460 template <typename R, typename P>
1461 bool wait(std::chrono::duration<R, P> duration) {
1462 std::unique_lock<std::mutex> lock(mMutex);
1463 return mCv.wait_for(lock, duration, [this] { return mValue; });
1464 }
1465 void notify() {
1466 std::unique_lock<std::mutex> lock(mMutex);
1467 mValue = true;
1468 lock.unlock();
1469 mCv.notify_all();
1470 }
1471
1472private:
1473 std::mutex mMutex;
1474 std::condition_variable mCv;
1475 bool mValue = false;
1476};
1477
Frederick Mayledc07cf82022-05-26 20:30:12 +00001478TEST_P(BinderRpcServerOnly, Shutdown) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001479 if constexpr (!kEnableRpcThreads) {
1480 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1481 }
1482
Yifan Hong1a235852021-05-13 16:07:47 -07001483 auto addr = allocateSocketAddress();
Frederick Mayledc07cf82022-05-26 20:30:12 +00001484 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1485 server->setProtocolVersion(std::get<1>(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001486 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001487 auto joinEnds = std::make_shared<OneOffSignal>();
1488
1489 // If things are broken and the thread never stops, don't block other tests. Because the thread
1490 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1491 // shared pointers are passed.
1492 std::thread([server, joinEnds] {
1493 server->join();
1494 joinEnds->notify();
1495 }).detach();
1496
1497 bool shutdown = false;
1498 for (int i = 0; i < 10 && !shutdown; i++) {
1499 usleep(300 * 1000); // 300ms; total 3s
1500 if (server->shutdown()) shutdown = true;
1501 }
1502 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1503
1504 ASSERT_TRUE(joinEnds->wait(2s))
1505 << "After server->shutdown() returns true, join() did not stop after 2s";
1506}
1507
Yifan Hong194acf22021-06-29 18:44:56 -07001508TEST(BinderRpc, Java) {
1509#if !defined(__ANDROID__)
1510 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1511 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1512 "to binderHostDeviceTest. Hence, just disable this test on host.";
1513#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001514 if constexpr (!kEnableKernelIpc) {
1515 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1516 "at build time.";
1517 }
1518
Yifan Hong194acf22021-06-29 18:44:56 -07001519 sp<IServiceManager> sm = defaultServiceManager();
1520 ASSERT_NE(nullptr, sm);
1521 // Any Java service with non-empty getInterfaceDescriptor() would do.
1522 // Let's pick batteryproperties.
1523 auto binder = sm->checkService(String16("batteryproperties"));
1524 ASSERT_NE(nullptr, binder);
1525 auto descriptor = binder->getInterfaceDescriptor();
1526 ASSERT_GE(descriptor.size(), 0);
1527 ASSERT_EQ(OK, binder->pingBinder());
1528
1529 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001530 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001531 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001532 auto socket = rpcServer->releaseServer();
1533
1534 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001535 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1536
Yifan Honge3caaf22022-01-12 14:46:56 -08001537 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1538 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001539 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001540 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1541 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001542 << statusToString(setRpcClientDebugStatus);
1543 GTEST_SKIP();
1544 }
1545
1546 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001547
1548 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001549 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001550 auto rpcBinder = rpcSession->getRootObject();
1551 ASSERT_NE(nullptr, rpcBinder);
1552
1553 ASSERT_EQ(OK, rpcBinder->pingBinder());
1554
1555 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1556 << "getInterfaceDescriptor should not crash system_server";
1557 ASSERT_EQ(OK, rpcBinder->pingBinder());
1558}
1559
Frederick Mayledc07cf82022-05-26 20:30:12 +00001560INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1561 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1562 ::testing::ValuesIn(testVersions())),
1563 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001564
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001565class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001566public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001567 // Only parameterized only server version because `RpcSession` is bypassed
1568 // in the client half of the tests.
1569 using Param =
1570 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001571 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001572
1573 // A server that handles client socket connections.
1574 class Server {
1575 public:
1576 explicit Server() {}
1577 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001578 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001579 [[nodiscard]] AssertionResult setUp(
1580 const Param& param,
1581 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001582 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001583 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001584 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001585 switch (socketType) {
1586 case SocketType::PRECONNECTED: {
1587 return AssertionFailure() << "Not supported by this test";
1588 } break;
1589 case SocketType::UNIX: {
1590 auto addr = allocateSocketAddress();
1591 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1592 if (status != OK) {
1593 return AssertionFailure()
1594 << "setupUnixDomainServer: " << statusToString(status);
1595 }
1596 mConnectToServer = [addr] {
1597 return connectTo(UnixSocketAddress(addr.c_str()));
1598 };
1599 } break;
1600 case SocketType::VSOCK: {
1601 auto port = allocateVsockPort();
1602 auto status = rpcServer->setupVsockServer(port);
1603 if (status != OK) {
1604 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1605 }
1606 mConnectToServer = [port] {
1607 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1608 };
1609 } break;
1610 case SocketType::INET: {
1611 unsigned int port;
1612 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1613 if (status != OK) {
1614 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1615 }
1616 mConnectToServer = [port] {
1617 const char* addr = kLocalInetAddress;
1618 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1619 if (aiStart == nullptr) return base::unique_fd{};
1620 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1621 auto fd = connectTo(
1622 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1623 if (fd.ok()) return fd;
1624 }
1625 ALOGE("None of the socket address resolved for %s:%u can be connected",
1626 addr, port);
1627 return base::unique_fd{};
1628 };
1629 }
1630 }
1631 mFd = rpcServer->releaseServer();
1632 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001633 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001634 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1635 mSetup = true;
1636 return AssertionSuccess();
1637 }
1638 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1639 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1640 return mCertVerifier;
1641 }
1642 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1643 void start() {
1644 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1645 mThread = std::make_unique<std::thread>(&Server::run, this);
1646 }
1647 void run() {
1648 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1649
1650 std::vector<std::thread> threads;
1651 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1652 base::unique_fd acceptedFd(
1653 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1654 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1655 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1656 }
1657
1658 for (auto& thread : threads) thread.join();
1659 }
1660 void handleOne(android::base::unique_fd acceptedFd) {
1661 ASSERT_TRUE(acceptedFd.ok());
1662 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1663 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001664 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001665 }
Yifan Honge07d2732021-09-13 21:59:14 -07001666 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001667 shutdown();
1668 join();
1669 }
1670 void shutdown() { mFdTrigger->trigger(); }
1671
1672 void setPostConnect(
1673 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1674 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001675 }
1676
1677 private:
1678 std::unique_ptr<std::thread> mThread;
1679 ConnectToServer mConnectToServer;
1680 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1681 base::unique_fd mFd;
1682 std::unique_ptr<RpcTransportCtx> mCtx;
1683 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1684 std::make_shared<RpcCertificateVerifierSimple>();
1685 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001686 // The function invoked after connection and handshake. By default, it is
1687 // |defaultPostConnect| that sends |kMessage| to the client.
1688 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1689 Server::defaultPostConnect;
1690
1691 void join() {
1692 if (mThread != nullptr) {
1693 mThread->join();
1694 mThread = nullptr;
1695 }
1696 }
1697
1698 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1699 FdTrigger* fdTrigger) {
1700 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001701 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001702 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001703 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001704 if (status != OK) return AssertionFailure() << statusToString(status);
1705 return AssertionSuccess();
1706 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001707 };
1708
1709 class Client {
1710 public:
1711 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1712 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001713 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001714 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1715 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001716 mFdTrigger = FdTrigger::make();
1717 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1718 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1719 return AssertionSuccess();
1720 }
1721 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1722 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1723 return mCertVerifier;
1724 }
Yifan Hong67519322021-09-13 18:51:16 -07001725 // connect() and do handshake
1726 bool setUpTransport() {
1727 mFd = mConnectToServer();
1728 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1729 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1730 return mClientTransport != nullptr;
1731 }
1732 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1733 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1734 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001735 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001736 status_t readStatus =
1737 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001738 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001739 if (readStatus != OK) {
1740 return AssertionFailure() << statusToString(readStatus);
1741 }
1742 if (readMessage != expectedMessage) {
1743 return AssertionFailure()
1744 << "Expected " << expectedMessage << ", actual " << readMessage;
1745 }
1746 return AssertionSuccess();
1747 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001748 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001749 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001750 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1751 return;
1752 }
1753 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001754 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001755 }
1756
1757 private:
1758 ConnectToServer mConnectToServer;
1759 base::unique_fd mFd;
1760 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1761 std::unique_ptr<RpcTransportCtx> mCtx;
1762 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1763 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001764 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001765 };
1766
1767 // Make A trust B.
1768 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001769 static status_t trust(RpcSecurity rpcSecurity,
1770 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1771 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001772 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001773 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1774 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1775 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001776 }
1777
1778 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001779};
1780
1781class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1782public:
1783 using Server = RpcTransportTestUtils::Server;
1784 using Client = RpcTransportTestUtils::Client;
1785 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001786 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001787 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1788 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001789 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001790 return ret;
1791 }
1792 static std::vector<ParamType> getRpcTranportTestParams() {
1793 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001794 for (auto serverVersion : testVersions()) {
1795 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1796 for (auto rpcSecurity : RpcSecurityValues()) {
1797 switch (rpcSecurity) {
1798 case RpcSecurity::RAW: {
1799 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1800 } break;
1801 case RpcSecurity::TLS: {
1802 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1803 serverVersion);
1804 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1805 serverVersion);
1806 } break;
1807 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001808 }
1809 }
1810 }
1811 return ret;
1812 }
1813 template <typename A, typename B>
1814 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001815 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1816 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001817 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1818 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001819 void SetUp() override {
1820 if constexpr (!kEnableRpcThreads) {
1821 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1822 }
1823 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001824};
1825
1826TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001827 auto server = std::make_unique<Server>();
1828 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001829
1830 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001831 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001832
1833 ASSERT_EQ(OK, trust(&client, server));
1834 ASSERT_EQ(OK, trust(server, &client));
1835
1836 server->start();
1837 client.run();
1838}
1839
1840TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001841 auto server = std::make_unique<Server>();
1842 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001843
1844 std::vector<Client> clients;
1845 for (int i = 0; i < 2; i++) {
1846 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001847 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001848 ASSERT_EQ(OK, trust(&client, server));
1849 ASSERT_EQ(OK, trust(server, &client));
1850 }
1851
1852 server->start();
1853 for (auto& client : clients) client.run();
1854}
1855
1856TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001857 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1858 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001859
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001860 auto untrustedServer = std::make_unique<Server>();
1861 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001862
1863 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001864 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001865
1866 ASSERT_EQ(OK, trust(untrustedServer, &client));
1867
1868 untrustedServer->start();
1869
1870 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1871 // the client can't verify the server's identity.
1872 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1873 client.run(handshakeOk);
1874}
1875TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001876 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1877 (void)serverVersion;
1878
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001879 auto validServer = std::make_unique<Server>();
1880 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001881
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001882 auto maliciousServer = std::make_unique<Server>();
1883 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001884
1885 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001886 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001887
1888 ASSERT_EQ(OK, trust(&client, validServer));
1889 ASSERT_EQ(OK, trust(validServer, &client));
1890 ASSERT_EQ(OK, trust(maliciousServer, &client));
1891
1892 maliciousServer->start();
1893
1894 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1895 // the client can't verify the server's identity.
1896 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1897 client.run(handshakeOk);
1898}
1899
1900TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001901 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1902 (void)serverVersion;
1903
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001904 auto server = std::make_unique<Server>();
1905 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001906
1907 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001908 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001909
1910 ASSERT_EQ(OK, trust(&client, server));
1911
1912 server->start();
1913
1914 // For TLS, Client should be able to verify server's identity, so client should see
1915 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1916 // identity and should drop the connection, so client shouldn't be able to read anything.
1917 bool readOk = rpcSecurity != RpcSecurity::TLS;
1918 client.run(true, readOk);
1919}
1920
1921TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001922 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1923 (void)serverVersion;
1924
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001925 auto server = std::make_unique<Server>();
1926 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001927
1928 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001929 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001930 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001931 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001932
1933 ASSERT_EQ(OK, trust(&validClient, server));
1934 ASSERT_EQ(OK, trust(&maliciousClient, server));
1935
1936 server->start();
1937
1938 // See UntrustedClient.
1939 bool readOk = rpcSecurity != RpcSecurity::TLS;
1940 maliciousClient.run(true, readOk);
1941}
1942
Yifan Hong67519322021-09-13 18:51:16 -07001943TEST_P(RpcTransportTest, Trigger) {
1944 std::string msg2 = ", world!";
1945 std::mutex writeMutex;
1946 std::condition_variable writeCv;
1947 bool shouldContinueWriting = false;
1948 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001949 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001950 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001951 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1952 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001953 if (status != OK) return AssertionFailure() << statusToString(status);
1954
1955 {
1956 std::unique_lock<std::mutex> lock(writeMutex);
1957 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1958 return AssertionFailure() << "write barrier not cleared in time!";
1959 }
1960 }
1961
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001962 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001963 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1964 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001965 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001966 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001967 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001968 << statusToString(status);
1969 return AssertionSuccess();
1970 };
1971
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001972 auto server = std::make_unique<Server>();
1973 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001974
1975 // Set up client
1976 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001977 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001978
1979 // Exchange keys
1980 ASSERT_EQ(OK, trust(&client, server));
1981 ASSERT_EQ(OK, trust(server, &client));
1982
1983 server->setPostConnect(serverPostConnect);
1984
Yifan Hong67519322021-09-13 18:51:16 -07001985 server->start();
1986 // connect() to server and do handshake
1987 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001988 // read the first message. This ensures that server has finished handshake and start handling
1989 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001990 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001991 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1992 // write is on an FdTrigger that has been shut down.
1993 server->shutdown();
1994 // Continues server thread to write the second message.
1995 {
Yifan Hong22211f82021-09-14 12:32:25 -07001996 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001997 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001998 }
Yifan Hong22211f82021-09-14 12:32:25 -07001999 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002000 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002001 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002002 // On the client side, second read fails with DEAD_OBJECT
2003 ASSERT_FALSE(client.readMessage(msg2));
2004}
2005
Yifan Hong1deca4b2021-09-10 16:16:44 -07002006INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002007 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002008 RpcTransportTest::PrintParamInfo);
2009
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002010class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002011 : public testing::TestWithParam<
2012 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002013public:
2014 template <typename A, typename B>
2015 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002016 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2017 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002018 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2019 }
2020 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002021 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2022 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2023 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002024 };
2025};
2026
2027TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002028 if constexpr (!kEnableRpcThreads) {
2029 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2030 }
2031
Frederick Mayledc07cf82022-05-26 20:30:12 +00002032 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002033
2034 std::vector<uint8_t> pkeyData, certData;
2035 {
2036 auto pkey = makeKeyPairForSelfSignedCert();
2037 ASSERT_NE(nullptr, pkey);
2038 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2039 ASSERT_NE(nullptr, cert);
2040 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2041 certData = serializeCertificate(cert.get(), certificateFormat);
2042 }
2043
2044 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2045 auto desCert = deserializeCertificate(certData, certificateFormat);
2046 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002047 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2048 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002049
2050 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2051 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2052
2053 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2054 ASSERT_TRUE(client.setUp(utilsParam));
2055
2056 ASSERT_EQ(OK, trust(&client, server));
2057 ASSERT_EQ(OK, trust(server, &client));
2058
2059 server->start();
2060 client.run();
2061}
2062
2063INSTANTIATE_TEST_CASE_P(
2064 BinderRpc, RpcTransportTlsKeyTest,
2065 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2066 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002067 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2068 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002069 RpcTransportTlsKeyTest::PrintParamInfo);
2070
Steven Morelandc1635952021-04-01 16:20:47 +00002071} // namespace android
2072
2073int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002074 ::testing::InitGoogleTest(&argc, argv);
2075 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002076
Steven Moreland5553ac42020-11-11 02:14:45 +00002077 return RUN_ALL_TESTS();
2078}