blob: f6ab6679a3dd1a93c984c0739d7603e704e9101c [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
Devin Moore66d5b7a2022-07-07 21:42:10 +000054 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "format must be set before data is written");
Steven Moreland1fda67b2021-04-02 18:35:50 +000055}
56
Frederick Mayledc07cf82022-05-26 20:30:12 +000057class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
Yifan Hong702115c2021-06-24 15:39:18 -070058public:
59 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +000060 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
61 std::to_string(std::get<1>(info.param));
Yifan Hong702115c2021-06-24 15:39:18 -070062 }
63};
64
Frederick Mayledc07cf82022-05-26 20:30:12 +000065TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -070066 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
67 int sinkFd = sink.get();
Frederick Mayledc07cf82022-05-26 20:30:12 +000068 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
69 server->setProtocolVersion(std::get<1>(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -070070 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -070071 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -070072 ASSERT_TRUE(server->hasServer());
73 base::unique_fd retrieved = server->releaseServer();
74 ASSERT_FALSE(server->hasServer());
75 ASSERT_EQ(sinkFd, retrieved.get());
76}
77
Steven Morelandbf57bce2021-07-26 15:26:12 -070078TEST(BinderRpc, CannotUseNextWireVersion) {
79 auto session = RpcSession::make();
80 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
81 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
82 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
83 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
84}
85
86TEST(BinderRpc, CanUseExperimentalWireVersion) {
87 auto session = RpcSession::make();
88 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
89}
90
Steven Moreland5553ac42020-11-11 02:14:45 +000091using android::binder::Status;
92
93#define EXPECT_OK(status) \
94 do { \
95 Status stat = (status); \
96 EXPECT_TRUE(stat.isOk()) << stat; \
97 } while (false)
98
Frederick Maylea12b0962022-06-25 01:13:22 +000099static std::string WaitStatusToString(int wstatus) {
100 if (WIFEXITED(wstatus)) {
101 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
102 }
103 if (WIFSIGNALED(wstatus)) {
104 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
105 }
106 return base::StringPrintf("unexpected state %d", wstatus);
107}
108
Steven Moreland5553ac42020-11-11 02:14:45 +0000109class Process {
110public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700111 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700112 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
113 android::base::borrowed_fd /* readEnd */)>& f) {
114 android::base::unique_fd childWriteEnd;
115 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +0000116 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
117 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000118 if (0 == (mPid = fork())) {
119 // racey: assume parent doesn't crash before this is set
120 prctl(PR_SET_PDEATHSIG, SIGHUP);
121
Yifan Hong1deca4b2021-09-10 16:16:44 -0700122 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000123
124 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000125 }
126 }
127 ~Process() {
128 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000129 int wstatus;
130 waitpid(mPid, &wstatus, 0);
131 if (mCustomExitStatusCheck) {
132 mCustomExitStatusCheck(wstatus);
133 } else {
134 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
135 << "server process failed: " << WaitStatusToString(wstatus);
136 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000137 }
138 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700139 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700140 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000141
Frederick Maylea12b0962022-06-25 01:13:22 +0000142 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
143 mCustomExitStatusCheck = std::move(f);
144 }
145
Frederick Mayle69a0c992022-05-26 20:38:39 +0000146 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
147 void terminate() { kill(mPid, SIGTERM); }
148
Steven Moreland5553ac42020-11-11 02:14:45 +0000149private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000150 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000151 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700152 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700153 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000154};
155
156static std::string allocateSocketAddress() {
157 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000158 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700159 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
160 unlink(ret.c_str());
161 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000162};
163
Steven Morelandda573042021-06-12 01:13:45 +0000164static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000165 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000166 return vsockPort++;
167}
168
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000169struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000170 // reference to process hosting a socket server
171 Process host;
172
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000173 struct SessionInfo {
174 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000175 sp<IBinder> root;
176 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000177
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000178 // client session objects associated with other process
179 // each one represents a separate session
180 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000181
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000182 ProcessSession(ProcessSession&&) = default;
183 ~ProcessSession() {
184 for (auto& session : sessions) {
185 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000186 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000187
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000188 for (auto& info : sessions) {
189 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000190
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000191 EXPECT_NE(nullptr, session);
192 EXPECT_NE(nullptr, session->state());
193 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000194
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000195 wp<RpcSession> weakSession = session;
196 session = nullptr;
197 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000198 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000199 }
200};
201
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000202// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000203// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000204struct BinderRpcTestProcessSession {
205 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000206
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000207 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000208 sp<IBinder> rootBinder;
209
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000210 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000211 sp<IBinderRpcTest> rootIface;
212
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000213 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000214 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000215
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000216 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
217 ~BinderRpcTestProcessSession() {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000218 if (!expectAlreadyShutdown) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000219 EXPECT_NE(nullptr, rootIface);
220 if (rootIface == nullptr) return;
221
Steven Moreland736664b2021-05-01 04:27:25 +0000222 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000223 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000224 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000225 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000226 for (auto remoteCount : remoteCounts) {
227 EXPECT_EQ(remoteCount, 1);
228 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000229
Steven Moreland798e0d12021-07-14 23:19:25 +0000230 // even though it is on another thread, shutdown races with
231 // the transaction reply being written
232 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
233 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
234 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000235 }
236
237 rootIface = nullptr;
238 rootBinder = nullptr;
239 }
240};
241
Yifan Hong1deca4b2021-09-10 16:16:44 -0700242static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700243 base::unique_fd serverFd(
244 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
245 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700246 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
247 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700248
249 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
250 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700251 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
252 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700253 }
254 return serverFd;
255}
256
Andrei Homescu2a298012022-06-15 01:08:54 +0000257using RunServiceFn = void (*)(android::base::borrowed_fd writeEnd,
258 android::base::borrowed_fd readEnd);
259
260class BinderRpc : public ::testing::TestWithParam<
261 std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t, bool, bool>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000262public:
Frederick Mayle69a0c992022-05-26 20:38:39 +0000263 SocketType socketType() const { return std::get<0>(GetParam()); }
264 RpcSecurity rpcSecurity() const { return std::get<1>(GetParam()); }
265 uint32_t clientVersion() const { return std::get<2>(GetParam()); }
266 uint32_t serverVersion() const { return std::get<3>(GetParam()); }
Andrei Homescu2a298012022-06-15 01:08:54 +0000267 bool singleThreaded() const { return std::get<4>(GetParam()); }
268 bool noKernel() const { return std::get<5>(GetParam()); }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000269
270 // Whether the test params support sending FDs in parcels.
271 bool supportsFdTransport() const {
272 return clientVersion() >= 1 && serverVersion() >= 1 && rpcSecurity() != RpcSecurity::TLS &&
273 (socketType() == SocketType::PRECONNECTED || socketType() == SocketType::UNIX);
274 }
275
Yifan Hong702115c2021-06-24 15:39:18 -0700276 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000277 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
278 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
Frederick Mayledc07cf82022-05-26 20:30:12 +0000279 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Andrei Homescu2a298012022-06-15 01:08:54 +0000280 if (singleThreaded) {
281 ret += "_single_threaded";
282 }
283 if (noKernel) {
284 ret += "_no_kernel";
285 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700286 return ret;
287 }
288
Steven Morelandc1635952021-04-01 16:20:47 +0000289 // This creates a new process serving an interface on a certain number of
290 // threads.
Andrei Homescu2a298012022-06-15 01:08:54 +0000291 ProcessSession createRpcTestSocketServerProcessEtc(const BinderRpcOptions& options) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000292 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000293
Yifan Hong702115c2021-06-24 15:39:18 -0700294 SocketType socketType = std::get<0>(GetParam());
295 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000296 uint32_t clientVersion = std::get<2>(GetParam());
297 uint32_t serverVersion = std::get<3>(GetParam());
Andrei Homescu2a298012022-06-15 01:08:54 +0000298 bool singleThreaded = std::get<4>(GetParam());
299 bool noKernel = std::get<5>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000300
Andrei Homescu2a298012022-06-15 01:08:54 +0000301 std::string path = android::base::GetExecutableDirectory();
302 auto servicePath =
303 android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
304 singleThreaded ? "_single_threaded" : "",
305 noKernel ? "_no_kernel" : "");
Steven Morelandc1635952021-04-01 16:20:47 +0000306
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000307 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000308 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700309 android::base::borrowed_fd readEnd) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000310 auto writeFd = std::to_string(writeEnd.get());
311 auto readFd = std::to_string(readEnd.get());
312 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
313 NULL);
Steven Morelandc1635952021-04-01 16:20:47 +0000314 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000315 };
316
Andrei Homescu2a298012022-06-15 01:08:54 +0000317 BinderRpcTestServerConfig serverConfig;
318 serverConfig.numThreads = options.numThreads;
319 serverConfig.socketType = static_cast<int32_t>(socketType);
320 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
321 serverConfig.serverVersion = serverVersion;
322 serverConfig.vsockPort = allocateVsockPort();
323 serverConfig.addr = allocateSocketAddress();
324 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
325 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
326 static_cast<int32_t>(mode));
327 }
328 writeToFd(ret.host.writeEnd(), serverConfig);
329
Yifan Hong1deca4b2021-09-10 16:16:44 -0700330 std::vector<sp<RpcSession>> sessions;
331 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
332 for (size_t i = 0; i < options.numSessions; i++) {
333 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
334 }
335
336 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
337 BinderRpcTestClientInfo clientInfo;
338 for (const auto& session : sessions) {
339 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700340 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700341 }
342 writeToFd(ret.host.writeEnd(), clientInfo);
343
344 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700345 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700346 CHECK_NE(0, serverInfo.port);
347 }
348
349 if (rpcSecurity == RpcSecurity::TLS) {
350 const auto& serverCert = serverInfo.cert.data;
351 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700352 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
353 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700354 }
355
Steven Moreland2372f9d2021-08-05 15:42:01 -0700356 status_t status;
357
Yifan Hong1deca4b2021-09-10 16:16:44 -0700358 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000359 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700360 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700361 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000362 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Moreland659416d2021-05-11 00:47:50 +0000363
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000364 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700365 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700366 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000367 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700368 });
Steven Moreland4198a122021-08-03 17:37:58 -0700369 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000370 case SocketType::UNIX:
Andrei Homescu2a298012022-06-15 01:08:54 +0000371 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000372 break;
373 case SocketType::VSOCK:
Andrei Homescu2a298012022-06-15 01:08:54 +0000374 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000375 break;
376 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700377 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000378 break;
379 default:
380 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000381 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000382 if (options.allowConnectFailure && status != OK) {
383 ret.sessions.clear();
384 break;
385 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700386 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000387 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000388 }
Steven Morelandc1635952021-04-01 16:20:47 +0000389 return ret;
390 }
391
Andrei Homescu2a298012022-06-15 01:08:54 +0000392 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const BinderRpcOptions& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000393 BinderRpcTestProcessSession ret{
Andrei Homescu2a298012022-06-15 01:08:54 +0000394 .proc = createRpcTestSocketServerProcessEtc(options),
Steven Morelandc1635952021-04-01 16:20:47 +0000395 };
396
Frederick Mayle69a0c992022-05-26 20:38:39 +0000397 ret.rootBinder = ret.proc.sessions.empty() ? nullptr : ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000398 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
399
400 return ret;
401 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700402
403 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
404 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000405};
406
Andrei Homescu12106de2022-04-27 04:42:21 +0000407// Test fixture for tests that start multiple threads.
408// This includes tests with one thread but multiple sessions,
409// since a server uses one thread per session.
410class BinderRpcThreads : public BinderRpc {
411public:
412 void SetUp() override {
413 if constexpr (!kEnableRpcThreads) {
414 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
415 }
416 }
417};
418
Steven Morelandc1635952021-04-01 16:20:47 +0000419TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000420 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000421 ASSERT_NE(proc.rootBinder, nullptr);
422 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
423}
424
Steven Moreland4cf688f2021-03-31 01:48:58 +0000425TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000426 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000427 ASSERT_NE(proc.rootBinder, nullptr);
428 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
429}
430
Andrei Homescu12106de2022-04-27 04:42:21 +0000431TEST_P(BinderRpcThreads, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000432 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000433 for (auto session : proc.proc.sessions) {
434 ASSERT_NE(nullptr, session.root);
435 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000436 }
437}
438
Andrei Homescu12106de2022-04-27 04:42:21 +0000439TEST_P(BinderRpcThreads, SeparateRootObject) {
Steven Moreland51c44a92021-10-14 16:50:35 -0700440 SocketType type = std::get<0>(GetParam());
441 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
442 // we can't get port numbers for unix sockets
443 return;
444 }
445
446 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
447
448 int port1 = 0;
449 EXPECT_OK(proc.rootIface->getClientPort(&port1));
450
451 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
452 int port2;
453 EXPECT_OK(rootIface2->getClientPort(&port2));
454
455 // we should have a different IBinderRpcTest object created for each
456 // session, because we use setPerSessionRootObject
457 EXPECT_NE(port1, port2);
458}
459
Steven Morelandc1635952021-04-01 16:20:47 +0000460TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000461 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000462 Parcel data;
463 Parcel reply;
464 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
465}
466
Steven Moreland67753c32021-04-02 18:45:19 +0000467TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700468 auto proc1 = createRpcTestSocketServerProcess({});
469 auto proc2 = createRpcTestSocketServerProcess({});
470
471 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000472
473 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700474 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000475 p1.writeInt32(3);
476
Frederick Maylea4ed5672022-06-17 22:03:38 +0000477 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700478 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
479
Steven Moreland67753c32021-04-02 18:45:19 +0000480 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700481 p2.markForBinder(proc2.rootBinder);
482 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000483
484 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
485 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
486}
487
Steven Morelandc1635952021-04-01 16:20:47 +0000488TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000489 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000490 Parcel data;
491 data.markForBinder(proc.rootBinder);
492 Parcel reply;
493 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
494}
495
Steven Morelandc1635952021-04-01 16:20:47 +0000496TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000497 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000498 EXPECT_OK(proc.rootIface->sendString("asdf"));
499}
500
Steven Morelandc1635952021-04-01 16:20:47 +0000501TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000502 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000503 std::string doubled;
504 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
505 EXPECT_EQ("cool cool ", doubled);
506}
507
Steven Morelandc1635952021-04-01 16:20:47 +0000508TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000509 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000510 std::string single = std::string(1024, 'a');
511 std::string doubled;
512 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
513 EXPECT_EQ(single + single, doubled);
514}
515
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000516TEST_P(BinderRpc, InvalidNullBinderReturn) {
517 auto proc = createRpcTestSocketServerProcess({});
518
519 sp<IBinder> outBinder;
520 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
521}
522
Steven Morelandc1635952021-04-01 16:20:47 +0000523TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000524 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000525
526 int32_t pingResult;
527 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
528 EXPECT_EQ(OK, pingResult);
529
530 EXPECT_EQ(0, MyBinderRpcSession::gNum);
531}
532
Steven Morelandc1635952021-04-01 16:20:47 +0000533TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000534 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000535
536 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
537 sp<IBinder> outBinder;
538 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
539 EXPECT_EQ(inBinder, outBinder);
540
541 wp<IBinder> weak = inBinder;
542 inBinder = nullptr;
543 outBinder = nullptr;
544
545 // Force reading a reply, to process any pending dec refs from the other
546 // process (the other process will process dec refs there before processing
547 // the ping here).
548 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
549
550 EXPECT_EQ(nullptr, weak.promote());
551
552 EXPECT_EQ(0, MyBinderRpcSession::gNum);
553}
554
Steven Morelandc1635952021-04-01 16:20:47 +0000555TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000556 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000557
558 sp<IBinderRpcSession> session;
559 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
560
561 sp<IBinder> inBinder = IInterface::asBinder(session);
562 sp<IBinder> outBinder;
563 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
564 EXPECT_EQ(inBinder, outBinder);
565
566 wp<IBinder> weak = inBinder;
567 session = nullptr;
568 inBinder = nullptr;
569 outBinder = nullptr;
570
571 // Force reading a reply, to process any pending dec refs from the other
572 // process (the other process will process dec refs there before processing
573 // the ping here).
574 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
575
576 EXPECT_EQ(nullptr, weak.promote());
577}
578
Steven Morelandc1635952021-04-01 16:20:47 +0000579TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000580 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000581
582 sp<IBinder> outBinder;
583 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
584 EXPECT_EQ(nullptr, outBinder);
585}
586
Steven Morelandc1635952021-04-01 16:20:47 +0000587TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000588 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000589
590 IBinder* ptr = nullptr;
591 {
592 sp<IBinder> binder = new BBinder();
593 ptr = binder.get();
594 EXPECT_OK(proc.rootIface->holdBinder(binder));
595 }
596
597 sp<IBinder> held;
598 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
599
600 EXPECT_EQ(held.get(), ptr);
601
602 // stop holding binder, because we test to make sure references are cleaned
603 // up
604 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
605 // and flush ref counts
606 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
607}
608
609// START TESTS FOR LIMITATIONS OF SOCKET BINDER
610// These are behavioral differences form regular binder, where certain usecases
611// aren't supported.
612
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000613TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000614 auto proc1 = createRpcTestSocketServerProcess({});
615 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000616
617 sp<IBinder> outBinder;
618 EXPECT_EQ(INVALID_OPERATION,
619 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
620}
621
Andrei Homescu12106de2022-04-27 04:42:21 +0000622TEST_P(BinderRpcThreads, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000623 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000624
625 sp<IBinder> outBinder;
626 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000627 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000628 .transactionError());
629}
630
Steven Morelandc1635952021-04-01 16:20:47 +0000631TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000632 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000633 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
634 "at build time.";
635 }
636
Steven Moreland4313d7e2021-07-15 23:41:22 +0000637 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000638
639 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
640 sp<IBinder> outBinder;
641 EXPECT_EQ(INVALID_OPERATION,
642 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
643}
644
Steven Morelandc1635952021-04-01 16:20:47 +0000645TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000646 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000647 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
648 "at build time.";
649 }
650
Steven Moreland4313d7e2021-07-15 23:41:22 +0000651 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000652
653 // for historical reasons, IServiceManager interface only returns the
654 // exception code
655 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
656 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
657}
658
659// END TESTS FOR LIMITATIONS OF SOCKET BINDER
660
Steven Morelandc1635952021-04-01 16:20:47 +0000661TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000662 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000663
664 sp<IBinder> outBinder;
665 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
666 EXPECT_EQ(proc.rootBinder, outBinder);
667}
668
Steven Morelandc1635952021-04-01 16:20:47 +0000669TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000670 auto proc = createRpcTestSocketServerProcess({
671 // Enable FD support because it uses more stack space and so represents
672 // something closer to a worst case scenario.
673 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
674 .serverSupportedFileDescriptorTransportModes =
675 {RpcSession::FileDescriptorTransportMode::UNIX},
676 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000677
678 auto nastyNester = sp<MyBinderRpcTest>::make();
679 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
680
681 wp<IBinder> weak = nastyNester;
682 nastyNester = nullptr;
683 EXPECT_EQ(nullptr, weak.promote());
684}
685
Steven Morelandc1635952021-04-01 16:20:47 +0000686TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000687 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000688
689 sp<IBinder> a;
690 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
691
692 sp<IBinder> b;
693 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
694
695 EXPECT_EQ(a, b);
696}
697
Steven Morelandc1635952021-04-01 16:20:47 +0000698TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000699 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000700
701 sp<IBinder> a;
702 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
703 wp<IBinder> weak = a;
704 a = nullptr;
705
706 sp<IBinder> b;
707 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
708
709 // this is the wrong behavior, since BpBinder
710 // doesn't implement onIncStrongAttempted
711 // but make sure there is no crash
712 EXPECT_EQ(nullptr, weak.promote());
713
714 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
715
716 // In order to fix this:
717 // - need to have incStrongAttempted reflected across IPC boundary (wait for
718 // response to promote - round trip...)
719 // - sendOnLastWeakRef, to delete entries out of RpcState table
720 EXPECT_EQ(b, weak.promote());
721}
722
723#define expectSessions(expected, iface) \
724 do { \
725 int session; \
726 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
727 EXPECT_EQ(expected, session); \
728 } while (false)
729
Steven Morelandc1635952021-04-01 16:20:47 +0000730TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000731 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000732
733 sp<IBinderRpcSession> session;
734 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
735 std::string out;
736 EXPECT_OK(session->getName(&out));
737 EXPECT_EQ("aoeu", out);
738
739 expectSessions(1, proc.rootIface);
740 session = nullptr;
741 expectSessions(0, proc.rootIface);
742}
743
Steven Morelandc1635952021-04-01 16:20:47 +0000744TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000745 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000746
747 std::vector<sp<IBinderRpcSession>> sessions;
748
749 for (size_t i = 0; i < 15; i++) {
750 expectSessions(i, proc.rootIface);
751 sp<IBinderRpcSession> session;
752 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
753 sessions.push_back(session);
754 }
755 expectSessions(sessions.size(), proc.rootIface);
756 for (size_t i = 0; i < sessions.size(); i++) {
757 std::string out;
758 EXPECT_OK(sessions.at(i)->getName(&out));
759 EXPECT_EQ(std::to_string(i), out);
760 }
761 expectSessions(sessions.size(), proc.rootIface);
762
763 while (!sessions.empty()) {
764 sessions.pop_back();
765 expectSessions(sessions.size(), proc.rootIface);
766 }
767 expectSessions(0, proc.rootIface);
768}
769
770size_t epochMillis() {
771 using std::chrono::duration_cast;
772 using std::chrono::milliseconds;
773 using std::chrono::seconds;
774 using std::chrono::system_clock;
775 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
776}
777
Andrei Homescu12106de2022-04-27 04:42:21 +0000778TEST_P(BinderRpcThreads, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000779 constexpr size_t kNumThreads = 10;
780
Steven Moreland4313d7e2021-07-15 23:41:22 +0000781 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000782
783 EXPECT_OK(proc.rootIface->lock());
784
785 // block all but one thread taking locks
786 std::vector<std::thread> ts;
787 for (size_t i = 0; i < kNumThreads - 1; i++) {
788 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
789 }
790
791 usleep(100000); // give chance for calls on other threads
792
793 // other calls still work
794 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
795
796 constexpr size_t blockTimeMs = 500;
797 size_t epochMsBefore = epochMillis();
798 // after this, we should never see a response within this time
799 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
800
801 // this call should be blocked for blockTimeMs
802 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
803
804 size_t epochMsAfter = epochMillis();
805 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
806
807 for (auto& t : ts) t.join();
808}
809
Yifan Hong1f44f982021-10-08 17:16:47 -0700810void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
811 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000812 size_t epochMsBefore = epochMillis();
813
814 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700815 for (size_t i = 0; i < numCalls; i++) {
816 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000817 }
818
819 for (auto& t : ts) t.join();
820
821 size_t epochMsAfter = epochMillis();
822
Yifan Hong1f44f982021-10-08 17:16:47 -0700823 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000824
825 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700826 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
827}
828
Andrei Homescu12106de2022-04-27 04:42:21 +0000829TEST_P(BinderRpcThreads, ThreadPoolOverSaturated) {
Yifan Hong1f44f982021-10-08 17:16:47 -0700830 constexpr size_t kNumThreads = 10;
831 constexpr size_t kNumCalls = kNumThreads + 3;
832 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
833 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
834}
835
Andrei Homescu12106de2022-04-27 04:42:21 +0000836TEST_P(BinderRpcThreads, ThreadPoolLimitOutgoing) {
Yifan Hong1f44f982021-10-08 17:16:47 -0700837 constexpr size_t kNumThreads = 20;
838 constexpr size_t kNumOutgoingConnections = 10;
839 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
840 auto proc = createRpcTestSocketServerProcess(
841 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
842 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000843}
844
Andrei Homescu12106de2022-04-27 04:42:21 +0000845TEST_P(BinderRpcThreads, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000846 constexpr size_t kNumClientThreads = 10;
847 constexpr size_t kNumServerThreads = 10;
848 constexpr size_t kNumCalls = 100;
849
Steven Moreland4313d7e2021-07-15 23:41:22 +0000850 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000851
852 std::vector<std::thread> threads;
853 for (size_t i = 0; i < kNumClientThreads; i++) {
854 threads.push_back(std::thread([&] {
855 for (size_t j = 0; j < kNumCalls; j++) {
856 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000857 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000858 EXPECT_EQ(proc.rootBinder, out);
859 }
860 }));
861 }
862
863 for (auto& t : threads) t.join();
864}
865
Steven Moreland925ba0a2021-09-17 18:06:32 -0700866static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
867 std::vector<std::thread> threads;
868 for (size_t i = 0; i < threadCount; i++) {
869 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
870 }
871 for (auto& t : threads) t.join();
872}
873
Andrei Homescu12106de2022-04-27 04:42:21 +0000874TEST_P(BinderRpcThreads, OnewayStressTest) {
Steven Morelandc6046982021-04-20 00:49:42 +0000875 constexpr size_t kNumClientThreads = 10;
876 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700877 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000878
Steven Moreland4313d7e2021-07-15 23:41:22 +0000879 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000880
881 std::vector<std::thread> threads;
882 for (size_t i = 0; i < kNumClientThreads; i++) {
883 threads.push_back(std::thread([&] {
884 for (size_t j = 0; j < kNumCalls; j++) {
885 EXPECT_OK(proc.rootIface->sendString("a"));
886 }
Steven Morelandc6046982021-04-20 00:49:42 +0000887 }));
888 }
889
890 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700891
892 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000893}
894
Steven Morelandc1635952021-04-01 16:20:47 +0000895TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000896 constexpr size_t kReallyLongTimeMs = 100;
897 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
898
Steven Moreland4313d7e2021-07-15 23:41:22 +0000899 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000900
901 size_t epochMsBefore = epochMillis();
902
903 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
904
905 size_t epochMsAfter = epochMillis();
906 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
907}
908
Andrei Homescu12106de2022-04-27 04:42:21 +0000909TEST_P(BinderRpcThreads, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000910 constexpr size_t kNumSleeps = 10;
911 constexpr size_t kNumExtraServerThreads = 4;
912 constexpr size_t kSleepMs = 50;
913
914 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000915 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000916
917 EXPECT_OK(proc.rootIface->lock());
918
Steven Moreland1c678802021-09-17 16:48:47 -0700919 size_t epochMsBefore = epochMillis();
920
921 // all these *Async commands should be queued on the server sequentially,
922 // even though there are multiple threads.
923 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000924 proc.rootIface->sleepMsAsync(kSleepMs);
925 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000926 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
927
Steven Moreland1c678802021-09-17 16:48:47 -0700928 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000929 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700930
Steven Moreland5553ac42020-11-11 02:14:45 +0000931 size_t epochMsAfter = epochMillis();
932
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000933 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000934
Steven Moreland925ba0a2021-09-17 18:06:32 -0700935 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000936}
937
Andrei Homescu12106de2022-04-27 04:42:21 +0000938TEST_P(BinderRpcThreads, OnewayCallExhaustion) {
Steven Morelandd45be622021-06-04 02:19:37 +0000939 constexpr size_t kNumClients = 2;
940 constexpr size_t kTooLongMs = 1000;
941
Steven Moreland4313d7e2021-07-15 23:41:22 +0000942 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000943
944 // Build up oneway calls on the second session to make sure it terminates
945 // and shuts down. The first session should be unaffected (proc destructor
946 // checks the first session).
947 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
948
949 std::vector<std::thread> threads;
950 for (size_t i = 0; i < kNumClients; i++) {
951 // one of these threads will get stuck queueing a transaction once the
952 // socket fills up, the other will be able to fill up transactions on
953 // this object
954 threads.push_back(std::thread([&] {
955 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
956 }
957 }));
958 }
959 for (auto& t : threads) t.join();
960
961 Status status = iface->sleepMsAsync(kTooLongMs);
962 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
963
Steven Moreland798e0d12021-07-14 23:19:25 +0000964 // now that it has died, wait for the remote session to shutdown
965 std::vector<int32_t> remoteCounts;
966 do {
967 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
968 } while (remoteCounts.size() == kNumClients);
969
Steven Morelandd45be622021-06-04 02:19:37 +0000970 // the second session should be shutdown in the other process by the time we
971 // are able to join above (it'll only be hung up once it finishes processing
972 // any pending commands). We need to erase this session from the record
973 // here, so that the destructor for our session won't check that this
974 // session is valid, but we still want it to test the other session.
975 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
976}
977
Steven Moreland659416d2021-05-11 00:47:50 +0000978TEST_P(BinderRpc, Callbacks) {
979 const static std::string kTestString = "good afternoon!";
980
Andrei Homescu2a298012022-06-15 01:08:54 +0000981 bool bothSingleThreaded = !kEnableRpcThreads || singleThreaded();
982
Steven Morelandc7d40132021-06-10 03:42:11 +0000983 for (bool callIsOneway : {true, false}) {
984 for (bool callbackIsOneway : {true, false}) {
985 for (bool delayed : {true, false}) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000986 if (bothSingleThreaded && (callIsOneway || callbackIsOneway || delayed)) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000987 // we have no incoming connections to receive the callback
988 continue;
989 }
990
Andrei Homescu2a298012022-06-15 01:08:54 +0000991 size_t numIncomingConnections = bothSingleThreaded ? 0 : 1;
Steven Moreland4313d7e2021-07-15 23:41:22 +0000992 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +0000993 {.numThreads = 1,
994 .numSessions = 1,
Andrei Homescu2a298012022-06-15 01:08:54 +0000995 .numIncomingConnections = numIncomingConnections});
Steven Morelandc7d40132021-06-10 03:42:11 +0000996 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +0000997
Steven Morelandc7d40132021-06-10 03:42:11 +0000998 if (callIsOneway) {
999 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1000 kTestString));
1001 } else {
1002 EXPECT_OK(
1003 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1004 }
Steven Moreland659416d2021-05-11 00:47:50 +00001005
Steven Moreland03ecce62022-05-13 23:22:05 +00001006 // if both transactions are synchronous and the response is sent back on the
1007 // same thread, everything should have happened in a nested call. Otherwise,
1008 // the callback will be processed on another thread.
1009 if (callIsOneway || callbackIsOneway || delayed) {
1010 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001011 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001012 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1013 }
Steven Moreland659416d2021-05-11 00:47:50 +00001014
Steven Morelandc7d40132021-06-10 03:42:11 +00001015 EXPECT_EQ(cb->mValues.size(), 1)
1016 << "callIsOneway: " << callIsOneway
1017 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1018 if (cb->mValues.empty()) continue;
1019 EXPECT_EQ(cb->mValues.at(0), kTestString)
1020 << "callIsOneway: " << callIsOneway
1021 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001022
Steven Morelandc7d40132021-06-10 03:42:11 +00001023 // since we are severing the connection, we need to go ahead and
1024 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001025 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1026 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1027 }
Steven Moreland659416d2021-05-11 00:47:50 +00001028
Steven Moreland1b304292021-07-15 22:59:34 +00001029 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001030 // need to manually shut it down
1031 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven 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
Devin Moore66d5b7a2022-07-07 21:42:10 +00001045TEST_P(BinderRpc, SingleDeathRecipient) {
1046 if (singleThreaded() || !kEnableRpcThreads) {
1047 GTEST_SKIP() << "This test requires multiple threads";
1048 }
1049 class MyDeathRec : public IBinder::DeathRecipient {
1050 public:
1051 void binderDied(const wp<IBinder>& /* who */) override {
1052 dead = true;
1053 mCv.notify_one();
1054 }
1055 std::mutex mMtx;
1056 std::condition_variable mCv;
1057 bool dead = false;
1058 };
1059
1060 // Death recipient needs to have an incoming connection to be called
1061 auto proc = createRpcTestSocketServerProcess(
1062 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1063
1064 auto dr = sp<MyDeathRec>::make();
1065 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1066
1067 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1068 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1069 }
1070
1071 std::unique_lock<std::mutex> lock(dr->mMtx);
1072 if (!dr->dead) {
1073 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1074 }
1075 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1076
1077 // need to wait for the session to shutdown so we don't "Leak session"
1078 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1079 proc.expectAlreadyShutdown = true;
1080}
1081
1082TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
1083 if (singleThreaded() || !kEnableRpcThreads) {
1084 GTEST_SKIP() << "This test requires multiple threads";
1085 }
1086 class MyDeathRec : public IBinder::DeathRecipient {
1087 public:
1088 void binderDied(const wp<IBinder>& /* who */) override {
1089 dead = true;
1090 mCv.notify_one();
1091 }
1092 std::mutex mMtx;
1093 std::condition_variable mCv;
1094 bool dead = false;
1095 };
1096
1097 // Death recipient needs to have an incoming connection to be called
1098 auto proc = createRpcTestSocketServerProcess(
1099 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1100
1101 auto dr = sp<MyDeathRec>::make();
1102 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1103
1104 // Explicitly calling shutDownAndWait will cause the death recipients
1105 // to be called.
1106 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1107
1108 std::unique_lock<std::mutex> lock(dr->mMtx);
1109 if (!dr->dead) {
1110 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1111 }
1112 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1113
1114 proc.proc.host.terminate();
1115 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1116 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1117 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1118 });
1119 proc.expectAlreadyShutdown = true;
1120}
1121
1122TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1123 class MyDeathRec : public IBinder::DeathRecipient {
1124 public:
1125 void binderDied(const wp<IBinder>& /* who */) override {}
1126 };
1127
1128 auto proc = createRpcTestSocketServerProcess(
1129 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1130
1131 auto dr = sp<MyDeathRec>::make();
1132 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1133 "Cannot register a DeathRecipient without any incoming connections.");
1134}
1135
1136TEST_P(BinderRpc, UnlinkDeathRecipient) {
1137 if (singleThreaded() || !kEnableRpcThreads) {
1138 GTEST_SKIP() << "This test requires multiple threads";
1139 }
1140 class MyDeathRec : public IBinder::DeathRecipient {
1141 public:
1142 void binderDied(const wp<IBinder>& /* who */) override {
1143 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1144 }
1145 };
1146
1147 // Death recipient needs to have an incoming connection to be called
1148 auto proc = createRpcTestSocketServerProcess(
1149 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1150
1151 auto dr = sp<MyDeathRec>::make();
1152 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1153 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1154
1155 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1156 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1157 }
1158
1159 // need to wait for the session to shutdown so we don't "Leak session"
1160 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1161 proc.expectAlreadyShutdown = true;
1162}
1163
Steven Moreland195edb82021-06-08 02:44:39 +00001164TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001165 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001166 auto cb = sp<MyBinderRpcCallback>::make();
1167
1168 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1169 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1170}
1171
Steven Morelandc1635952021-04-01 16:20:47 +00001172TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001173 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001174 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001175
1176 // make sure there is some state during crash
1177 // 1. we hold their binder
1178 sp<IBinderRpcSession> session;
1179 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1180 // 2. they hold our binder
1181 sp<IBinder> binder = new BBinder();
1182 EXPECT_OK(proc.rootIface->holdBinder(binder));
1183
1184 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1185 << "Do death cleanup: " << doDeathCleanup;
1186
Frederick Maylea12b0962022-06-25 01:13:22 +00001187 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1188 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1189 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1190 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001191 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001192 }
1193}
1194
Steven Morelandd7302072021-05-15 01:32:04 +00001195TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001196 // This test only works if the current process shared the internal state of
1197 // ProcessState with the service across the call to fork(). Both the static
1198 // libraries and libbinder.so have their own separate copies of all the
1199 // globals, so the test only works when the test client and service both use
1200 // libbinder.so (when using static libraries, even a client and service
1201 // using the same kind of static library should have separate copies of the
1202 // variables).
1203 if (!kEnableSharedLibs || singleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001204 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1205 "at build time.";
1206 }
1207
Steven Moreland4313d7e2021-07-15 23:41:22 +00001208 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001209
Andrei Homescu2a298012022-06-15 01:08:54 +00001210 // we can't allocate IPCThreadState so actually the first time should
1211 // succeed :(
1212 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001213
1214 // second time! we catch the error :)
1215 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1216
Frederick Maylea12b0962022-06-25 01:13:22 +00001217 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1218 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1219 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1220 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001221 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001222}
1223
Frederick Mayle69a0c992022-05-26 20:38:39 +00001224TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1225 auto proc = createRpcTestSocketServerProcess({
1226 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1227 .serverSupportedFileDescriptorTransportModes =
1228 {RpcSession::FileDescriptorTransportMode::UNIX},
1229 .allowConnectFailure = true,
1230 });
1231 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1232 proc.proc.host.terminate();
1233 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1234 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1235 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1236 });
1237 proc.expectAlreadyShutdown = true;
1238}
1239
1240TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1241 auto proc = createRpcTestSocketServerProcess({
1242 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1243 .serverSupportedFileDescriptorTransportModes =
1244 {RpcSession::FileDescriptorTransportMode::NONE},
1245 .allowConnectFailure = true,
1246 });
1247 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1248 proc.proc.host.terminate();
1249 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1250 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1251 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1252 });
1253 proc.expectAlreadyShutdown = true;
1254}
1255
1256TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1257 auto proc = createRpcTestSocketServerProcess({
1258 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1259 .serverSupportedFileDescriptorTransportModes =
1260 {RpcSession::FileDescriptorTransportMode::NONE,
1261 RpcSession::FileDescriptorTransportMode::UNIX},
1262 });
1263
1264 android::os::ParcelFileDescriptor out;
1265 auto status = proc.rootIface->echoAsFile("hello", &out);
1266 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1267}
1268
1269TEST_P(BinderRpc, ReceiveFile) {
1270 auto proc = createRpcTestSocketServerProcess({
1271 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1272 .serverSupportedFileDescriptorTransportModes =
1273 {RpcSession::FileDescriptorTransportMode::UNIX},
1274 });
1275
1276 android::os::ParcelFileDescriptor out;
1277 auto status = proc.rootIface->echoAsFile("hello", &out);
1278 if (!supportsFdTransport()) {
1279 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1280 return;
1281 }
1282 ASSERT_TRUE(status.isOk()) << status;
1283
1284 std::string result;
1285 CHECK(android::base::ReadFdToString(out.get(), &result));
1286 EXPECT_EQ(result, "hello");
1287}
1288
1289TEST_P(BinderRpc, SendFiles) {
1290 auto proc = createRpcTestSocketServerProcess({
1291 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1292 .serverSupportedFileDescriptorTransportModes =
1293 {RpcSession::FileDescriptorTransportMode::UNIX},
1294 });
1295
1296 std::vector<android::os::ParcelFileDescriptor> files;
1297 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1298 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1299 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1300 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1301
1302 android::os::ParcelFileDescriptor out;
1303 auto status = proc.rootIface->concatFiles(files, &out);
1304 if (!supportsFdTransport()) {
1305 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1306 return;
1307 }
1308 ASSERT_TRUE(status.isOk()) << status;
1309
1310 std::string result;
1311 CHECK(android::base::ReadFdToString(out.get(), &result));
1312 EXPECT_EQ(result, "123abcd");
1313}
1314
1315TEST_P(BinderRpc, SendMaxFiles) {
1316 if (!supportsFdTransport()) {
1317 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1318 }
1319
1320 auto proc = createRpcTestSocketServerProcess({
1321 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1322 .serverSupportedFileDescriptorTransportModes =
1323 {RpcSession::FileDescriptorTransportMode::UNIX},
1324 });
1325
1326 std::vector<android::os::ParcelFileDescriptor> files;
1327 for (int i = 0; i < 253; i++) {
1328 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1329 }
1330
1331 android::os::ParcelFileDescriptor out;
1332 auto status = proc.rootIface->concatFiles(files, &out);
1333 ASSERT_TRUE(status.isOk()) << status;
1334
1335 std::string result;
1336 CHECK(android::base::ReadFdToString(out.get(), &result));
1337 EXPECT_EQ(result, std::string(253, 'a'));
1338}
1339
1340TEST_P(BinderRpc, SendTooManyFiles) {
1341 if (!supportsFdTransport()) {
1342 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1343 }
1344
1345 auto proc = createRpcTestSocketServerProcess({
1346 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1347 .serverSupportedFileDescriptorTransportModes =
1348 {RpcSession::FileDescriptorTransportMode::UNIX},
1349 });
1350
1351 std::vector<android::os::ParcelFileDescriptor> files;
1352 for (int i = 0; i < 254; i++) {
1353 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1354 }
1355
1356 android::os::ParcelFileDescriptor out;
1357 auto status = proc.rootIface->concatFiles(files, &out);
1358 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1359}
1360
Steven Moreland37aff182021-03-26 02:04:16 +00001361TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001362 if constexpr (!kEnableSharedLibs) {
1363 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1364 }
1365
Steven Moreland4313d7e2021-07-15 23:41:22 +00001366 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001367
1368 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1369 ASSERT_NE(binder, nullptr);
1370
1371 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1372}
1373
1374TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001375 if constexpr (!kEnableSharedLibs) {
1376 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1377 }
1378
Steven Moreland4313d7e2021-07-15 23:41:22 +00001379 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001380
1381 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1382 ASSERT_NE(binder, nullptr);
1383
1384 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1385 ASSERT_NE(ndkBinder, nullptr);
1386
1387 std::string out;
1388 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1389 ASSERT_TRUE(status.isOk()) << status.getDescription();
1390 ASSERT_EQ("aoeuaoeu", out);
1391}
1392
Steven Moreland5553ac42020-11-11 02:14:45 +00001393ssize_t countFds() {
1394 DIR* dir = opendir("/proc/self/fd/");
1395 if (dir == nullptr) return -1;
1396 ssize_t ret = 0;
1397 dirent* ent;
1398 while ((ent = readdir(dir)) != nullptr) ret++;
1399 closedir(dir);
1400 return ret;
1401}
1402
Andrei Homescu12106de2022-04-27 04:42:21 +00001403TEST_P(BinderRpcThreads, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001404 ssize_t beforeFds = countFds();
1405 ASSERT_GE(beforeFds, 0);
1406 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001407 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001408 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1409 }
1410 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1411}
1412
Devin Moore800b2252021-10-15 16:22:57 +00001413TEST_P(BinderRpc, AidlDelegatorTest) {
1414 auto proc = createRpcTestSocketServerProcess({});
1415 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1416 ASSERT_NE(nullptr, myDelegator);
1417
1418 std::string doubled;
1419 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1420 EXPECT_EQ("cool cool ", doubled);
1421}
1422
Steven Morelandda573042021-06-12 01:13:45 +00001423static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001424 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001425 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001426
Andrei Homescu992a4052022-06-28 21:26:18 +00001427 android::base::unique_fd serverFd(
1428 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1429 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1430
1431 sockaddr_vm serverAddr{
1432 .svm_family = AF_VSOCK,
1433 .svm_port = vsockPort,
1434 .svm_cid = VMADDR_CID_ANY,
1435 };
1436 int ret = TEMP_FAILURE_RETRY(
1437 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1438 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1439 strerror(errno));
1440
1441 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1442 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1443 strerror(errno));
1444
1445 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1446 // to see if the kernel supports it. It's safe to use a blocking
1447 // connect because vsock sockets have a 2 second connection timeout,
1448 // and they return ETIMEDOUT after that.
1449 android::base::unique_fd connectFd(
1450 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1451 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1452 strerror(errno));
1453
1454 bool success = false;
1455 sockaddr_vm connectAddr{
1456 .svm_family = AF_VSOCK,
1457 .svm_port = vsockPort,
1458 .svm_cid = VMADDR_CID_LOCAL,
1459 };
1460 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1461 sizeof(connectAddr)));
1462 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1463 android::base::unique_fd acceptFd;
1464 while (true) {
1465 pollfd pfd[]{
1466 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1467 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1468 };
1469 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1470 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1471
1472 if (pfd[0].revents & POLLIN) {
1473 sockaddr_vm acceptAddr;
1474 socklen_t acceptAddrLen = sizeof(acceptAddr);
1475 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1476 reinterpret_cast<sockaddr*>(&acceptAddr),
1477 &acceptAddrLen, SOCK_CLOEXEC));
1478 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1479 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1480 "Truncated address");
1481
1482 // Store the fd in acceptFd so we keep the connection alive
1483 // while polling connectFd
1484 acceptFd.reset(ret);
1485 }
1486
1487 if (pfd[1].revents & POLLOUT) {
1488 // Connect either succeeded or timed out
1489 int connectErrno;
1490 socklen_t connectErrnoLen = sizeof(connectErrno);
1491 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1492 &connectErrnoLen);
1493 LOG_ALWAYS_FATAL_IF(ret == -1,
1494 "Could not getsockopt() after connect() "
1495 "on non-blocking socket: %s.",
1496 strerror(errno));
1497
1498 // We're done, this is all we wanted
1499 success = connectErrno == 0;
1500 break;
1501 }
1502 }
1503 } else {
1504 success = ret == 0;
1505 }
1506
1507 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1508
1509 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001510}
1511
Yifan Hong1deca4b2021-09-10 16:16:44 -07001512static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1513 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1514
1515 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001516
1517 static bool hasVsockLoopback = testSupportVsockLoopback();
1518
1519 if (hasVsockLoopback) {
1520 ret.push_back(SocketType::VSOCK);
1521 }
1522
1523 return ret;
1524}
1525
Frederick Mayledc07cf82022-05-26 20:30:12 +00001526static std::vector<uint32_t> testVersions() {
1527 std::vector<uint32_t> versions;
1528 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1529 versions.push_back(i);
1530 }
1531 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1532 return versions;
1533}
1534
Yifan Hong702115c2021-06-24 15:39:18 -07001535INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1536 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001537 ::testing::ValuesIn(RpcSecurityValues()),
1538 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001539 ::testing::ValuesIn(testVersions()),
1540 ::testing::Values(false, true),
1541 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001542 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001543
Andrei Homescu12106de2022-04-27 04:42:21 +00001544INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpcThreads,
1545 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1546 ::testing::ValuesIn(RpcSecurityValues()),
1547 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001548 ::testing::ValuesIn(testVersions()),
1549 ::testing::Values(false),
1550 ::testing::Values(false, true)),
Andrei Homescu12106de2022-04-27 04:42:21 +00001551 BinderRpc::PrintParamInfo);
1552
Yifan Hong702115c2021-06-24 15:39:18 -07001553class BinderRpcServerRootObject
1554 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001555
1556TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1557 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1558 auto setRootObject = [](bool isStrong) -> SetFn {
1559 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1560 };
1561
Yifan Hong702115c2021-06-24 15:39:18 -07001562 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1563 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001564 auto binder1 = sp<BBinder>::make();
1565 IBinder* binderRaw1 = binder1.get();
1566 setRootObject(isStrong1)(server.get(), binder1);
1567 EXPECT_EQ(binderRaw1, server->getRootObject());
1568 binder1.clear();
1569 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1570
1571 auto binder2 = sp<BBinder>::make();
1572 IBinder* binderRaw2 = binder2.get();
1573 setRootObject(isStrong2)(server.get(), binder2);
1574 EXPECT_EQ(binderRaw2, server->getRootObject());
1575 binder2.clear();
1576 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1577}
1578
1579INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001580 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1581 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001582
Yifan Hong1a235852021-05-13 16:07:47 -07001583class OneOffSignal {
1584public:
1585 // If notify() was previously called, or is called within |duration|, return true; else false.
1586 template <typename R, typename P>
1587 bool wait(std::chrono::duration<R, P> duration) {
1588 std::unique_lock<std::mutex> lock(mMutex);
1589 return mCv.wait_for(lock, duration, [this] { return mValue; });
1590 }
1591 void notify() {
1592 std::unique_lock<std::mutex> lock(mMutex);
1593 mValue = true;
1594 lock.unlock();
1595 mCv.notify_all();
1596 }
1597
1598private:
1599 std::mutex mMutex;
1600 std::condition_variable mCv;
1601 bool mValue = false;
1602};
1603
Frederick Mayledc07cf82022-05-26 20:30:12 +00001604TEST_P(BinderRpcServerOnly, Shutdown) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001605 if constexpr (!kEnableRpcThreads) {
1606 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1607 }
1608
Yifan Hong1a235852021-05-13 16:07:47 -07001609 auto addr = allocateSocketAddress();
Frederick Mayledc07cf82022-05-26 20:30:12 +00001610 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1611 server->setProtocolVersion(std::get<1>(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001612 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001613 auto joinEnds = std::make_shared<OneOffSignal>();
1614
1615 // If things are broken and the thread never stops, don't block other tests. Because the thread
1616 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1617 // shared pointers are passed.
1618 std::thread([server, joinEnds] {
1619 server->join();
1620 joinEnds->notify();
1621 }).detach();
1622
1623 bool shutdown = false;
1624 for (int i = 0; i < 10 && !shutdown; i++) {
1625 usleep(300 * 1000); // 300ms; total 3s
1626 if (server->shutdown()) shutdown = true;
1627 }
1628 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1629
1630 ASSERT_TRUE(joinEnds->wait(2s))
1631 << "After server->shutdown() returns true, join() did not stop after 2s";
1632}
1633
Yifan Hong194acf22021-06-29 18:44:56 -07001634TEST(BinderRpc, Java) {
1635#if !defined(__ANDROID__)
1636 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1637 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1638 "to binderHostDeviceTest. Hence, just disable this test on host.";
1639#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001640 if constexpr (!kEnableKernelIpc) {
1641 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1642 "at build time.";
1643 }
1644
Yifan Hong194acf22021-06-29 18:44:56 -07001645 sp<IServiceManager> sm = defaultServiceManager();
1646 ASSERT_NE(nullptr, sm);
1647 // Any Java service with non-empty getInterfaceDescriptor() would do.
1648 // Let's pick batteryproperties.
1649 auto binder = sm->checkService(String16("batteryproperties"));
1650 ASSERT_NE(nullptr, binder);
1651 auto descriptor = binder->getInterfaceDescriptor();
1652 ASSERT_GE(descriptor.size(), 0);
1653 ASSERT_EQ(OK, binder->pingBinder());
1654
1655 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001656 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001657 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001658 auto socket = rpcServer->releaseServer();
1659
1660 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001661 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1662
Yifan Honge3caaf22022-01-12 14:46:56 -08001663 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1664 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001665 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001666 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1667 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001668 << statusToString(setRpcClientDebugStatus);
1669 GTEST_SKIP();
1670 }
1671
1672 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001673
1674 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001675 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001676 auto rpcBinder = rpcSession->getRootObject();
1677 ASSERT_NE(nullptr, rpcBinder);
1678
1679 ASSERT_EQ(OK, rpcBinder->pingBinder());
1680
1681 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1682 << "getInterfaceDescriptor should not crash system_server";
1683 ASSERT_EQ(OK, rpcBinder->pingBinder());
1684}
1685
Frederick Mayledc07cf82022-05-26 20:30:12 +00001686INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1687 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1688 ::testing::ValuesIn(testVersions())),
1689 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001690
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001691class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001692public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001693 // Only parameterized only server version because `RpcSession` is bypassed
1694 // in the client half of the tests.
1695 using Param =
1696 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001697 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001698
1699 // A server that handles client socket connections.
1700 class Server {
1701 public:
1702 explicit Server() {}
1703 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001704 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001705 [[nodiscard]] AssertionResult setUp(
1706 const Param& param,
1707 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001708 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001709 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001710 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001711 switch (socketType) {
1712 case SocketType::PRECONNECTED: {
1713 return AssertionFailure() << "Not supported by this test";
1714 } break;
1715 case SocketType::UNIX: {
1716 auto addr = allocateSocketAddress();
1717 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1718 if (status != OK) {
1719 return AssertionFailure()
1720 << "setupUnixDomainServer: " << statusToString(status);
1721 }
1722 mConnectToServer = [addr] {
1723 return connectTo(UnixSocketAddress(addr.c_str()));
1724 };
1725 } break;
1726 case SocketType::VSOCK: {
1727 auto port = allocateVsockPort();
1728 auto status = rpcServer->setupVsockServer(port);
1729 if (status != OK) {
1730 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1731 }
1732 mConnectToServer = [port] {
1733 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1734 };
1735 } break;
1736 case SocketType::INET: {
1737 unsigned int port;
1738 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1739 if (status != OK) {
1740 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1741 }
1742 mConnectToServer = [port] {
1743 const char* addr = kLocalInetAddress;
1744 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1745 if (aiStart == nullptr) return base::unique_fd{};
1746 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1747 auto fd = connectTo(
1748 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1749 if (fd.ok()) return fd;
1750 }
1751 ALOGE("None of the socket address resolved for %s:%u can be connected",
1752 addr, port);
1753 return base::unique_fd{};
1754 };
1755 }
1756 }
1757 mFd = rpcServer->releaseServer();
1758 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001759 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001760 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1761 mSetup = true;
1762 return AssertionSuccess();
1763 }
1764 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1765 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1766 return mCertVerifier;
1767 }
1768 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1769 void start() {
1770 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1771 mThread = std::make_unique<std::thread>(&Server::run, this);
1772 }
1773 void run() {
1774 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1775
1776 std::vector<std::thread> threads;
1777 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1778 base::unique_fd acceptedFd(
1779 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1780 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1781 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1782 }
1783
1784 for (auto& thread : threads) thread.join();
1785 }
1786 void handleOne(android::base::unique_fd acceptedFd) {
1787 ASSERT_TRUE(acceptedFd.ok());
1788 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1789 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001790 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001791 }
Yifan Honge07d2732021-09-13 21:59:14 -07001792 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001793 shutdown();
1794 join();
1795 }
1796 void shutdown() { mFdTrigger->trigger(); }
1797
1798 void setPostConnect(
1799 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1800 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001801 }
1802
1803 private:
1804 std::unique_ptr<std::thread> mThread;
1805 ConnectToServer mConnectToServer;
1806 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1807 base::unique_fd mFd;
1808 std::unique_ptr<RpcTransportCtx> mCtx;
1809 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1810 std::make_shared<RpcCertificateVerifierSimple>();
1811 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001812 // The function invoked after connection and handshake. By default, it is
1813 // |defaultPostConnect| that sends |kMessage| to the client.
1814 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1815 Server::defaultPostConnect;
1816
1817 void join() {
1818 if (mThread != nullptr) {
1819 mThread->join();
1820 mThread = nullptr;
1821 }
1822 }
1823
1824 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1825 FdTrigger* fdTrigger) {
1826 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001827 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001828 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001829 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001830 if (status != OK) return AssertionFailure() << statusToString(status);
1831 return AssertionSuccess();
1832 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001833 };
1834
1835 class Client {
1836 public:
1837 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1838 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001839 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001840 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1841 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001842 mFdTrigger = FdTrigger::make();
1843 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1844 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1845 return AssertionSuccess();
1846 }
1847 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1848 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1849 return mCertVerifier;
1850 }
Yifan Hong67519322021-09-13 18:51:16 -07001851 // connect() and do handshake
1852 bool setUpTransport() {
1853 mFd = mConnectToServer();
1854 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1855 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1856 return mClientTransport != nullptr;
1857 }
1858 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1859 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1860 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001861 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001862 status_t readStatus =
1863 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001864 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001865 if (readStatus != OK) {
1866 return AssertionFailure() << statusToString(readStatus);
1867 }
1868 if (readMessage != expectedMessage) {
1869 return AssertionFailure()
1870 << "Expected " << expectedMessage << ", actual " << readMessage;
1871 }
1872 return AssertionSuccess();
1873 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001874 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001875 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001876 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1877 return;
1878 }
1879 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001880 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001881 }
1882
1883 private:
1884 ConnectToServer mConnectToServer;
1885 base::unique_fd mFd;
1886 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1887 std::unique_ptr<RpcTransportCtx> mCtx;
1888 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1889 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001890 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001891 };
1892
1893 // Make A trust B.
1894 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001895 static status_t trust(RpcSecurity rpcSecurity,
1896 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1897 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001898 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001899 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1900 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1901 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001902 }
1903
1904 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001905};
1906
1907class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1908public:
1909 using Server = RpcTransportTestUtils::Server;
1910 using Client = RpcTransportTestUtils::Client;
1911 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001912 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001913 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1914 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001915 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001916 return ret;
1917 }
1918 static std::vector<ParamType> getRpcTranportTestParams() {
1919 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001920 for (auto serverVersion : testVersions()) {
1921 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1922 for (auto rpcSecurity : RpcSecurityValues()) {
1923 switch (rpcSecurity) {
1924 case RpcSecurity::RAW: {
1925 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1926 } break;
1927 case RpcSecurity::TLS: {
1928 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1929 serverVersion);
1930 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1931 serverVersion);
1932 } break;
1933 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001934 }
1935 }
1936 }
1937 return ret;
1938 }
1939 template <typename A, typename B>
1940 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001941 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1942 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001943 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1944 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001945 void SetUp() override {
1946 if constexpr (!kEnableRpcThreads) {
1947 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1948 }
1949 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001950};
1951
1952TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001953 auto server = std::make_unique<Server>();
1954 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001955
1956 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001957 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001958
1959 ASSERT_EQ(OK, trust(&client, server));
1960 ASSERT_EQ(OK, trust(server, &client));
1961
1962 server->start();
1963 client.run();
1964}
1965
1966TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001967 auto server = std::make_unique<Server>();
1968 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001969
1970 std::vector<Client> clients;
1971 for (int i = 0; i < 2; i++) {
1972 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001973 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001974 ASSERT_EQ(OK, trust(&client, server));
1975 ASSERT_EQ(OK, trust(server, &client));
1976 }
1977
1978 server->start();
1979 for (auto& client : clients) client.run();
1980}
1981
1982TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001983 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1984 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001985
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001986 auto untrustedServer = std::make_unique<Server>();
1987 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001988
1989 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001990 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001991
1992 ASSERT_EQ(OK, trust(untrustedServer, &client));
1993
1994 untrustedServer->start();
1995
1996 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1997 // the client can't verify the server's identity.
1998 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1999 client.run(handshakeOk);
2000}
2001TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002002 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2003 (void)serverVersion;
2004
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002005 auto validServer = std::make_unique<Server>();
2006 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002007
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002008 auto maliciousServer = std::make_unique<Server>();
2009 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002010
2011 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002012 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002013
2014 ASSERT_EQ(OK, trust(&client, validServer));
2015 ASSERT_EQ(OK, trust(validServer, &client));
2016 ASSERT_EQ(OK, trust(maliciousServer, &client));
2017
2018 maliciousServer->start();
2019
2020 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2021 // the client can't verify the server's identity.
2022 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2023 client.run(handshakeOk);
2024}
2025
2026TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002027 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2028 (void)serverVersion;
2029
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002030 auto server = std::make_unique<Server>();
2031 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002032
2033 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002034 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002035
2036 ASSERT_EQ(OK, trust(&client, server));
2037
2038 server->start();
2039
2040 // For TLS, Client should be able to verify server's identity, so client should see
2041 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2042 // identity and should drop the connection, so client shouldn't be able to read anything.
2043 bool readOk = rpcSecurity != RpcSecurity::TLS;
2044 client.run(true, readOk);
2045}
2046
2047TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002048 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2049 (void)serverVersion;
2050
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002051 auto server = std::make_unique<Server>();
2052 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002053
2054 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002055 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002056 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002057 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002058
2059 ASSERT_EQ(OK, trust(&validClient, server));
2060 ASSERT_EQ(OK, trust(&maliciousClient, server));
2061
2062 server->start();
2063
2064 // See UntrustedClient.
2065 bool readOk = rpcSecurity != RpcSecurity::TLS;
2066 maliciousClient.run(true, readOk);
2067}
2068
Yifan Hong67519322021-09-13 18:51:16 -07002069TEST_P(RpcTransportTest, Trigger) {
2070 std::string msg2 = ", world!";
2071 std::mutex writeMutex;
2072 std::condition_variable writeCv;
2073 bool shouldContinueWriting = false;
2074 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002075 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002076 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002077 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2078 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002079 if (status != OK) return AssertionFailure() << statusToString(status);
2080
2081 {
2082 std::unique_lock<std::mutex> lock(writeMutex);
2083 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2084 return AssertionFailure() << "write barrier not cleared in time!";
2085 }
2086 }
2087
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002088 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002089 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2090 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002091 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002092 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002093 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002094 << statusToString(status);
2095 return AssertionSuccess();
2096 };
2097
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002098 auto server = std::make_unique<Server>();
2099 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002100
2101 // Set up client
2102 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002103 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002104
2105 // Exchange keys
2106 ASSERT_EQ(OK, trust(&client, server));
2107 ASSERT_EQ(OK, trust(server, &client));
2108
2109 server->setPostConnect(serverPostConnect);
2110
Yifan Hong67519322021-09-13 18:51:16 -07002111 server->start();
2112 // connect() to server and do handshake
2113 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002114 // read the first message. This ensures that server has finished handshake and start handling
2115 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002116 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002117 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2118 // write is on an FdTrigger that has been shut down.
2119 server->shutdown();
2120 // Continues server thread to write the second message.
2121 {
Yifan Hong22211f82021-09-14 12:32:25 -07002122 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002123 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002124 }
Yifan Hong22211f82021-09-14 12:32:25 -07002125 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002126 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002127 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002128 // On the client side, second read fails with DEAD_OBJECT
2129 ASSERT_FALSE(client.readMessage(msg2));
2130}
2131
Yifan Hong1deca4b2021-09-10 16:16:44 -07002132INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002133 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002134 RpcTransportTest::PrintParamInfo);
2135
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002136class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002137 : public testing::TestWithParam<
2138 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002139public:
2140 template <typename A, typename B>
2141 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002142 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2143 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002144 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2145 }
2146 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002147 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2148 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2149 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002150 };
2151};
2152
2153TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002154 if constexpr (!kEnableRpcThreads) {
2155 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2156 }
2157
Frederick Mayledc07cf82022-05-26 20:30:12 +00002158 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002159
2160 std::vector<uint8_t> pkeyData, certData;
2161 {
2162 auto pkey = makeKeyPairForSelfSignedCert();
2163 ASSERT_NE(nullptr, pkey);
2164 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2165 ASSERT_NE(nullptr, cert);
2166 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2167 certData = serializeCertificate(cert.get(), certificateFormat);
2168 }
2169
2170 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2171 auto desCert = deserializeCertificate(certData, certificateFormat);
2172 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002173 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2174 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002175
2176 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2177 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2178
2179 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2180 ASSERT_TRUE(client.setUp(utilsParam));
2181
2182 ASSERT_EQ(OK, trust(&client, server));
2183 ASSERT_EQ(OK, trust(server, &client));
2184
2185 server->start();
2186 client.run();
2187}
2188
2189INSTANTIATE_TEST_CASE_P(
2190 BinderRpc, RpcTransportTlsKeyTest,
2191 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2192 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002193 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2194 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002195 RpcTransportTlsKeyTest::PrintParamInfo);
2196
Steven Morelandc1635952021-04-01 16:20:47 +00002197} // namespace android
2198
2199int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002200 ::testing::InitGoogleTest(&argc, argv);
2201 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002202
Steven Moreland5553ac42020-11-11 02:14:45 +00002203 return RUN_ALL_TESTS();
2204}