blob: 4e41d8e604012c8a4d65e02ab5dd48b5997e5cae [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
933 EXPECT_GT(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 Moreland659416d2021-05-11 00:47:50 +00001032
Frederick Maylea12b0962022-06-25 01:13:22 +00001033 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1034 // Flaky. Sometimes gets SIGABRT.
1035 EXPECT_TRUE((WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0) ||
1036 (WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT))
1037 << "server process failed: " << WaitStatusToString(wstatus);
1038 });
Steven Morelandc7d40132021-06-10 03:42:11 +00001039 proc.expectAlreadyShutdown = true;
1040 }
Steven Moreland659416d2021-05-11 00:47:50 +00001041 }
1042 }
1043}
1044
Steven Moreland195edb82021-06-08 02:44:39 +00001045TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001046 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001047 auto cb = sp<MyBinderRpcCallback>::make();
1048
1049 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1050 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1051}
1052
Steven Morelandc1635952021-04-01 16:20:47 +00001053TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001054 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001055 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001056
1057 // make sure there is some state during crash
1058 // 1. we hold their binder
1059 sp<IBinderRpcSession> session;
1060 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1061 // 2. they hold our binder
1062 sp<IBinder> binder = new BBinder();
1063 EXPECT_OK(proc.rootIface->holdBinder(binder));
1064
1065 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1066 << "Do death cleanup: " << doDeathCleanup;
1067
Frederick Maylea12b0962022-06-25 01:13:22 +00001068 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1069 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1070 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1071 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001072 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001073 }
1074}
1075
Steven Morelandd7302072021-05-15 01:32:04 +00001076TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001077 // This test only works if the current process shared the internal state of
1078 // ProcessState with the service across the call to fork(). Both the static
1079 // libraries and libbinder.so have their own separate copies of all the
1080 // globals, so the test only works when the test client and service both use
1081 // libbinder.so (when using static libraries, even a client and service
1082 // using the same kind of static library should have separate copies of the
1083 // variables).
1084 if (!kEnableSharedLibs || singleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001085 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1086 "at build time.";
1087 }
1088
Steven Moreland4313d7e2021-07-15 23:41:22 +00001089 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001090
Andrei Homescu2a298012022-06-15 01:08:54 +00001091 // we can't allocate IPCThreadState so actually the first time should
1092 // succeed :(
1093 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001094
1095 // second time! we catch the error :)
1096 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1097
Frederick Maylea12b0962022-06-25 01:13:22 +00001098 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1099 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1100 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1101 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001102 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001103}
1104
Frederick Mayle69a0c992022-05-26 20:38:39 +00001105TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1106 auto proc = createRpcTestSocketServerProcess({
1107 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1108 .serverSupportedFileDescriptorTransportModes =
1109 {RpcSession::FileDescriptorTransportMode::UNIX},
1110 .allowConnectFailure = true,
1111 });
1112 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1113 proc.proc.host.terminate();
1114 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1115 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1116 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1117 });
1118 proc.expectAlreadyShutdown = true;
1119}
1120
1121TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1122 auto proc = createRpcTestSocketServerProcess({
1123 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1124 .serverSupportedFileDescriptorTransportModes =
1125 {RpcSession::FileDescriptorTransportMode::NONE},
1126 .allowConnectFailure = true,
1127 });
1128 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1129 proc.proc.host.terminate();
1130 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1131 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1132 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1133 });
1134 proc.expectAlreadyShutdown = true;
1135}
1136
1137TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1138 auto proc = createRpcTestSocketServerProcess({
1139 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1140 .serverSupportedFileDescriptorTransportModes =
1141 {RpcSession::FileDescriptorTransportMode::NONE,
1142 RpcSession::FileDescriptorTransportMode::UNIX},
1143 });
1144
1145 android::os::ParcelFileDescriptor out;
1146 auto status = proc.rootIface->echoAsFile("hello", &out);
1147 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1148}
1149
1150TEST_P(BinderRpc, ReceiveFile) {
1151 auto proc = createRpcTestSocketServerProcess({
1152 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1153 .serverSupportedFileDescriptorTransportModes =
1154 {RpcSession::FileDescriptorTransportMode::UNIX},
1155 });
1156
1157 android::os::ParcelFileDescriptor out;
1158 auto status = proc.rootIface->echoAsFile("hello", &out);
1159 if (!supportsFdTransport()) {
1160 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1161 return;
1162 }
1163 ASSERT_TRUE(status.isOk()) << status;
1164
1165 std::string result;
1166 CHECK(android::base::ReadFdToString(out.get(), &result));
1167 EXPECT_EQ(result, "hello");
1168}
1169
1170TEST_P(BinderRpc, SendFiles) {
1171 auto proc = createRpcTestSocketServerProcess({
1172 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1173 .serverSupportedFileDescriptorTransportModes =
1174 {RpcSession::FileDescriptorTransportMode::UNIX},
1175 });
1176
1177 std::vector<android::os::ParcelFileDescriptor> files;
1178 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1179 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1180 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1181 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1182
1183 android::os::ParcelFileDescriptor out;
1184 auto status = proc.rootIface->concatFiles(files, &out);
1185 if (!supportsFdTransport()) {
1186 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1187 return;
1188 }
1189 ASSERT_TRUE(status.isOk()) << status;
1190
1191 std::string result;
1192 CHECK(android::base::ReadFdToString(out.get(), &result));
1193 EXPECT_EQ(result, "123abcd");
1194}
1195
1196TEST_P(BinderRpc, SendMaxFiles) {
1197 if (!supportsFdTransport()) {
1198 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1199 }
1200
1201 auto proc = createRpcTestSocketServerProcess({
1202 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1203 .serverSupportedFileDescriptorTransportModes =
1204 {RpcSession::FileDescriptorTransportMode::UNIX},
1205 });
1206
1207 std::vector<android::os::ParcelFileDescriptor> files;
1208 for (int i = 0; i < 253; i++) {
1209 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1210 }
1211
1212 android::os::ParcelFileDescriptor out;
1213 auto status = proc.rootIface->concatFiles(files, &out);
1214 ASSERT_TRUE(status.isOk()) << status;
1215
1216 std::string result;
1217 CHECK(android::base::ReadFdToString(out.get(), &result));
1218 EXPECT_EQ(result, std::string(253, 'a'));
1219}
1220
1221TEST_P(BinderRpc, SendTooManyFiles) {
1222 if (!supportsFdTransport()) {
1223 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1224 }
1225
1226 auto proc = createRpcTestSocketServerProcess({
1227 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1228 .serverSupportedFileDescriptorTransportModes =
1229 {RpcSession::FileDescriptorTransportMode::UNIX},
1230 });
1231
1232 std::vector<android::os::ParcelFileDescriptor> files;
1233 for (int i = 0; i < 254; i++) {
1234 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1235 }
1236
1237 android::os::ParcelFileDescriptor out;
1238 auto status = proc.rootIface->concatFiles(files, &out);
1239 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1240}
1241
Steven Moreland37aff182021-03-26 02:04:16 +00001242TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001243 if constexpr (!kEnableSharedLibs) {
1244 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1245 }
1246
Steven Moreland4313d7e2021-07-15 23:41:22 +00001247 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001248
1249 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1250 ASSERT_NE(binder, nullptr);
1251
1252 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1253}
1254
1255TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001256 if constexpr (!kEnableSharedLibs) {
1257 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1258 }
1259
Steven Moreland4313d7e2021-07-15 23:41:22 +00001260 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001261
1262 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1263 ASSERT_NE(binder, nullptr);
1264
1265 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1266 ASSERT_NE(ndkBinder, nullptr);
1267
1268 std::string out;
1269 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1270 ASSERT_TRUE(status.isOk()) << status.getDescription();
1271 ASSERT_EQ("aoeuaoeu", out);
1272}
1273
Steven Moreland5553ac42020-11-11 02:14:45 +00001274ssize_t countFds() {
1275 DIR* dir = opendir("/proc/self/fd/");
1276 if (dir == nullptr) return -1;
1277 ssize_t ret = 0;
1278 dirent* ent;
1279 while ((ent = readdir(dir)) != nullptr) ret++;
1280 closedir(dir);
1281 return ret;
1282}
1283
Andrei Homescu12106de2022-04-27 04:42:21 +00001284TEST_P(BinderRpcThreads, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001285 ssize_t beforeFds = countFds();
1286 ASSERT_GE(beforeFds, 0);
1287 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001288 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001289 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1290 }
1291 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1292}
1293
Devin Moore800b2252021-10-15 16:22:57 +00001294TEST_P(BinderRpc, AidlDelegatorTest) {
1295 auto proc = createRpcTestSocketServerProcess({});
1296 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1297 ASSERT_NE(nullptr, myDelegator);
1298
1299 std::string doubled;
1300 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1301 EXPECT_EQ("cool cool ", doubled);
1302}
1303
Steven Morelandda573042021-06-12 01:13:45 +00001304static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001305 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001306 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001307
Andrei Homescu992a4052022-06-28 21:26:18 +00001308 android::base::unique_fd serverFd(
1309 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1310 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1311
1312 sockaddr_vm serverAddr{
1313 .svm_family = AF_VSOCK,
1314 .svm_port = vsockPort,
1315 .svm_cid = VMADDR_CID_ANY,
1316 };
1317 int ret = TEMP_FAILURE_RETRY(
1318 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1319 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1320 strerror(errno));
1321
1322 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1323 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1324 strerror(errno));
1325
1326 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1327 // to see if the kernel supports it. It's safe to use a blocking
1328 // connect because vsock sockets have a 2 second connection timeout,
1329 // and they return ETIMEDOUT after that.
1330 android::base::unique_fd connectFd(
1331 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1332 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1333 strerror(errno));
1334
1335 bool success = false;
1336 sockaddr_vm connectAddr{
1337 .svm_family = AF_VSOCK,
1338 .svm_port = vsockPort,
1339 .svm_cid = VMADDR_CID_LOCAL,
1340 };
1341 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1342 sizeof(connectAddr)));
1343 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1344 android::base::unique_fd acceptFd;
1345 while (true) {
1346 pollfd pfd[]{
1347 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1348 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1349 };
1350 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1351 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1352
1353 if (pfd[0].revents & POLLIN) {
1354 sockaddr_vm acceptAddr;
1355 socklen_t acceptAddrLen = sizeof(acceptAddr);
1356 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1357 reinterpret_cast<sockaddr*>(&acceptAddr),
1358 &acceptAddrLen, SOCK_CLOEXEC));
1359 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1360 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1361 "Truncated address");
1362
1363 // Store the fd in acceptFd so we keep the connection alive
1364 // while polling connectFd
1365 acceptFd.reset(ret);
1366 }
1367
1368 if (pfd[1].revents & POLLOUT) {
1369 // Connect either succeeded or timed out
1370 int connectErrno;
1371 socklen_t connectErrnoLen = sizeof(connectErrno);
1372 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1373 &connectErrnoLen);
1374 LOG_ALWAYS_FATAL_IF(ret == -1,
1375 "Could not getsockopt() after connect() "
1376 "on non-blocking socket: %s.",
1377 strerror(errno));
1378
1379 // We're done, this is all we wanted
1380 success = connectErrno == 0;
1381 break;
1382 }
1383 }
1384 } else {
1385 success = ret == 0;
1386 }
1387
1388 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1389
1390 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001391}
1392
Yifan Hong1deca4b2021-09-10 16:16:44 -07001393static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1394 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1395
1396 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001397
1398 static bool hasVsockLoopback = testSupportVsockLoopback();
1399
1400 if (hasVsockLoopback) {
1401 ret.push_back(SocketType::VSOCK);
1402 }
1403
1404 return ret;
1405}
1406
Frederick Mayledc07cf82022-05-26 20:30:12 +00001407static std::vector<uint32_t> testVersions() {
1408 std::vector<uint32_t> versions;
1409 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1410 versions.push_back(i);
1411 }
1412 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1413 return versions;
1414}
1415
Yifan Hong702115c2021-06-24 15:39:18 -07001416INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1417 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001418 ::testing::ValuesIn(RpcSecurityValues()),
1419 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001420 ::testing::ValuesIn(testVersions()),
1421 ::testing::Values(false, true),
1422 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001423 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001424
Andrei Homescu12106de2022-04-27 04:42:21 +00001425INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpcThreads,
1426 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1427 ::testing::ValuesIn(RpcSecurityValues()),
1428 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001429 ::testing::ValuesIn(testVersions()),
1430 ::testing::Values(false),
1431 ::testing::Values(false, true)),
Andrei Homescu12106de2022-04-27 04:42:21 +00001432 BinderRpc::PrintParamInfo);
1433
Yifan Hong702115c2021-06-24 15:39:18 -07001434class BinderRpcServerRootObject
1435 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001436
1437TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1438 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1439 auto setRootObject = [](bool isStrong) -> SetFn {
1440 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1441 };
1442
Yifan Hong702115c2021-06-24 15:39:18 -07001443 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1444 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001445 auto binder1 = sp<BBinder>::make();
1446 IBinder* binderRaw1 = binder1.get();
1447 setRootObject(isStrong1)(server.get(), binder1);
1448 EXPECT_EQ(binderRaw1, server->getRootObject());
1449 binder1.clear();
1450 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1451
1452 auto binder2 = sp<BBinder>::make();
1453 IBinder* binderRaw2 = binder2.get();
1454 setRootObject(isStrong2)(server.get(), binder2);
1455 EXPECT_EQ(binderRaw2, server->getRootObject());
1456 binder2.clear();
1457 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1458}
1459
1460INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001461 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1462 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001463
Yifan Hong1a235852021-05-13 16:07:47 -07001464class OneOffSignal {
1465public:
1466 // If notify() was previously called, or is called within |duration|, return true; else false.
1467 template <typename R, typename P>
1468 bool wait(std::chrono::duration<R, P> duration) {
1469 std::unique_lock<std::mutex> lock(mMutex);
1470 return mCv.wait_for(lock, duration, [this] { return mValue; });
1471 }
1472 void notify() {
1473 std::unique_lock<std::mutex> lock(mMutex);
1474 mValue = true;
1475 lock.unlock();
1476 mCv.notify_all();
1477 }
1478
1479private:
1480 std::mutex mMutex;
1481 std::condition_variable mCv;
1482 bool mValue = false;
1483};
1484
Frederick Mayledc07cf82022-05-26 20:30:12 +00001485TEST_P(BinderRpcServerOnly, Shutdown) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001486 if constexpr (!kEnableRpcThreads) {
1487 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1488 }
1489
Yifan Hong1a235852021-05-13 16:07:47 -07001490 auto addr = allocateSocketAddress();
Frederick Mayledc07cf82022-05-26 20:30:12 +00001491 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1492 server->setProtocolVersion(std::get<1>(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001493 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001494 auto joinEnds = std::make_shared<OneOffSignal>();
1495
1496 // If things are broken and the thread never stops, don't block other tests. Because the thread
1497 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1498 // shared pointers are passed.
1499 std::thread([server, joinEnds] {
1500 server->join();
1501 joinEnds->notify();
1502 }).detach();
1503
1504 bool shutdown = false;
1505 for (int i = 0; i < 10 && !shutdown; i++) {
1506 usleep(300 * 1000); // 300ms; total 3s
1507 if (server->shutdown()) shutdown = true;
1508 }
1509 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1510
1511 ASSERT_TRUE(joinEnds->wait(2s))
1512 << "After server->shutdown() returns true, join() did not stop after 2s";
1513}
1514
Yifan Hong194acf22021-06-29 18:44:56 -07001515TEST(BinderRpc, Java) {
1516#if !defined(__ANDROID__)
1517 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1518 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1519 "to binderHostDeviceTest. Hence, just disable this test on host.";
1520#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001521 if constexpr (!kEnableKernelIpc) {
1522 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1523 "at build time.";
1524 }
1525
Yifan Hong194acf22021-06-29 18:44:56 -07001526 sp<IServiceManager> sm = defaultServiceManager();
1527 ASSERT_NE(nullptr, sm);
1528 // Any Java service with non-empty getInterfaceDescriptor() would do.
1529 // Let's pick batteryproperties.
1530 auto binder = sm->checkService(String16("batteryproperties"));
1531 ASSERT_NE(nullptr, binder);
1532 auto descriptor = binder->getInterfaceDescriptor();
1533 ASSERT_GE(descriptor.size(), 0);
1534 ASSERT_EQ(OK, binder->pingBinder());
1535
1536 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001537 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001538 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001539 auto socket = rpcServer->releaseServer();
1540
1541 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001542 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1543
Yifan Honge3caaf22022-01-12 14:46:56 -08001544 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1545 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001546 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001547 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1548 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001549 << statusToString(setRpcClientDebugStatus);
1550 GTEST_SKIP();
1551 }
1552
1553 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001554
1555 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001556 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001557 auto rpcBinder = rpcSession->getRootObject();
1558 ASSERT_NE(nullptr, rpcBinder);
1559
1560 ASSERT_EQ(OK, rpcBinder->pingBinder());
1561
1562 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1563 << "getInterfaceDescriptor should not crash system_server";
1564 ASSERT_EQ(OK, rpcBinder->pingBinder());
1565}
1566
Frederick Mayledc07cf82022-05-26 20:30:12 +00001567INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1568 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1569 ::testing::ValuesIn(testVersions())),
1570 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001571
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001572class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001573public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001574 // Only parameterized only server version because `RpcSession` is bypassed
1575 // in the client half of the tests.
1576 using Param =
1577 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001578 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001579
1580 // A server that handles client socket connections.
1581 class Server {
1582 public:
1583 explicit Server() {}
1584 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001585 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001586 [[nodiscard]] AssertionResult setUp(
1587 const Param& param,
1588 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001589 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001590 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001591 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001592 switch (socketType) {
1593 case SocketType::PRECONNECTED: {
1594 return AssertionFailure() << "Not supported by this test";
1595 } break;
1596 case SocketType::UNIX: {
1597 auto addr = allocateSocketAddress();
1598 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1599 if (status != OK) {
1600 return AssertionFailure()
1601 << "setupUnixDomainServer: " << statusToString(status);
1602 }
1603 mConnectToServer = [addr] {
1604 return connectTo(UnixSocketAddress(addr.c_str()));
1605 };
1606 } break;
1607 case SocketType::VSOCK: {
1608 auto port = allocateVsockPort();
1609 auto status = rpcServer->setupVsockServer(port);
1610 if (status != OK) {
1611 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1612 }
1613 mConnectToServer = [port] {
1614 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1615 };
1616 } break;
1617 case SocketType::INET: {
1618 unsigned int port;
1619 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1620 if (status != OK) {
1621 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1622 }
1623 mConnectToServer = [port] {
1624 const char* addr = kLocalInetAddress;
1625 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1626 if (aiStart == nullptr) return base::unique_fd{};
1627 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1628 auto fd = connectTo(
1629 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1630 if (fd.ok()) return fd;
1631 }
1632 ALOGE("None of the socket address resolved for %s:%u can be connected",
1633 addr, port);
1634 return base::unique_fd{};
1635 };
1636 }
1637 }
1638 mFd = rpcServer->releaseServer();
1639 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001640 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001641 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1642 mSetup = true;
1643 return AssertionSuccess();
1644 }
1645 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1646 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1647 return mCertVerifier;
1648 }
1649 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1650 void start() {
1651 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1652 mThread = std::make_unique<std::thread>(&Server::run, this);
1653 }
1654 void run() {
1655 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1656
1657 std::vector<std::thread> threads;
1658 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1659 base::unique_fd acceptedFd(
1660 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1661 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1662 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1663 }
1664
1665 for (auto& thread : threads) thread.join();
1666 }
1667 void handleOne(android::base::unique_fd acceptedFd) {
1668 ASSERT_TRUE(acceptedFd.ok());
1669 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1670 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001671 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001672 }
Yifan Honge07d2732021-09-13 21:59:14 -07001673 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001674 shutdown();
1675 join();
1676 }
1677 void shutdown() { mFdTrigger->trigger(); }
1678
1679 void setPostConnect(
1680 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1681 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001682 }
1683
1684 private:
1685 std::unique_ptr<std::thread> mThread;
1686 ConnectToServer mConnectToServer;
1687 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1688 base::unique_fd mFd;
1689 std::unique_ptr<RpcTransportCtx> mCtx;
1690 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1691 std::make_shared<RpcCertificateVerifierSimple>();
1692 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001693 // The function invoked after connection and handshake. By default, it is
1694 // |defaultPostConnect| that sends |kMessage| to the client.
1695 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1696 Server::defaultPostConnect;
1697
1698 void join() {
1699 if (mThread != nullptr) {
1700 mThread->join();
1701 mThread = nullptr;
1702 }
1703 }
1704
1705 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1706 FdTrigger* fdTrigger) {
1707 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001708 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001709 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001710 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001711 if (status != OK) return AssertionFailure() << statusToString(status);
1712 return AssertionSuccess();
1713 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001714 };
1715
1716 class Client {
1717 public:
1718 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1719 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001720 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001721 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1722 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001723 mFdTrigger = FdTrigger::make();
1724 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1725 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1726 return AssertionSuccess();
1727 }
1728 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1729 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1730 return mCertVerifier;
1731 }
Yifan Hong67519322021-09-13 18:51:16 -07001732 // connect() and do handshake
1733 bool setUpTransport() {
1734 mFd = mConnectToServer();
1735 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1736 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1737 return mClientTransport != nullptr;
1738 }
1739 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1740 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1741 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001742 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001743 status_t readStatus =
1744 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001745 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001746 if (readStatus != OK) {
1747 return AssertionFailure() << statusToString(readStatus);
1748 }
1749 if (readMessage != expectedMessage) {
1750 return AssertionFailure()
1751 << "Expected " << expectedMessage << ", actual " << readMessage;
1752 }
1753 return AssertionSuccess();
1754 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001755 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001756 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001757 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1758 return;
1759 }
1760 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001761 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001762 }
1763
1764 private:
1765 ConnectToServer mConnectToServer;
1766 base::unique_fd mFd;
1767 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1768 std::unique_ptr<RpcTransportCtx> mCtx;
1769 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1770 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001771 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001772 };
1773
1774 // Make A trust B.
1775 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001776 static status_t trust(RpcSecurity rpcSecurity,
1777 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1778 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001779 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001780 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1781 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1782 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001783 }
1784
1785 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001786};
1787
1788class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1789public:
1790 using Server = RpcTransportTestUtils::Server;
1791 using Client = RpcTransportTestUtils::Client;
1792 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001793 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001794 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1795 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001796 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001797 return ret;
1798 }
1799 static std::vector<ParamType> getRpcTranportTestParams() {
1800 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001801 for (auto serverVersion : testVersions()) {
1802 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1803 for (auto rpcSecurity : RpcSecurityValues()) {
1804 switch (rpcSecurity) {
1805 case RpcSecurity::RAW: {
1806 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1807 } break;
1808 case RpcSecurity::TLS: {
1809 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1810 serverVersion);
1811 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1812 serverVersion);
1813 } break;
1814 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001815 }
1816 }
1817 }
1818 return ret;
1819 }
1820 template <typename A, typename B>
1821 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001822 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1823 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001824 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1825 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001826 void SetUp() override {
1827 if constexpr (!kEnableRpcThreads) {
1828 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1829 }
1830 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001831};
1832
1833TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001834 auto server = std::make_unique<Server>();
1835 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001836
1837 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001838 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001839
1840 ASSERT_EQ(OK, trust(&client, server));
1841 ASSERT_EQ(OK, trust(server, &client));
1842
1843 server->start();
1844 client.run();
1845}
1846
1847TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001848 auto server = std::make_unique<Server>();
1849 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001850
1851 std::vector<Client> clients;
1852 for (int i = 0; i < 2; i++) {
1853 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001854 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001855 ASSERT_EQ(OK, trust(&client, server));
1856 ASSERT_EQ(OK, trust(server, &client));
1857 }
1858
1859 server->start();
1860 for (auto& client : clients) client.run();
1861}
1862
1863TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001864 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1865 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001866
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001867 auto untrustedServer = std::make_unique<Server>();
1868 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001869
1870 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001871 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001872
1873 ASSERT_EQ(OK, trust(untrustedServer, &client));
1874
1875 untrustedServer->start();
1876
1877 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1878 // the client can't verify the server's identity.
1879 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1880 client.run(handshakeOk);
1881}
1882TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001883 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1884 (void)serverVersion;
1885
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001886 auto validServer = std::make_unique<Server>();
1887 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001888
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001889 auto maliciousServer = std::make_unique<Server>();
1890 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001891
1892 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001893 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001894
1895 ASSERT_EQ(OK, trust(&client, validServer));
1896 ASSERT_EQ(OK, trust(validServer, &client));
1897 ASSERT_EQ(OK, trust(maliciousServer, &client));
1898
1899 maliciousServer->start();
1900
1901 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1902 // the client can't verify the server's identity.
1903 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1904 client.run(handshakeOk);
1905}
1906
1907TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001908 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1909 (void)serverVersion;
1910
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001911 auto server = std::make_unique<Server>();
1912 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001913
1914 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001915 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001916
1917 ASSERT_EQ(OK, trust(&client, server));
1918
1919 server->start();
1920
1921 // For TLS, Client should be able to verify server's identity, so client should see
1922 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1923 // identity and should drop the connection, so client shouldn't be able to read anything.
1924 bool readOk = rpcSecurity != RpcSecurity::TLS;
1925 client.run(true, readOk);
1926}
1927
1928TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001929 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1930 (void)serverVersion;
1931
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001932 auto server = std::make_unique<Server>();
1933 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001934
1935 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001936 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001937 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001938 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001939
1940 ASSERT_EQ(OK, trust(&validClient, server));
1941 ASSERT_EQ(OK, trust(&maliciousClient, server));
1942
1943 server->start();
1944
1945 // See UntrustedClient.
1946 bool readOk = rpcSecurity != RpcSecurity::TLS;
1947 maliciousClient.run(true, readOk);
1948}
1949
Yifan Hong67519322021-09-13 18:51:16 -07001950TEST_P(RpcTransportTest, Trigger) {
1951 std::string msg2 = ", world!";
1952 std::mutex writeMutex;
1953 std::condition_variable writeCv;
1954 bool shouldContinueWriting = false;
1955 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001956 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001957 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001958 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1959 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001960 if (status != OK) return AssertionFailure() << statusToString(status);
1961
1962 {
1963 std::unique_lock<std::mutex> lock(writeMutex);
1964 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1965 return AssertionFailure() << "write barrier not cleared in time!";
1966 }
1967 }
1968
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001969 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00001970 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1971 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07001972 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001973 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001974 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001975 << statusToString(status);
1976 return AssertionSuccess();
1977 };
1978
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001979 auto server = std::make_unique<Server>();
1980 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001981
1982 // Set up client
1983 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001984 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001985
1986 // Exchange keys
1987 ASSERT_EQ(OK, trust(&client, server));
1988 ASSERT_EQ(OK, trust(server, &client));
1989
1990 server->setPostConnect(serverPostConnect);
1991
Yifan Hong67519322021-09-13 18:51:16 -07001992 server->start();
1993 // connect() to server and do handshake
1994 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001995 // read the first message. This ensures that server has finished handshake and start handling
1996 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001997 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001998 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1999 // write is on an FdTrigger that has been shut down.
2000 server->shutdown();
2001 // Continues server thread to write the second message.
2002 {
Yifan Hong22211f82021-09-14 12:32:25 -07002003 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002004 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002005 }
Yifan Hong22211f82021-09-14 12:32:25 -07002006 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002007 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002008 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002009 // On the client side, second read fails with DEAD_OBJECT
2010 ASSERT_FALSE(client.readMessage(msg2));
2011}
2012
Yifan Hong1deca4b2021-09-10 16:16:44 -07002013INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002014 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002015 RpcTransportTest::PrintParamInfo);
2016
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002017class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002018 : public testing::TestWithParam<
2019 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002020public:
2021 template <typename A, typename B>
2022 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002023 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2024 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002025 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2026 }
2027 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002028 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2029 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2030 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002031 };
2032};
2033
2034TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002035 if constexpr (!kEnableRpcThreads) {
2036 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2037 }
2038
Frederick Mayledc07cf82022-05-26 20:30:12 +00002039 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002040
2041 std::vector<uint8_t> pkeyData, certData;
2042 {
2043 auto pkey = makeKeyPairForSelfSignedCert();
2044 ASSERT_NE(nullptr, pkey);
2045 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2046 ASSERT_NE(nullptr, cert);
2047 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2048 certData = serializeCertificate(cert.get(), certificateFormat);
2049 }
2050
2051 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2052 auto desCert = deserializeCertificate(certData, certificateFormat);
2053 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002054 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2055 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002056
2057 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2058 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2059
2060 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2061 ASSERT_TRUE(client.setUp(utilsParam));
2062
2063 ASSERT_EQ(OK, trust(&client, server));
2064 ASSERT_EQ(OK, trust(server, &client));
2065
2066 server->start();
2067 client.run();
2068}
2069
2070INSTANTIATE_TEST_CASE_P(
2071 BinderRpc, RpcTransportTlsKeyTest,
2072 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2073 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002074 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2075 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002076 RpcTransportTlsKeyTest::PrintParamInfo);
2077
Steven Morelandc1635952021-04-01 16:20:47 +00002078} // namespace android
2079
2080int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002081 ::testing::InitGoogleTest(&argc, argv);
2082 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002083
Steven Moreland5553ac42020-11-11 02:14:45 +00002084 return RUN_ALL_TESTS();
2085}