blob: 0ee15a1498eefeb4cc6492b38aeb74120109c111 [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 Homescua858b0e2022-08-01 23:43:09 +0000267 bool serverSingleThreaded() const { return std::get<4>(GetParam()); }
Andrei Homescu2a298012022-06-15 01:08:54 +0000268 bool noKernel() const { return std::get<5>(GetParam()); }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000269
Andrei Homescua858b0e2022-08-01 23:43:09 +0000270 bool clientOrServerSingleThreaded() const {
271 return !kEnableRpcThreads || serverSingleThreaded();
272 }
273
Frederick Mayle69a0c992022-05-26 20:38:39 +0000274 // Whether the test params support sending FDs in parcels.
275 bool supportsFdTransport() const {
276 return clientVersion() >= 1 && serverVersion() >= 1 && rpcSecurity() != RpcSecurity::TLS &&
277 (socketType() == SocketType::PRECONNECTED || socketType() == SocketType::UNIX);
278 }
279
Yifan Hong702115c2021-06-24 15:39:18 -0700280 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000281 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
282 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
Frederick Mayledc07cf82022-05-26 20:30:12 +0000283 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Andrei Homescu2a298012022-06-15 01:08:54 +0000284 if (singleThreaded) {
285 ret += "_single_threaded";
286 }
287 if (noKernel) {
288 ret += "_no_kernel";
289 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700290 return ret;
291 }
292
Steven Morelandc1635952021-04-01 16:20:47 +0000293 // This creates a new process serving an interface on a certain number of
294 // threads.
Andrei Homescu2a298012022-06-15 01:08:54 +0000295 ProcessSession createRpcTestSocketServerProcessEtc(const BinderRpcOptions& options) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000296 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000297
Yifan Hong702115c2021-06-24 15:39:18 -0700298 SocketType socketType = std::get<0>(GetParam());
299 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000300 uint32_t clientVersion = std::get<2>(GetParam());
301 uint32_t serverVersion = std::get<3>(GetParam());
Andrei Homescu2a298012022-06-15 01:08:54 +0000302 bool singleThreaded = std::get<4>(GetParam());
303 bool noKernel = std::get<5>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000304
Andrei Homescu2a298012022-06-15 01:08:54 +0000305 std::string path = android::base::GetExecutableDirectory();
306 auto servicePath =
307 android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
308 singleThreaded ? "_single_threaded" : "",
309 noKernel ? "_no_kernel" : "");
Steven Morelandc1635952021-04-01 16:20:47 +0000310
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000311 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000312 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700313 android::base::borrowed_fd readEnd) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000314 auto writeFd = std::to_string(writeEnd.get());
315 auto readFd = std::to_string(readEnd.get());
316 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
317 NULL);
Steven Morelandc1635952021-04-01 16:20:47 +0000318 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000319 };
320
Andrei Homescu2a298012022-06-15 01:08:54 +0000321 BinderRpcTestServerConfig serverConfig;
322 serverConfig.numThreads = options.numThreads;
323 serverConfig.socketType = static_cast<int32_t>(socketType);
324 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
325 serverConfig.serverVersion = serverVersion;
326 serverConfig.vsockPort = allocateVsockPort();
327 serverConfig.addr = allocateSocketAddress();
328 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
329 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
330 static_cast<int32_t>(mode));
331 }
332 writeToFd(ret.host.writeEnd(), serverConfig);
333
Yifan Hong1deca4b2021-09-10 16:16:44 -0700334 std::vector<sp<RpcSession>> sessions;
335 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
336 for (size_t i = 0; i < options.numSessions; i++) {
337 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
338 }
339
340 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
341 BinderRpcTestClientInfo clientInfo;
342 for (const auto& session : sessions) {
343 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700344 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700345 }
346 writeToFd(ret.host.writeEnd(), clientInfo);
347
348 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700349 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700350 CHECK_NE(0, serverInfo.port);
351 }
352
353 if (rpcSecurity == RpcSecurity::TLS) {
354 const auto& serverCert = serverInfo.cert.data;
355 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700356 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
357 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700358 }
359
Steven Moreland2372f9d2021-08-05 15:42:01 -0700360 status_t status;
361
Yifan Hong1deca4b2021-09-10 16:16:44 -0700362 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000363 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700364 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700365 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000366 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Moreland659416d2021-05-11 00:47:50 +0000367
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000368 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700369 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700370 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000371 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700372 });
Steven Moreland4198a122021-08-03 17:37:58 -0700373 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000374 case SocketType::UNIX:
Andrei Homescu2a298012022-06-15 01:08:54 +0000375 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000376 break;
377 case SocketType::VSOCK:
Andrei Homescu2a298012022-06-15 01:08:54 +0000378 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000379 break;
380 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700381 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000382 break;
383 default:
384 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000385 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000386 if (options.allowConnectFailure && status != OK) {
387 ret.sessions.clear();
388 break;
389 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700390 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000391 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000392 }
Steven Morelandc1635952021-04-01 16:20:47 +0000393 return ret;
394 }
395
Andrei Homescu2a298012022-06-15 01:08:54 +0000396 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const BinderRpcOptions& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000397 BinderRpcTestProcessSession ret{
Andrei Homescu2a298012022-06-15 01:08:54 +0000398 .proc = createRpcTestSocketServerProcessEtc(options),
Steven Morelandc1635952021-04-01 16:20:47 +0000399 };
400
Frederick Mayle69a0c992022-05-26 20:38:39 +0000401 ret.rootBinder = ret.proc.sessions.empty() ? nullptr : ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000402 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
403
404 return ret;
405 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700406
407 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
408 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000409};
410
Steven Morelandc1635952021-04-01 16:20:47 +0000411TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000412 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000413 ASSERT_NE(proc.rootBinder, nullptr);
414 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
415}
416
Steven Moreland4cf688f2021-03-31 01:48:58 +0000417TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000418 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000419 ASSERT_NE(proc.rootBinder, nullptr);
420 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
421}
422
Andrei Homescua858b0e2022-08-01 23:43:09 +0000423TEST_P(BinderRpc, MultipleSessions) {
424 if (serverSingleThreaded()) {
425 // Tests with multiple sessions require a multi-threaded service,
426 // but work fine on a single-threaded client
427 GTEST_SKIP() << "This test requires a multi-threaded service";
428 }
429
Steven Moreland4313d7e2021-07-15 23:41:22 +0000430 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000431 for (auto session : proc.proc.sessions) {
432 ASSERT_NE(nullptr, session.root);
433 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000434 }
435}
436
Andrei Homescua858b0e2022-08-01 23:43:09 +0000437TEST_P(BinderRpc, SeparateRootObject) {
438 if (serverSingleThreaded()) {
439 GTEST_SKIP() << "This test requires a multi-threaded service";
440 }
441
Steven Moreland51c44a92021-10-14 16:50:35 -0700442 SocketType type = std::get<0>(GetParam());
443 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
444 // we can't get port numbers for unix sockets
445 return;
446 }
447
448 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
449
450 int port1 = 0;
451 EXPECT_OK(proc.rootIface->getClientPort(&port1));
452
453 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
454 int port2;
455 EXPECT_OK(rootIface2->getClientPort(&port2));
456
457 // we should have a different IBinderRpcTest object created for each
458 // session, because we use setPerSessionRootObject
459 EXPECT_NE(port1, port2);
460}
461
Steven Morelandc1635952021-04-01 16:20:47 +0000462TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000463 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000464 Parcel data;
465 Parcel reply;
466 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
467}
468
Steven Moreland67753c32021-04-02 18:45:19 +0000469TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700470 auto proc1 = createRpcTestSocketServerProcess({});
471 auto proc2 = createRpcTestSocketServerProcess({});
472
473 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000474
475 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700476 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000477 p1.writeInt32(3);
478
Frederick Maylea4ed5672022-06-17 22:03:38 +0000479 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700480 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
481
Steven Moreland67753c32021-04-02 18:45:19 +0000482 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700483 p2.markForBinder(proc2.rootBinder);
484 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000485
486 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
487 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
488}
489
Steven Morelandc1635952021-04-01 16:20:47 +0000490TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000491 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000492 Parcel data;
493 data.markForBinder(proc.rootBinder);
494 Parcel reply;
495 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
496}
497
Steven Morelandc1635952021-04-01 16:20:47 +0000498TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000499 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000500 EXPECT_OK(proc.rootIface->sendString("asdf"));
501}
502
Steven Morelandc1635952021-04-01 16:20:47 +0000503TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000504 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000505 std::string doubled;
506 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
507 EXPECT_EQ("cool cool ", doubled);
508}
509
Steven Morelandc1635952021-04-01 16:20:47 +0000510TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000511 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000512 std::string single = std::string(1024, 'a');
513 std::string doubled;
514 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
515 EXPECT_EQ(single + single, doubled);
516}
517
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000518TEST_P(BinderRpc, InvalidNullBinderReturn) {
519 auto proc = createRpcTestSocketServerProcess({});
520
521 sp<IBinder> outBinder;
522 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
523}
524
Steven Morelandc1635952021-04-01 16:20:47 +0000525TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000526 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000527
528 int32_t pingResult;
529 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
530 EXPECT_EQ(OK, pingResult);
531
532 EXPECT_EQ(0, MyBinderRpcSession::gNum);
533}
534
Steven Morelandc1635952021-04-01 16:20:47 +0000535TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000536 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000537
538 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
539 sp<IBinder> outBinder;
540 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
541 EXPECT_EQ(inBinder, outBinder);
542
543 wp<IBinder> weak = inBinder;
544 inBinder = nullptr;
545 outBinder = nullptr;
546
547 // Force reading a reply, to process any pending dec refs from the other
548 // process (the other process will process dec refs there before processing
549 // the ping here).
550 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
551
552 EXPECT_EQ(nullptr, weak.promote());
553
554 EXPECT_EQ(0, MyBinderRpcSession::gNum);
555}
556
Steven Morelandc1635952021-04-01 16:20:47 +0000557TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000558 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000559
560 sp<IBinderRpcSession> session;
561 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
562
563 sp<IBinder> inBinder = IInterface::asBinder(session);
564 sp<IBinder> outBinder;
565 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
566 EXPECT_EQ(inBinder, outBinder);
567
568 wp<IBinder> weak = inBinder;
569 session = nullptr;
570 inBinder = nullptr;
571 outBinder = nullptr;
572
573 // Force reading a reply, to process any pending dec refs from the other
574 // process (the other process will process dec refs there before processing
575 // the ping here).
576 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
577
578 EXPECT_EQ(nullptr, weak.promote());
579}
580
Steven Morelandc1635952021-04-01 16:20:47 +0000581TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000582 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000583
584 sp<IBinder> outBinder;
585 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
586 EXPECT_EQ(nullptr, outBinder);
587}
588
Steven Morelandc1635952021-04-01 16:20:47 +0000589TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000590 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000591
592 IBinder* ptr = nullptr;
593 {
594 sp<IBinder> binder = new BBinder();
595 ptr = binder.get();
596 EXPECT_OK(proc.rootIface->holdBinder(binder));
597 }
598
599 sp<IBinder> held;
600 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
601
602 EXPECT_EQ(held.get(), ptr);
603
604 // stop holding binder, because we test to make sure references are cleaned
605 // up
606 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
607 // and flush ref counts
608 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
609}
610
611// START TESTS FOR LIMITATIONS OF SOCKET BINDER
612// These are behavioral differences form regular binder, where certain usecases
613// aren't supported.
614
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000615TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000616 auto proc1 = createRpcTestSocketServerProcess({});
617 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000618
619 sp<IBinder> outBinder;
620 EXPECT_EQ(INVALID_OPERATION,
621 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
622}
623
Andrei Homescua858b0e2022-08-01 23:43:09 +0000624TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
625 if (serverSingleThreaded()) {
626 GTEST_SKIP() << "This test requires a multi-threaded service";
627 }
628
Steven Moreland4313d7e2021-07-15 23:41:22 +0000629 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000630
631 sp<IBinder> outBinder;
632 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000633 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000634 .transactionError());
635}
636
Steven Morelandc1635952021-04-01 16:20:47 +0000637TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000638 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000639 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
640 "at build time.";
641 }
642
Steven Moreland4313d7e2021-07-15 23:41:22 +0000643 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000644
645 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
646 sp<IBinder> outBinder;
647 EXPECT_EQ(INVALID_OPERATION,
648 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
649}
650
Steven Morelandc1635952021-04-01 16:20:47 +0000651TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000652 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000653 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
654 "at build time.";
655 }
656
Steven Moreland4313d7e2021-07-15 23:41:22 +0000657 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000658
659 // for historical reasons, IServiceManager interface only returns the
660 // exception code
661 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
662 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
663}
664
665// END TESTS FOR LIMITATIONS OF SOCKET BINDER
666
Steven Morelandc1635952021-04-01 16:20:47 +0000667TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000668 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000669
670 sp<IBinder> outBinder;
671 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
672 EXPECT_EQ(proc.rootBinder, outBinder);
673}
674
Steven Morelandc1635952021-04-01 16:20:47 +0000675TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000676 auto proc = createRpcTestSocketServerProcess({
677 // Enable FD support because it uses more stack space and so represents
678 // something closer to a worst case scenario.
679 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
680 .serverSupportedFileDescriptorTransportModes =
681 {RpcSession::FileDescriptorTransportMode::UNIX},
682 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000683
684 auto nastyNester = sp<MyBinderRpcTest>::make();
685 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
686
687 wp<IBinder> weak = nastyNester;
688 nastyNester = nullptr;
689 EXPECT_EQ(nullptr, weak.promote());
690}
691
Steven Morelandc1635952021-04-01 16:20:47 +0000692TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000693 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000694
695 sp<IBinder> a;
696 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
697
698 sp<IBinder> b;
699 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
700
701 EXPECT_EQ(a, b);
702}
703
Steven Morelandc1635952021-04-01 16:20:47 +0000704TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000705 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000706
707 sp<IBinder> a;
708 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
709 wp<IBinder> weak = a;
710 a = nullptr;
711
712 sp<IBinder> b;
713 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
714
715 // this is the wrong behavior, since BpBinder
716 // doesn't implement onIncStrongAttempted
717 // but make sure there is no crash
718 EXPECT_EQ(nullptr, weak.promote());
719
720 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
721
722 // In order to fix this:
723 // - need to have incStrongAttempted reflected across IPC boundary (wait for
724 // response to promote - round trip...)
725 // - sendOnLastWeakRef, to delete entries out of RpcState table
726 EXPECT_EQ(b, weak.promote());
727}
728
729#define expectSessions(expected, iface) \
730 do { \
731 int session; \
732 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
733 EXPECT_EQ(expected, session); \
734 } while (false)
735
Steven Morelandc1635952021-04-01 16:20:47 +0000736TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000737 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000738
739 sp<IBinderRpcSession> session;
740 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
741 std::string out;
742 EXPECT_OK(session->getName(&out));
743 EXPECT_EQ("aoeu", out);
744
745 expectSessions(1, proc.rootIface);
746 session = nullptr;
747 expectSessions(0, proc.rootIface);
748}
749
Steven Morelandc1635952021-04-01 16:20:47 +0000750TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000751 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000752
753 std::vector<sp<IBinderRpcSession>> sessions;
754
755 for (size_t i = 0; i < 15; i++) {
756 expectSessions(i, proc.rootIface);
757 sp<IBinderRpcSession> session;
758 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
759 sessions.push_back(session);
760 }
761 expectSessions(sessions.size(), proc.rootIface);
762 for (size_t i = 0; i < sessions.size(); i++) {
763 std::string out;
764 EXPECT_OK(sessions.at(i)->getName(&out));
765 EXPECT_EQ(std::to_string(i), out);
766 }
767 expectSessions(sessions.size(), proc.rootIface);
768
769 while (!sessions.empty()) {
770 sessions.pop_back();
771 expectSessions(sessions.size(), proc.rootIface);
772 }
773 expectSessions(0, proc.rootIface);
774}
775
776size_t epochMillis() {
777 using std::chrono::duration_cast;
778 using std::chrono::milliseconds;
779 using std::chrono::seconds;
780 using std::chrono::system_clock;
781 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
782}
783
Andrei Homescua858b0e2022-08-01 23:43:09 +0000784TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
785 if (clientOrServerSingleThreaded()) {
786 GTEST_SKIP() << "This test requires multiple threads";
787 }
788
Steven Moreland5553ac42020-11-11 02:14:45 +0000789 constexpr size_t kNumThreads = 10;
790
Steven Moreland4313d7e2021-07-15 23:41:22 +0000791 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000792
793 EXPECT_OK(proc.rootIface->lock());
794
795 // block all but one thread taking locks
796 std::vector<std::thread> ts;
797 for (size_t i = 0; i < kNumThreads - 1; i++) {
798 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
799 }
800
801 usleep(100000); // give chance for calls on other threads
802
803 // other calls still work
804 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
805
806 constexpr size_t blockTimeMs = 500;
807 size_t epochMsBefore = epochMillis();
808 // after this, we should never see a response within this time
809 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
810
811 // this call should be blocked for blockTimeMs
812 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
813
814 size_t epochMsAfter = epochMillis();
815 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
816
817 for (auto& t : ts) t.join();
818}
819
Yifan Hong1f44f982021-10-08 17:16:47 -0700820void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
821 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000822 size_t epochMsBefore = epochMillis();
823
824 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700825 for (size_t i = 0; i < numCalls; i++) {
826 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000827 }
828
829 for (auto& t : ts) t.join();
830
831 size_t epochMsAfter = epochMillis();
832
Yifan Hong1f44f982021-10-08 17:16:47 -0700833 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000834
835 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700836 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
837}
838
Andrei Homescua858b0e2022-08-01 23:43:09 +0000839TEST_P(BinderRpc, ThreadPoolOverSaturated) {
840 if (clientOrServerSingleThreaded()) {
841 GTEST_SKIP() << "This test requires multiple threads";
842 }
843
Yifan Hong1f44f982021-10-08 17:16:47 -0700844 constexpr size_t kNumThreads = 10;
845 constexpr size_t kNumCalls = kNumThreads + 3;
846 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
847 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
848}
849
Andrei Homescua858b0e2022-08-01 23:43:09 +0000850TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
851 if (clientOrServerSingleThreaded()) {
852 GTEST_SKIP() << "This test requires multiple threads";
853 }
854
Yifan Hong1f44f982021-10-08 17:16:47 -0700855 constexpr size_t kNumThreads = 20;
856 constexpr size_t kNumOutgoingConnections = 10;
857 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
858 auto proc = createRpcTestSocketServerProcess(
859 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
860 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000861}
862
Andrei Homescua858b0e2022-08-01 23:43:09 +0000863TEST_P(BinderRpc, ThreadingStressTest) {
864 if (clientOrServerSingleThreaded()) {
865 GTEST_SKIP() << "This test requires multiple threads";
866 }
867
Steven Moreland5553ac42020-11-11 02:14:45 +0000868 constexpr size_t kNumClientThreads = 10;
869 constexpr size_t kNumServerThreads = 10;
870 constexpr size_t kNumCalls = 100;
871
Steven Moreland4313d7e2021-07-15 23:41:22 +0000872 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000873
874 std::vector<std::thread> threads;
875 for (size_t i = 0; i < kNumClientThreads; i++) {
876 threads.push_back(std::thread([&] {
877 for (size_t j = 0; j < kNumCalls; j++) {
878 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000879 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000880 EXPECT_EQ(proc.rootBinder, out);
881 }
882 }));
883 }
884
885 for (auto& t : threads) t.join();
886}
887
Steven Moreland925ba0a2021-09-17 18:06:32 -0700888static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
889 std::vector<std::thread> threads;
890 for (size_t i = 0; i < threadCount; i++) {
891 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
892 }
893 for (auto& t : threads) t.join();
894}
895
Andrei Homescua858b0e2022-08-01 23:43:09 +0000896TEST_P(BinderRpc, OnewayStressTest) {
897 if (clientOrServerSingleThreaded()) {
898 GTEST_SKIP() << "This test requires multiple threads";
899 }
900
Steven Morelandc6046982021-04-20 00:49:42 +0000901 constexpr size_t kNumClientThreads = 10;
902 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700903 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000904
Steven Moreland4313d7e2021-07-15 23:41:22 +0000905 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000906
907 std::vector<std::thread> threads;
908 for (size_t i = 0; i < kNumClientThreads; i++) {
909 threads.push_back(std::thread([&] {
910 for (size_t j = 0; j < kNumCalls; j++) {
911 EXPECT_OK(proc.rootIface->sendString("a"));
912 }
Steven Morelandc6046982021-04-20 00:49:42 +0000913 }));
914 }
915
916 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700917
918 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000919}
920
Steven Morelandc1635952021-04-01 16:20:47 +0000921TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000922 constexpr size_t kReallyLongTimeMs = 100;
923 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
924
Steven Moreland4313d7e2021-07-15 23:41:22 +0000925 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000926
927 size_t epochMsBefore = epochMillis();
928
929 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
930
931 size_t epochMsAfter = epochMillis();
932 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
933}
934
Andrei Homescua858b0e2022-08-01 23:43:09 +0000935TEST_P(BinderRpc, OnewayCallQueueing) {
936 if (clientOrServerSingleThreaded()) {
937 GTEST_SKIP() << "This test requires multiple threads";
938 }
939
Steven Moreland5553ac42020-11-11 02:14:45 +0000940 constexpr size_t kNumSleeps = 10;
941 constexpr size_t kNumExtraServerThreads = 4;
942 constexpr size_t kSleepMs = 50;
943
944 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000945 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000946
947 EXPECT_OK(proc.rootIface->lock());
948
Steven Moreland1c678802021-09-17 16:48:47 -0700949 size_t epochMsBefore = epochMillis();
950
951 // all these *Async commands should be queued on the server sequentially,
952 // even though there are multiple threads.
953 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000954 proc.rootIface->sleepMsAsync(kSleepMs);
955 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000956 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
957
Steven Moreland1c678802021-09-17 16:48:47 -0700958 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000959 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700960
Steven Moreland5553ac42020-11-11 02:14:45 +0000961 size_t epochMsAfter = epochMillis();
962
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000963 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000964
Steven Moreland925ba0a2021-09-17 18:06:32 -0700965 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000966}
967
Andrei Homescua858b0e2022-08-01 23:43:09 +0000968TEST_P(BinderRpc, OnewayCallExhaustion) {
969 if (clientOrServerSingleThreaded()) {
970 GTEST_SKIP() << "This test requires multiple threads";
971 }
972
Steven Morelandd45be622021-06-04 02:19:37 +0000973 constexpr size_t kNumClients = 2;
974 constexpr size_t kTooLongMs = 1000;
975
Steven Moreland4313d7e2021-07-15 23:41:22 +0000976 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000977
978 // Build up oneway calls on the second session to make sure it terminates
979 // and shuts down. The first session should be unaffected (proc destructor
980 // checks the first session).
981 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
982
983 std::vector<std::thread> threads;
984 for (size_t i = 0; i < kNumClients; i++) {
985 // one of these threads will get stuck queueing a transaction once the
986 // socket fills up, the other will be able to fill up transactions on
987 // this object
988 threads.push_back(std::thread([&] {
989 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
990 }
991 }));
992 }
993 for (auto& t : threads) t.join();
994
995 Status status = iface->sleepMsAsync(kTooLongMs);
996 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
997
Steven Moreland798e0d12021-07-14 23:19:25 +0000998 // now that it has died, wait for the remote session to shutdown
999 std::vector<int32_t> remoteCounts;
1000 do {
1001 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1002 } while (remoteCounts.size() == kNumClients);
1003
Steven Morelandd45be622021-06-04 02:19:37 +00001004 // the second session should be shutdown in the other process by the time we
1005 // are able to join above (it'll only be hung up once it finishes processing
1006 // any pending commands). We need to erase this session from the record
1007 // here, so that the destructor for our session won't check that this
1008 // session is valid, but we still want it to test the other session.
1009 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1010}
1011
Steven Moreland659416d2021-05-11 00:47:50 +00001012TEST_P(BinderRpc, Callbacks) {
1013 const static std::string kTestString = "good afternoon!";
1014
Steven Morelandc7d40132021-06-10 03:42:11 +00001015 for (bool callIsOneway : {true, false}) {
1016 for (bool callbackIsOneway : {true, false}) {
1017 for (bool delayed : {true, false}) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001018 if (clientOrServerSingleThreaded() &&
1019 (callIsOneway || callbackIsOneway || delayed)) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001020 // we have no incoming connections to receive the callback
1021 continue;
1022 }
1023
Andrei Homescua858b0e2022-08-01 23:43:09 +00001024 size_t numIncomingConnections = clientOrServerSingleThreaded() ? 0 : 1;
Steven Moreland4313d7e2021-07-15 23:41:22 +00001025 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +00001026 {.numThreads = 1,
1027 .numSessions = 1,
Andrei Homescu2a298012022-06-15 01:08:54 +00001028 .numIncomingConnections = numIncomingConnections});
Steven Morelandc7d40132021-06-10 03:42:11 +00001029 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001030
Steven Morelandc7d40132021-06-10 03:42:11 +00001031 if (callIsOneway) {
1032 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1033 kTestString));
1034 } else {
1035 EXPECT_OK(
1036 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1037 }
Steven Moreland659416d2021-05-11 00:47:50 +00001038
Steven Moreland03ecce62022-05-13 23:22:05 +00001039 // if both transactions are synchronous and the response is sent back on the
1040 // same thread, everything should have happened in a nested call. Otherwise,
1041 // the callback will be processed on another thread.
1042 if (callIsOneway || callbackIsOneway || delayed) {
1043 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001044 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001045 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1046 }
Steven Moreland659416d2021-05-11 00:47:50 +00001047
Steven Morelandc7d40132021-06-10 03:42:11 +00001048 EXPECT_EQ(cb->mValues.size(), 1)
1049 << "callIsOneway: " << callIsOneway
1050 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1051 if (cb->mValues.empty()) continue;
1052 EXPECT_EQ(cb->mValues.at(0), kTestString)
1053 << "callIsOneway: " << callIsOneway
1054 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001055
Steven Morelandc7d40132021-06-10 03:42:11 +00001056 // since we are severing the connection, we need to go ahead and
1057 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001058 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1059 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1060 }
Steven Moreland659416d2021-05-11 00:47:50 +00001061
Steven Moreland1b304292021-07-15 22:59:34 +00001062 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001063 // need to manually shut it down
1064 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Morelandc7d40132021-06-10 03:42:11 +00001065 proc.expectAlreadyShutdown = true;
1066 }
Steven Moreland659416d2021-05-11 00:47:50 +00001067 }
1068 }
1069}
1070
Devin Moore66d5b7a2022-07-07 21:42:10 +00001071TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001072 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001073 GTEST_SKIP() << "This test requires multiple threads";
1074 }
1075 class MyDeathRec : public IBinder::DeathRecipient {
1076 public:
1077 void binderDied(const wp<IBinder>& /* who */) override {
1078 dead = true;
1079 mCv.notify_one();
1080 }
1081 std::mutex mMtx;
1082 std::condition_variable mCv;
1083 bool dead = false;
1084 };
1085
1086 // Death recipient needs to have an incoming connection to be called
1087 auto proc = createRpcTestSocketServerProcess(
1088 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1089
1090 auto dr = sp<MyDeathRec>::make();
1091 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1092
1093 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1094 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1095 }
1096
1097 std::unique_lock<std::mutex> lock(dr->mMtx);
1098 if (!dr->dead) {
1099 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1100 }
1101 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1102
1103 // need to wait for the session to shutdown so we don't "Leak session"
1104 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1105 proc.expectAlreadyShutdown = true;
1106}
1107
1108TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001109 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001110 GTEST_SKIP() << "This test requires multiple threads";
1111 }
1112 class MyDeathRec : public IBinder::DeathRecipient {
1113 public:
1114 void binderDied(const wp<IBinder>& /* who */) override {
1115 dead = true;
1116 mCv.notify_one();
1117 }
1118 std::mutex mMtx;
1119 std::condition_variable mCv;
1120 bool dead = false;
1121 };
1122
1123 // Death recipient needs to have an incoming connection to be called
1124 auto proc = createRpcTestSocketServerProcess(
1125 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1126
1127 auto dr = sp<MyDeathRec>::make();
1128 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1129
1130 // Explicitly calling shutDownAndWait will cause the death recipients
1131 // to be called.
1132 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1133
1134 std::unique_lock<std::mutex> lock(dr->mMtx);
1135 if (!dr->dead) {
1136 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1137 }
1138 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1139
1140 proc.proc.host.terminate();
1141 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1142 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1143 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1144 });
1145 proc.expectAlreadyShutdown = true;
1146}
1147
1148TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1149 class MyDeathRec : public IBinder::DeathRecipient {
1150 public:
1151 void binderDied(const wp<IBinder>& /* who */) override {}
1152 };
1153
1154 auto proc = createRpcTestSocketServerProcess(
1155 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1156
1157 auto dr = sp<MyDeathRec>::make();
1158 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1159 "Cannot register a DeathRecipient without any incoming connections.");
1160}
1161
1162TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001163 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001164 GTEST_SKIP() << "This test requires multiple threads";
1165 }
1166 class MyDeathRec : public IBinder::DeathRecipient {
1167 public:
1168 void binderDied(const wp<IBinder>& /* who */) override {
1169 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1170 }
1171 };
1172
1173 // Death recipient needs to have an incoming connection to be called
1174 auto proc = createRpcTestSocketServerProcess(
1175 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1176
1177 auto dr = sp<MyDeathRec>::make();
1178 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1179 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1180
1181 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1182 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1183 }
1184
1185 // need to wait for the session to shutdown so we don't "Leak session"
1186 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1187 proc.expectAlreadyShutdown = true;
1188}
1189
Steven Moreland195edb82021-06-08 02:44:39 +00001190TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001191 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001192 auto cb = sp<MyBinderRpcCallback>::make();
1193
1194 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1195 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1196}
1197
Steven Morelandc1635952021-04-01 16:20:47 +00001198TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001199 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001200 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001201
1202 // make sure there is some state during crash
1203 // 1. we hold their binder
1204 sp<IBinderRpcSession> session;
1205 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1206 // 2. they hold our binder
1207 sp<IBinder> binder = new BBinder();
1208 EXPECT_OK(proc.rootIface->holdBinder(binder));
1209
1210 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1211 << "Do death cleanup: " << doDeathCleanup;
1212
Frederick Maylea12b0962022-06-25 01:13:22 +00001213 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1214 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1215 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1216 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001217 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001218 }
1219}
1220
Steven Morelandd7302072021-05-15 01:32:04 +00001221TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001222 // This test only works if the current process shared the internal state of
1223 // ProcessState with the service across the call to fork(). Both the static
1224 // libraries and libbinder.so have their own separate copies of all the
1225 // globals, so the test only works when the test client and service both use
1226 // libbinder.so (when using static libraries, even a client and service
1227 // using the same kind of static library should have separate copies of the
1228 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +00001229 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001230 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1231 "at build time.";
1232 }
1233
Steven Moreland4313d7e2021-07-15 23:41:22 +00001234 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001235
Andrei Homescu2a298012022-06-15 01:08:54 +00001236 // we can't allocate IPCThreadState so actually the first time should
1237 // succeed :(
1238 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001239
1240 // second time! we catch the error :)
1241 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1242
Frederick Maylea12b0962022-06-25 01:13:22 +00001243 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1244 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1245 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1246 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001247 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001248}
1249
Frederick Mayle69a0c992022-05-26 20:38:39 +00001250TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1251 auto proc = createRpcTestSocketServerProcess({
1252 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1253 .serverSupportedFileDescriptorTransportModes =
1254 {RpcSession::FileDescriptorTransportMode::UNIX},
1255 .allowConnectFailure = true,
1256 });
1257 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1258 proc.proc.host.terminate();
1259 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1260 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1261 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1262 });
1263 proc.expectAlreadyShutdown = true;
1264}
1265
1266TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1267 auto proc = createRpcTestSocketServerProcess({
1268 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1269 .serverSupportedFileDescriptorTransportModes =
1270 {RpcSession::FileDescriptorTransportMode::NONE},
1271 .allowConnectFailure = true,
1272 });
1273 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1274 proc.proc.host.terminate();
1275 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1276 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1277 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1278 });
1279 proc.expectAlreadyShutdown = true;
1280}
1281
1282TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1283 auto proc = createRpcTestSocketServerProcess({
1284 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1285 .serverSupportedFileDescriptorTransportModes =
1286 {RpcSession::FileDescriptorTransportMode::NONE,
1287 RpcSession::FileDescriptorTransportMode::UNIX},
1288 });
1289
1290 android::os::ParcelFileDescriptor out;
1291 auto status = proc.rootIface->echoAsFile("hello", &out);
1292 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1293}
1294
1295TEST_P(BinderRpc, ReceiveFile) {
1296 auto proc = createRpcTestSocketServerProcess({
1297 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1298 .serverSupportedFileDescriptorTransportModes =
1299 {RpcSession::FileDescriptorTransportMode::UNIX},
1300 });
1301
1302 android::os::ParcelFileDescriptor out;
1303 auto status = proc.rootIface->echoAsFile("hello", &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, "hello");
1313}
1314
1315TEST_P(BinderRpc, SendFiles) {
1316 auto proc = createRpcTestSocketServerProcess({
1317 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1318 .serverSupportedFileDescriptorTransportModes =
1319 {RpcSession::FileDescriptorTransportMode::UNIX},
1320 });
1321
1322 std::vector<android::os::ParcelFileDescriptor> files;
1323 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1324 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1325 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1326 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1327
1328 android::os::ParcelFileDescriptor out;
1329 auto status = proc.rootIface->concatFiles(files, &out);
1330 if (!supportsFdTransport()) {
1331 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1332 return;
1333 }
1334 ASSERT_TRUE(status.isOk()) << status;
1335
1336 std::string result;
1337 CHECK(android::base::ReadFdToString(out.get(), &result));
1338 EXPECT_EQ(result, "123abcd");
1339}
1340
1341TEST_P(BinderRpc, SendMaxFiles) {
1342 if (!supportsFdTransport()) {
1343 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1344 }
1345
1346 auto proc = createRpcTestSocketServerProcess({
1347 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1348 .serverSupportedFileDescriptorTransportModes =
1349 {RpcSession::FileDescriptorTransportMode::UNIX},
1350 });
1351
1352 std::vector<android::os::ParcelFileDescriptor> files;
1353 for (int i = 0; i < 253; i++) {
1354 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1355 }
1356
1357 android::os::ParcelFileDescriptor out;
1358 auto status = proc.rootIface->concatFiles(files, &out);
1359 ASSERT_TRUE(status.isOk()) << status;
1360
1361 std::string result;
1362 CHECK(android::base::ReadFdToString(out.get(), &result));
1363 EXPECT_EQ(result, std::string(253, 'a'));
1364}
1365
1366TEST_P(BinderRpc, SendTooManyFiles) {
1367 if (!supportsFdTransport()) {
1368 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1369 }
1370
1371 auto proc = createRpcTestSocketServerProcess({
1372 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1373 .serverSupportedFileDescriptorTransportModes =
1374 {RpcSession::FileDescriptorTransportMode::UNIX},
1375 });
1376
1377 std::vector<android::os::ParcelFileDescriptor> files;
1378 for (int i = 0; i < 254; i++) {
1379 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1380 }
1381
1382 android::os::ParcelFileDescriptor out;
1383 auto status = proc.rootIface->concatFiles(files, &out);
1384 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1385}
1386
Steven Moreland37aff182021-03-26 02:04:16 +00001387TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001388 if constexpr (!kEnableSharedLibs) {
1389 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1390 }
1391
Steven Moreland4313d7e2021-07-15 23:41:22 +00001392 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001393
1394 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1395 ASSERT_NE(binder, nullptr);
1396
1397 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1398}
1399
1400TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001401 if constexpr (!kEnableSharedLibs) {
1402 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1403 }
1404
Steven Moreland4313d7e2021-07-15 23:41:22 +00001405 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001406
1407 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1408 ASSERT_NE(binder, nullptr);
1409
1410 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1411 ASSERT_NE(ndkBinder, nullptr);
1412
1413 std::string out;
1414 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1415 ASSERT_TRUE(status.isOk()) << status.getDescription();
1416 ASSERT_EQ("aoeuaoeu", out);
1417}
1418
Steven Moreland5553ac42020-11-11 02:14:45 +00001419ssize_t countFds() {
1420 DIR* dir = opendir("/proc/self/fd/");
1421 if (dir == nullptr) return -1;
1422 ssize_t ret = 0;
1423 dirent* ent;
1424 while ((ent = readdir(dir)) != nullptr) ret++;
1425 closedir(dir);
1426 return ret;
1427}
1428
Andrei Homescua858b0e2022-08-01 23:43:09 +00001429TEST_P(BinderRpc, Fds) {
1430 if (serverSingleThreaded()) {
1431 GTEST_SKIP() << "This test requires multiple threads";
1432 }
1433
Steven Moreland5553ac42020-11-11 02:14:45 +00001434 ssize_t beforeFds = countFds();
1435 ASSERT_GE(beforeFds, 0);
1436 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001437 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001438 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1439 }
1440 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1441}
1442
Devin Moore800b2252021-10-15 16:22:57 +00001443TEST_P(BinderRpc, AidlDelegatorTest) {
1444 auto proc = createRpcTestSocketServerProcess({});
1445 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1446 ASSERT_NE(nullptr, myDelegator);
1447
1448 std::string doubled;
1449 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1450 EXPECT_EQ("cool cool ", doubled);
1451}
1452
Steven Morelandda573042021-06-12 01:13:45 +00001453static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001454 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001455 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001456
Andrei Homescu992a4052022-06-28 21:26:18 +00001457 android::base::unique_fd serverFd(
1458 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1459 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1460
1461 sockaddr_vm serverAddr{
1462 .svm_family = AF_VSOCK,
1463 .svm_port = vsockPort,
1464 .svm_cid = VMADDR_CID_ANY,
1465 };
1466 int ret = TEMP_FAILURE_RETRY(
1467 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1468 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1469 strerror(errno));
1470
1471 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1472 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1473 strerror(errno));
1474
1475 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1476 // to see if the kernel supports it. It's safe to use a blocking
1477 // connect because vsock sockets have a 2 second connection timeout,
1478 // and they return ETIMEDOUT after that.
1479 android::base::unique_fd connectFd(
1480 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1481 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1482 strerror(errno));
1483
1484 bool success = false;
1485 sockaddr_vm connectAddr{
1486 .svm_family = AF_VSOCK,
1487 .svm_port = vsockPort,
1488 .svm_cid = VMADDR_CID_LOCAL,
1489 };
1490 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1491 sizeof(connectAddr)));
1492 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1493 android::base::unique_fd acceptFd;
1494 while (true) {
1495 pollfd pfd[]{
1496 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1497 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1498 };
1499 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1500 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1501
1502 if (pfd[0].revents & POLLIN) {
1503 sockaddr_vm acceptAddr;
1504 socklen_t acceptAddrLen = sizeof(acceptAddr);
1505 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1506 reinterpret_cast<sockaddr*>(&acceptAddr),
1507 &acceptAddrLen, SOCK_CLOEXEC));
1508 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1509 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1510 "Truncated address");
1511
1512 // Store the fd in acceptFd so we keep the connection alive
1513 // while polling connectFd
1514 acceptFd.reset(ret);
1515 }
1516
1517 if (pfd[1].revents & POLLOUT) {
1518 // Connect either succeeded or timed out
1519 int connectErrno;
1520 socklen_t connectErrnoLen = sizeof(connectErrno);
1521 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1522 &connectErrnoLen);
1523 LOG_ALWAYS_FATAL_IF(ret == -1,
1524 "Could not getsockopt() after connect() "
1525 "on non-blocking socket: %s.",
1526 strerror(errno));
1527
1528 // We're done, this is all we wanted
1529 success = connectErrno == 0;
1530 break;
1531 }
1532 }
1533 } else {
1534 success = ret == 0;
1535 }
1536
1537 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1538
1539 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001540}
1541
Yifan Hong1deca4b2021-09-10 16:16:44 -07001542static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1543 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1544
1545 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001546
1547 static bool hasVsockLoopback = testSupportVsockLoopback();
1548
1549 if (hasVsockLoopback) {
1550 ret.push_back(SocketType::VSOCK);
1551 }
1552
1553 return ret;
1554}
1555
Frederick Mayledc07cf82022-05-26 20:30:12 +00001556static std::vector<uint32_t> testVersions() {
1557 std::vector<uint32_t> versions;
1558 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1559 versions.push_back(i);
1560 }
1561 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1562 return versions;
1563}
1564
Yifan Hong702115c2021-06-24 15:39:18 -07001565INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1566 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001567 ::testing::ValuesIn(RpcSecurityValues()),
1568 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001569 ::testing::ValuesIn(testVersions()),
1570 ::testing::Values(false, true),
1571 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001572 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001573
Yifan Hong702115c2021-06-24 15:39:18 -07001574class BinderRpcServerRootObject
1575 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001576
1577TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1578 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1579 auto setRootObject = [](bool isStrong) -> SetFn {
1580 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1581 };
1582
Yifan Hong702115c2021-06-24 15:39:18 -07001583 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1584 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001585 auto binder1 = sp<BBinder>::make();
1586 IBinder* binderRaw1 = binder1.get();
1587 setRootObject(isStrong1)(server.get(), binder1);
1588 EXPECT_EQ(binderRaw1, server->getRootObject());
1589 binder1.clear();
1590 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1591
1592 auto binder2 = sp<BBinder>::make();
1593 IBinder* binderRaw2 = binder2.get();
1594 setRootObject(isStrong2)(server.get(), binder2);
1595 EXPECT_EQ(binderRaw2, server->getRootObject());
1596 binder2.clear();
1597 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1598}
1599
1600INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001601 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1602 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001603
Yifan Hong1a235852021-05-13 16:07:47 -07001604class OneOffSignal {
1605public:
1606 // If notify() was previously called, or is called within |duration|, return true; else false.
1607 template <typename R, typename P>
1608 bool wait(std::chrono::duration<R, P> duration) {
1609 std::unique_lock<std::mutex> lock(mMutex);
1610 return mCv.wait_for(lock, duration, [this] { return mValue; });
1611 }
1612 void notify() {
1613 std::unique_lock<std::mutex> lock(mMutex);
1614 mValue = true;
1615 lock.unlock();
1616 mCv.notify_all();
1617 }
1618
1619private:
1620 std::mutex mMutex;
1621 std::condition_variable mCv;
1622 bool mValue = false;
1623};
1624
Frederick Mayledc07cf82022-05-26 20:30:12 +00001625TEST_P(BinderRpcServerOnly, Shutdown) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001626 if constexpr (!kEnableRpcThreads) {
1627 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1628 }
1629
Yifan Hong1a235852021-05-13 16:07:47 -07001630 auto addr = allocateSocketAddress();
Frederick Mayledc07cf82022-05-26 20:30:12 +00001631 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1632 server->setProtocolVersion(std::get<1>(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001633 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001634 auto joinEnds = std::make_shared<OneOffSignal>();
1635
1636 // If things are broken and the thread never stops, don't block other tests. Because the thread
1637 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1638 // shared pointers are passed.
1639 std::thread([server, joinEnds] {
1640 server->join();
1641 joinEnds->notify();
1642 }).detach();
1643
1644 bool shutdown = false;
1645 for (int i = 0; i < 10 && !shutdown; i++) {
1646 usleep(300 * 1000); // 300ms; total 3s
1647 if (server->shutdown()) shutdown = true;
1648 }
1649 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1650
1651 ASSERT_TRUE(joinEnds->wait(2s))
1652 << "After server->shutdown() returns true, join() did not stop after 2s";
1653}
1654
Yifan Hong194acf22021-06-29 18:44:56 -07001655TEST(BinderRpc, Java) {
1656#if !defined(__ANDROID__)
1657 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1658 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1659 "to binderHostDeviceTest. Hence, just disable this test on host.";
1660#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001661 if constexpr (!kEnableKernelIpc) {
1662 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1663 "at build time.";
1664 }
1665
Yifan Hong194acf22021-06-29 18:44:56 -07001666 sp<IServiceManager> sm = defaultServiceManager();
1667 ASSERT_NE(nullptr, sm);
1668 // Any Java service with non-empty getInterfaceDescriptor() would do.
1669 // Let's pick batteryproperties.
1670 auto binder = sm->checkService(String16("batteryproperties"));
1671 ASSERT_NE(nullptr, binder);
1672 auto descriptor = binder->getInterfaceDescriptor();
1673 ASSERT_GE(descriptor.size(), 0);
1674 ASSERT_EQ(OK, binder->pingBinder());
1675
1676 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001677 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001678 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001679 auto socket = rpcServer->releaseServer();
1680
1681 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001682 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1683
Yifan Honge3caaf22022-01-12 14:46:56 -08001684 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1685 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001686 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001687 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1688 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001689 << statusToString(setRpcClientDebugStatus);
1690 GTEST_SKIP();
1691 }
1692
1693 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001694
1695 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001696 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001697 auto rpcBinder = rpcSession->getRootObject();
1698 ASSERT_NE(nullptr, rpcBinder);
1699
1700 ASSERT_EQ(OK, rpcBinder->pingBinder());
1701
1702 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1703 << "getInterfaceDescriptor should not crash system_server";
1704 ASSERT_EQ(OK, rpcBinder->pingBinder());
1705}
1706
Frederick Mayledc07cf82022-05-26 20:30:12 +00001707INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1708 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1709 ::testing::ValuesIn(testVersions())),
1710 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001711
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001712class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001713public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001714 // Only parameterized only server version because `RpcSession` is bypassed
1715 // in the client half of the tests.
1716 using Param =
1717 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001718 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001719
1720 // A server that handles client socket connections.
1721 class Server {
1722 public:
1723 explicit Server() {}
1724 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001725 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001726 [[nodiscard]] AssertionResult setUp(
1727 const Param& param,
1728 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001729 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001730 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001731 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001732 switch (socketType) {
1733 case SocketType::PRECONNECTED: {
1734 return AssertionFailure() << "Not supported by this test";
1735 } break;
1736 case SocketType::UNIX: {
1737 auto addr = allocateSocketAddress();
1738 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1739 if (status != OK) {
1740 return AssertionFailure()
1741 << "setupUnixDomainServer: " << statusToString(status);
1742 }
1743 mConnectToServer = [addr] {
1744 return connectTo(UnixSocketAddress(addr.c_str()));
1745 };
1746 } break;
1747 case SocketType::VSOCK: {
1748 auto port = allocateVsockPort();
1749 auto status = rpcServer->setupVsockServer(port);
1750 if (status != OK) {
1751 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1752 }
1753 mConnectToServer = [port] {
1754 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1755 };
1756 } break;
1757 case SocketType::INET: {
1758 unsigned int port;
1759 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1760 if (status != OK) {
1761 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1762 }
1763 mConnectToServer = [port] {
1764 const char* addr = kLocalInetAddress;
1765 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1766 if (aiStart == nullptr) return base::unique_fd{};
1767 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1768 auto fd = connectTo(
1769 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1770 if (fd.ok()) return fd;
1771 }
1772 ALOGE("None of the socket address resolved for %s:%u can be connected",
1773 addr, port);
1774 return base::unique_fd{};
1775 };
1776 }
1777 }
1778 mFd = rpcServer->releaseServer();
1779 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001780 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001781 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1782 mSetup = true;
1783 return AssertionSuccess();
1784 }
1785 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1786 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1787 return mCertVerifier;
1788 }
1789 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1790 void start() {
1791 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1792 mThread = std::make_unique<std::thread>(&Server::run, this);
1793 }
1794 void run() {
1795 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1796
1797 std::vector<std::thread> threads;
1798 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1799 base::unique_fd acceptedFd(
1800 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1801 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1802 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1803 }
1804
1805 for (auto& thread : threads) thread.join();
1806 }
1807 void handleOne(android::base::unique_fd acceptedFd) {
1808 ASSERT_TRUE(acceptedFd.ok());
1809 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1810 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001811 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001812 }
Yifan Honge07d2732021-09-13 21:59:14 -07001813 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001814 shutdown();
1815 join();
1816 }
1817 void shutdown() { mFdTrigger->trigger(); }
1818
1819 void setPostConnect(
1820 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1821 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001822 }
1823
1824 private:
1825 std::unique_ptr<std::thread> mThread;
1826 ConnectToServer mConnectToServer;
1827 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1828 base::unique_fd mFd;
1829 std::unique_ptr<RpcTransportCtx> mCtx;
1830 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1831 std::make_shared<RpcCertificateVerifierSimple>();
1832 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001833 // The function invoked after connection and handshake. By default, it is
1834 // |defaultPostConnect| that sends |kMessage| to the client.
1835 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1836 Server::defaultPostConnect;
1837
1838 void join() {
1839 if (mThread != nullptr) {
1840 mThread->join();
1841 mThread = nullptr;
1842 }
1843 }
1844
1845 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1846 FdTrigger* fdTrigger) {
1847 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001848 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001849 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001850 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001851 if (status != OK) return AssertionFailure() << statusToString(status);
1852 return AssertionSuccess();
1853 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001854 };
1855
1856 class Client {
1857 public:
1858 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1859 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001860 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001861 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1862 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001863 mFdTrigger = FdTrigger::make();
1864 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1865 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1866 return AssertionSuccess();
1867 }
1868 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1869 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1870 return mCertVerifier;
1871 }
Yifan Hong67519322021-09-13 18:51:16 -07001872 // connect() and do handshake
1873 bool setUpTransport() {
1874 mFd = mConnectToServer();
1875 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1876 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1877 return mClientTransport != nullptr;
1878 }
1879 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1880 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1881 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001882 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001883 status_t readStatus =
1884 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001885 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001886 if (readStatus != OK) {
1887 return AssertionFailure() << statusToString(readStatus);
1888 }
1889 if (readMessage != expectedMessage) {
1890 return AssertionFailure()
1891 << "Expected " << expectedMessage << ", actual " << readMessage;
1892 }
1893 return AssertionSuccess();
1894 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001895 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001896 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001897 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1898 return;
1899 }
1900 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001901 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001902 }
1903
1904 private:
1905 ConnectToServer mConnectToServer;
1906 base::unique_fd mFd;
1907 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1908 std::unique_ptr<RpcTransportCtx> mCtx;
1909 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1910 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001911 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001912 };
1913
1914 // Make A trust B.
1915 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001916 static status_t trust(RpcSecurity rpcSecurity,
1917 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1918 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001919 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001920 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1921 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1922 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001923 }
1924
1925 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001926};
1927
1928class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1929public:
1930 using Server = RpcTransportTestUtils::Server;
1931 using Client = RpcTransportTestUtils::Client;
1932 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001933 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001934 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1935 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001936 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001937 return ret;
1938 }
1939 static std::vector<ParamType> getRpcTranportTestParams() {
1940 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001941 for (auto serverVersion : testVersions()) {
1942 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1943 for (auto rpcSecurity : RpcSecurityValues()) {
1944 switch (rpcSecurity) {
1945 case RpcSecurity::RAW: {
1946 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1947 } break;
1948 case RpcSecurity::TLS: {
1949 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1950 serverVersion);
1951 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1952 serverVersion);
1953 } break;
1954 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001955 }
1956 }
1957 }
1958 return ret;
1959 }
1960 template <typename A, typename B>
1961 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001962 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1963 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001964 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1965 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001966 void SetUp() override {
1967 if constexpr (!kEnableRpcThreads) {
1968 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1969 }
1970 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001971};
1972
1973TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001974 auto server = std::make_unique<Server>();
1975 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001976
1977 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001978 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001979
1980 ASSERT_EQ(OK, trust(&client, server));
1981 ASSERT_EQ(OK, trust(server, &client));
1982
1983 server->start();
1984 client.run();
1985}
1986
1987TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001988 auto server = std::make_unique<Server>();
1989 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001990
1991 std::vector<Client> clients;
1992 for (int i = 0; i < 2; i++) {
1993 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001994 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001995 ASSERT_EQ(OK, trust(&client, server));
1996 ASSERT_EQ(OK, trust(server, &client));
1997 }
1998
1999 server->start();
2000 for (auto& client : clients) client.run();
2001}
2002
2003TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002004 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2005 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002006
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002007 auto untrustedServer = std::make_unique<Server>();
2008 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002009
2010 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002011 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002012
2013 ASSERT_EQ(OK, trust(untrustedServer, &client));
2014
2015 untrustedServer->start();
2016
2017 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2018 // the client can't verify the server's identity.
2019 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2020 client.run(handshakeOk);
2021}
2022TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002023 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2024 (void)serverVersion;
2025
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002026 auto validServer = std::make_unique<Server>();
2027 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002028
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002029 auto maliciousServer = std::make_unique<Server>();
2030 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002031
2032 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002033 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002034
2035 ASSERT_EQ(OK, trust(&client, validServer));
2036 ASSERT_EQ(OK, trust(validServer, &client));
2037 ASSERT_EQ(OK, trust(maliciousServer, &client));
2038
2039 maliciousServer->start();
2040
2041 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2042 // the client can't verify the server's identity.
2043 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2044 client.run(handshakeOk);
2045}
2046
2047TEST_P(RpcTransportTest, UntrustedClient) {
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 client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002055 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002056
2057 ASSERT_EQ(OK, trust(&client, server));
2058
2059 server->start();
2060
2061 // For TLS, Client should be able to verify server's identity, so client should see
2062 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2063 // identity and should drop the connection, so client shouldn't be able to read anything.
2064 bool readOk = rpcSecurity != RpcSecurity::TLS;
2065 client.run(true, readOk);
2066}
2067
2068TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002069 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2070 (void)serverVersion;
2071
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002072 auto server = std::make_unique<Server>();
2073 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002074
2075 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002076 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002077 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002078 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002079
2080 ASSERT_EQ(OK, trust(&validClient, server));
2081 ASSERT_EQ(OK, trust(&maliciousClient, server));
2082
2083 server->start();
2084
2085 // See UntrustedClient.
2086 bool readOk = rpcSecurity != RpcSecurity::TLS;
2087 maliciousClient.run(true, readOk);
2088}
2089
Yifan Hong67519322021-09-13 18:51:16 -07002090TEST_P(RpcTransportTest, Trigger) {
2091 std::string msg2 = ", world!";
2092 std::mutex writeMutex;
2093 std::condition_variable writeCv;
2094 bool shouldContinueWriting = false;
2095 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002096 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002097 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002098 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2099 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002100 if (status != OK) return AssertionFailure() << statusToString(status);
2101
2102 {
2103 std::unique_lock<std::mutex> lock(writeMutex);
2104 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2105 return AssertionFailure() << "write barrier not cleared in time!";
2106 }
2107 }
2108
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002109 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002110 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2111 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002112 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002113 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002114 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002115 << statusToString(status);
2116 return AssertionSuccess();
2117 };
2118
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002119 auto server = std::make_unique<Server>();
2120 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002121
2122 // Set up client
2123 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002124 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002125
2126 // Exchange keys
2127 ASSERT_EQ(OK, trust(&client, server));
2128 ASSERT_EQ(OK, trust(server, &client));
2129
2130 server->setPostConnect(serverPostConnect);
2131
Yifan Hong67519322021-09-13 18:51:16 -07002132 server->start();
2133 // connect() to server and do handshake
2134 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002135 // read the first message. This ensures that server has finished handshake and start handling
2136 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002137 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002138 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2139 // write is on an FdTrigger that has been shut down.
2140 server->shutdown();
2141 // Continues server thread to write the second message.
2142 {
Yifan Hong22211f82021-09-14 12:32:25 -07002143 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002144 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002145 }
Yifan Hong22211f82021-09-14 12:32:25 -07002146 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002147 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002148 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002149 // On the client side, second read fails with DEAD_OBJECT
2150 ASSERT_FALSE(client.readMessage(msg2));
2151}
2152
Yifan Hong1deca4b2021-09-10 16:16:44 -07002153INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002154 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002155 RpcTransportTest::PrintParamInfo);
2156
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002157class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002158 : public testing::TestWithParam<
2159 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002160public:
2161 template <typename A, typename B>
2162 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002163 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2164 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002165 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2166 }
2167 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002168 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2169 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2170 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002171 };
2172};
2173
2174TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002175 if constexpr (!kEnableRpcThreads) {
2176 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2177 }
2178
Frederick Mayledc07cf82022-05-26 20:30:12 +00002179 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002180
2181 std::vector<uint8_t> pkeyData, certData;
2182 {
2183 auto pkey = makeKeyPairForSelfSignedCert();
2184 ASSERT_NE(nullptr, pkey);
2185 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2186 ASSERT_NE(nullptr, cert);
2187 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2188 certData = serializeCertificate(cert.get(), certificateFormat);
2189 }
2190
2191 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2192 auto desCert = deserializeCertificate(certData, certificateFormat);
2193 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002194 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2195 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002196
2197 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2198 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2199
2200 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2201 ASSERT_TRUE(client.setUp(utilsParam));
2202
2203 ASSERT_EQ(OK, trust(&client, server));
2204 ASSERT_EQ(OK, trust(server, &client));
2205
2206 server->start();
2207 client.run();
2208}
2209
2210INSTANTIATE_TEST_CASE_P(
2211 BinderRpc, RpcTransportTlsKeyTest,
2212 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2213 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002214 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2215 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002216 RpcTransportTlsKeyTest::PrintParamInfo);
2217
Steven Morelandc1635952021-04-01 16:20:47 +00002218} // namespace android
2219
2220int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002221 ::testing::InitGoogleTest(&argc, argv);
2222 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002223
Steven Moreland5553ac42020-11-11 02:14:45 +00002224 return RUN_ALL_TESTS();
2225}