blob: b59308c15654023e652c39a90c82e35ff4bf1d42 [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);
Devin Moore47a12012022-08-19 21:16:17 +00001098 ASSERT_TRUE(dr->mCv.wait_for(lock, 1000ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001099
1100 // need to wait for the session to shutdown so we don't "Leak session"
1101 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1102 proc.expectAlreadyShutdown = true;
1103}
1104
1105TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001106 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001107 GTEST_SKIP() << "This test requires multiple threads";
1108 }
1109 class MyDeathRec : public IBinder::DeathRecipient {
1110 public:
1111 void binderDied(const wp<IBinder>& /* who */) override {
1112 dead = true;
1113 mCv.notify_one();
1114 }
1115 std::mutex mMtx;
1116 std::condition_variable mCv;
1117 bool dead = false;
1118 };
1119
1120 // Death recipient needs to have an incoming connection to be called
1121 auto proc = createRpcTestSocketServerProcess(
1122 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1123
1124 auto dr = sp<MyDeathRec>::make();
1125 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1126
1127 // Explicitly calling shutDownAndWait will cause the death recipients
1128 // to be called.
1129 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1130
1131 std::unique_lock<std::mutex> lock(dr->mMtx);
1132 if (!dr->dead) {
1133 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1134 }
1135 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1136
1137 proc.proc.host.terminate();
1138 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1139 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1140 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1141 });
1142 proc.expectAlreadyShutdown = true;
1143}
1144
1145TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1146 class MyDeathRec : public IBinder::DeathRecipient {
1147 public:
1148 void binderDied(const wp<IBinder>& /* who */) override {}
1149 };
1150
1151 auto proc = createRpcTestSocketServerProcess(
1152 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1153
1154 auto dr = sp<MyDeathRec>::make();
1155 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1156 "Cannot register a DeathRecipient without any incoming connections.");
1157}
1158
1159TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001160 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001161 GTEST_SKIP() << "This test requires multiple threads";
1162 }
1163 class MyDeathRec : public IBinder::DeathRecipient {
1164 public:
1165 void binderDied(const wp<IBinder>& /* who */) override {
1166 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1167 }
1168 };
1169
1170 // Death recipient needs to have an incoming connection to be called
1171 auto proc = createRpcTestSocketServerProcess(
1172 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1173
1174 auto dr = sp<MyDeathRec>::make();
1175 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1176 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1177
1178 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1179 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1180 }
1181
1182 // need to wait for the session to shutdown so we don't "Leak session"
1183 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1184 proc.expectAlreadyShutdown = true;
1185}
1186
Steven Moreland195edb82021-06-08 02:44:39 +00001187TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001188 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001189 auto cb = sp<MyBinderRpcCallback>::make();
1190
1191 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1192 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1193}
1194
Steven Morelandc1635952021-04-01 16:20:47 +00001195TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001196 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001197 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001198
1199 // make sure there is some state during crash
1200 // 1. we hold their binder
1201 sp<IBinderRpcSession> session;
1202 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1203 // 2. they hold our binder
1204 sp<IBinder> binder = new BBinder();
1205 EXPECT_OK(proc.rootIface->holdBinder(binder));
1206
1207 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1208 << "Do death cleanup: " << doDeathCleanup;
1209
Frederick Maylea12b0962022-06-25 01:13:22 +00001210 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1211 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1212 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1213 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001214 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001215 }
1216}
1217
Steven Morelandd7302072021-05-15 01:32:04 +00001218TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001219 // This test only works if the current process shared the internal state of
1220 // ProcessState with the service across the call to fork(). Both the static
1221 // libraries and libbinder.so have their own separate copies of all the
1222 // globals, so the test only works when the test client and service both use
1223 // libbinder.so (when using static libraries, even a client and service
1224 // using the same kind of static library should have separate copies of the
1225 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +00001226 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001227 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1228 "at build time.";
1229 }
1230
Steven Moreland4313d7e2021-07-15 23:41:22 +00001231 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001232
Andrei Homescu2a298012022-06-15 01:08:54 +00001233 // we can't allocate IPCThreadState so actually the first time should
1234 // succeed :(
1235 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001236
1237 // second time! we catch the error :)
1238 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1239
Frederick Maylea12b0962022-06-25 01:13:22 +00001240 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1241 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1242 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1243 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001244 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001245}
1246
Frederick Mayle69a0c992022-05-26 20:38:39 +00001247TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1248 auto proc = createRpcTestSocketServerProcess({
1249 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1250 .serverSupportedFileDescriptorTransportModes =
1251 {RpcSession::FileDescriptorTransportMode::UNIX},
1252 .allowConnectFailure = true,
1253 });
1254 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1255 proc.proc.host.terminate();
1256 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1257 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1258 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1259 });
1260 proc.expectAlreadyShutdown = true;
1261}
1262
1263TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1264 auto proc = createRpcTestSocketServerProcess({
1265 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1266 .serverSupportedFileDescriptorTransportModes =
1267 {RpcSession::FileDescriptorTransportMode::NONE},
1268 .allowConnectFailure = true,
1269 });
1270 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1271 proc.proc.host.terminate();
1272 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1273 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1274 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1275 });
1276 proc.expectAlreadyShutdown = true;
1277}
1278
1279TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1280 auto proc = createRpcTestSocketServerProcess({
1281 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1282 .serverSupportedFileDescriptorTransportModes =
1283 {RpcSession::FileDescriptorTransportMode::NONE,
1284 RpcSession::FileDescriptorTransportMode::UNIX},
1285 });
1286
1287 android::os::ParcelFileDescriptor out;
1288 auto status = proc.rootIface->echoAsFile("hello", &out);
1289 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1290}
1291
1292TEST_P(BinderRpc, ReceiveFile) {
1293 auto proc = createRpcTestSocketServerProcess({
1294 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1295 .serverSupportedFileDescriptorTransportModes =
1296 {RpcSession::FileDescriptorTransportMode::UNIX},
1297 });
1298
1299 android::os::ParcelFileDescriptor out;
1300 auto status = proc.rootIface->echoAsFile("hello", &out);
1301 if (!supportsFdTransport()) {
1302 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1303 return;
1304 }
1305 ASSERT_TRUE(status.isOk()) << status;
1306
1307 std::string result;
1308 CHECK(android::base::ReadFdToString(out.get(), &result));
1309 EXPECT_EQ(result, "hello");
1310}
1311
1312TEST_P(BinderRpc, SendFiles) {
1313 auto proc = createRpcTestSocketServerProcess({
1314 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1315 .serverSupportedFileDescriptorTransportModes =
1316 {RpcSession::FileDescriptorTransportMode::UNIX},
1317 });
1318
1319 std::vector<android::os::ParcelFileDescriptor> files;
1320 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1321 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1322 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1323 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1324
1325 android::os::ParcelFileDescriptor out;
1326 auto status = proc.rootIface->concatFiles(files, &out);
1327 if (!supportsFdTransport()) {
1328 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1329 return;
1330 }
1331 ASSERT_TRUE(status.isOk()) << status;
1332
1333 std::string result;
1334 CHECK(android::base::ReadFdToString(out.get(), &result));
1335 EXPECT_EQ(result, "123abcd");
1336}
1337
1338TEST_P(BinderRpc, SendMaxFiles) {
1339 if (!supportsFdTransport()) {
1340 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1341 }
1342
1343 auto proc = createRpcTestSocketServerProcess({
1344 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1345 .serverSupportedFileDescriptorTransportModes =
1346 {RpcSession::FileDescriptorTransportMode::UNIX},
1347 });
1348
1349 std::vector<android::os::ParcelFileDescriptor> files;
1350 for (int i = 0; i < 253; i++) {
1351 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1352 }
1353
1354 android::os::ParcelFileDescriptor out;
1355 auto status = proc.rootIface->concatFiles(files, &out);
1356 ASSERT_TRUE(status.isOk()) << status;
1357
1358 std::string result;
1359 CHECK(android::base::ReadFdToString(out.get(), &result));
1360 EXPECT_EQ(result, std::string(253, 'a'));
1361}
1362
1363TEST_P(BinderRpc, SendTooManyFiles) {
1364 if (!supportsFdTransport()) {
1365 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1366 }
1367
1368 auto proc = createRpcTestSocketServerProcess({
1369 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1370 .serverSupportedFileDescriptorTransportModes =
1371 {RpcSession::FileDescriptorTransportMode::UNIX},
1372 });
1373
1374 std::vector<android::os::ParcelFileDescriptor> files;
1375 for (int i = 0; i < 254; i++) {
1376 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1377 }
1378
1379 android::os::ParcelFileDescriptor out;
1380 auto status = proc.rootIface->concatFiles(files, &out);
1381 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1382}
1383
Steven Moreland37aff182021-03-26 02:04:16 +00001384TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001385 if constexpr (!kEnableSharedLibs) {
1386 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1387 }
1388
Steven Moreland4313d7e2021-07-15 23:41:22 +00001389 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001390
1391 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1392 ASSERT_NE(binder, nullptr);
1393
1394 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1395}
1396
1397TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001398 if constexpr (!kEnableSharedLibs) {
1399 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1400 }
1401
Steven Moreland4313d7e2021-07-15 23:41:22 +00001402 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001403
1404 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1405 ASSERT_NE(binder, nullptr);
1406
1407 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1408 ASSERT_NE(ndkBinder, nullptr);
1409
1410 std::string out;
1411 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1412 ASSERT_TRUE(status.isOk()) << status.getDescription();
1413 ASSERT_EQ("aoeuaoeu", out);
1414}
1415
Steven Moreland5553ac42020-11-11 02:14:45 +00001416ssize_t countFds() {
1417 DIR* dir = opendir("/proc/self/fd/");
1418 if (dir == nullptr) return -1;
1419 ssize_t ret = 0;
1420 dirent* ent;
1421 while ((ent = readdir(dir)) != nullptr) ret++;
1422 closedir(dir);
1423 return ret;
1424}
1425
Andrei Homescua858b0e2022-08-01 23:43:09 +00001426TEST_P(BinderRpc, Fds) {
1427 if (serverSingleThreaded()) {
1428 GTEST_SKIP() << "This test requires multiple threads";
1429 }
1430
Steven Moreland5553ac42020-11-11 02:14:45 +00001431 ssize_t beforeFds = countFds();
1432 ASSERT_GE(beforeFds, 0);
1433 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001434 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001435 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1436 }
1437 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1438}
1439
Devin Moore800b2252021-10-15 16:22:57 +00001440TEST_P(BinderRpc, AidlDelegatorTest) {
1441 auto proc = createRpcTestSocketServerProcess({});
1442 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1443 ASSERT_NE(nullptr, myDelegator);
1444
1445 std::string doubled;
1446 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1447 EXPECT_EQ("cool cool ", doubled);
1448}
1449
Steven Morelandda573042021-06-12 01:13:45 +00001450static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001451 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001452 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001453
Andrei Homescu992a4052022-06-28 21:26:18 +00001454 android::base::unique_fd serverFd(
1455 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1456 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1457
1458 sockaddr_vm serverAddr{
1459 .svm_family = AF_VSOCK,
1460 .svm_port = vsockPort,
1461 .svm_cid = VMADDR_CID_ANY,
1462 };
1463 int ret = TEMP_FAILURE_RETRY(
1464 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1465 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1466 strerror(errno));
1467
1468 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1469 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1470 strerror(errno));
1471
1472 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1473 // to see if the kernel supports it. It's safe to use a blocking
1474 // connect because vsock sockets have a 2 second connection timeout,
1475 // and they return ETIMEDOUT after that.
1476 android::base::unique_fd connectFd(
1477 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1478 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1479 strerror(errno));
1480
1481 bool success = false;
1482 sockaddr_vm connectAddr{
1483 .svm_family = AF_VSOCK,
1484 .svm_port = vsockPort,
1485 .svm_cid = VMADDR_CID_LOCAL,
1486 };
1487 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1488 sizeof(connectAddr)));
1489 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1490 android::base::unique_fd acceptFd;
1491 while (true) {
1492 pollfd pfd[]{
1493 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1494 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1495 };
1496 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1497 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1498
1499 if (pfd[0].revents & POLLIN) {
1500 sockaddr_vm acceptAddr;
1501 socklen_t acceptAddrLen = sizeof(acceptAddr);
1502 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1503 reinterpret_cast<sockaddr*>(&acceptAddr),
1504 &acceptAddrLen, SOCK_CLOEXEC));
1505 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1506 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1507 "Truncated address");
1508
1509 // Store the fd in acceptFd so we keep the connection alive
1510 // while polling connectFd
1511 acceptFd.reset(ret);
1512 }
1513
1514 if (pfd[1].revents & POLLOUT) {
1515 // Connect either succeeded or timed out
1516 int connectErrno;
1517 socklen_t connectErrnoLen = sizeof(connectErrno);
1518 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1519 &connectErrnoLen);
1520 LOG_ALWAYS_FATAL_IF(ret == -1,
1521 "Could not getsockopt() after connect() "
1522 "on non-blocking socket: %s.",
1523 strerror(errno));
1524
1525 // We're done, this is all we wanted
1526 success = connectErrno == 0;
1527 break;
1528 }
1529 }
1530 } else {
1531 success = ret == 0;
1532 }
1533
1534 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1535
1536 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001537}
1538
Yifan Hong1deca4b2021-09-10 16:16:44 -07001539static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1540 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1541
1542 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001543
1544 static bool hasVsockLoopback = testSupportVsockLoopback();
1545
1546 if (hasVsockLoopback) {
1547 ret.push_back(SocketType::VSOCK);
1548 }
1549
1550 return ret;
1551}
1552
Frederick Mayledc07cf82022-05-26 20:30:12 +00001553static std::vector<uint32_t> testVersions() {
1554 std::vector<uint32_t> versions;
1555 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1556 versions.push_back(i);
1557 }
1558 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1559 return versions;
1560}
1561
Yifan Hong702115c2021-06-24 15:39:18 -07001562INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1563 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001564 ::testing::ValuesIn(RpcSecurityValues()),
1565 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001566 ::testing::ValuesIn(testVersions()),
1567 ::testing::Values(false, true),
1568 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001569 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001570
Yifan Hong702115c2021-06-24 15:39:18 -07001571class BinderRpcServerRootObject
1572 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001573
1574TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1575 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1576 auto setRootObject = [](bool isStrong) -> SetFn {
1577 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1578 };
1579
Yifan Hong702115c2021-06-24 15:39:18 -07001580 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1581 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001582 auto binder1 = sp<BBinder>::make();
1583 IBinder* binderRaw1 = binder1.get();
1584 setRootObject(isStrong1)(server.get(), binder1);
1585 EXPECT_EQ(binderRaw1, server->getRootObject());
1586 binder1.clear();
1587 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1588
1589 auto binder2 = sp<BBinder>::make();
1590 IBinder* binderRaw2 = binder2.get();
1591 setRootObject(isStrong2)(server.get(), binder2);
1592 EXPECT_EQ(binderRaw2, server->getRootObject());
1593 binder2.clear();
1594 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1595}
1596
1597INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001598 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1599 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001600
Yifan Hong1a235852021-05-13 16:07:47 -07001601class OneOffSignal {
1602public:
1603 // If notify() was previously called, or is called within |duration|, return true; else false.
1604 template <typename R, typename P>
1605 bool wait(std::chrono::duration<R, P> duration) {
1606 std::unique_lock<std::mutex> lock(mMutex);
1607 return mCv.wait_for(lock, duration, [this] { return mValue; });
1608 }
1609 void notify() {
1610 std::unique_lock<std::mutex> lock(mMutex);
1611 mValue = true;
1612 lock.unlock();
1613 mCv.notify_all();
1614 }
1615
1616private:
1617 std::mutex mMutex;
1618 std::condition_variable mCv;
1619 bool mValue = false;
1620};
1621
Frederick Mayledc07cf82022-05-26 20:30:12 +00001622TEST_P(BinderRpcServerOnly, Shutdown) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001623 if constexpr (!kEnableRpcThreads) {
1624 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1625 }
1626
Yifan Hong1a235852021-05-13 16:07:47 -07001627 auto addr = allocateSocketAddress();
Frederick Mayledc07cf82022-05-26 20:30:12 +00001628 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1629 server->setProtocolVersion(std::get<1>(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001630 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001631 auto joinEnds = std::make_shared<OneOffSignal>();
1632
1633 // If things are broken and the thread never stops, don't block other tests. Because the thread
1634 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1635 // shared pointers are passed.
1636 std::thread([server, joinEnds] {
1637 server->join();
1638 joinEnds->notify();
1639 }).detach();
1640
1641 bool shutdown = false;
1642 for (int i = 0; i < 10 && !shutdown; i++) {
1643 usleep(300 * 1000); // 300ms; total 3s
1644 if (server->shutdown()) shutdown = true;
1645 }
1646 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1647
1648 ASSERT_TRUE(joinEnds->wait(2s))
1649 << "After server->shutdown() returns true, join() did not stop after 2s";
1650}
1651
Yifan Hong194acf22021-06-29 18:44:56 -07001652TEST(BinderRpc, Java) {
1653#if !defined(__ANDROID__)
1654 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1655 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1656 "to binderHostDeviceTest. Hence, just disable this test on host.";
1657#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001658 if constexpr (!kEnableKernelIpc) {
1659 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1660 "at build time.";
1661 }
1662
Yifan Hong194acf22021-06-29 18:44:56 -07001663 sp<IServiceManager> sm = defaultServiceManager();
1664 ASSERT_NE(nullptr, sm);
1665 // Any Java service with non-empty getInterfaceDescriptor() would do.
1666 // Let's pick batteryproperties.
1667 auto binder = sm->checkService(String16("batteryproperties"));
1668 ASSERT_NE(nullptr, binder);
1669 auto descriptor = binder->getInterfaceDescriptor();
1670 ASSERT_GE(descriptor.size(), 0);
1671 ASSERT_EQ(OK, binder->pingBinder());
1672
1673 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001674 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001675 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001676 auto socket = rpcServer->releaseServer();
1677
1678 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001679 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1680
Yifan Honge3caaf22022-01-12 14:46:56 -08001681 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1682 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001683 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001684 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1685 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001686 << statusToString(setRpcClientDebugStatus);
1687 GTEST_SKIP();
1688 }
1689
1690 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001691
1692 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001693 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001694 auto rpcBinder = rpcSession->getRootObject();
1695 ASSERT_NE(nullptr, rpcBinder);
1696
1697 ASSERT_EQ(OK, rpcBinder->pingBinder());
1698
1699 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1700 << "getInterfaceDescriptor should not crash system_server";
1701 ASSERT_EQ(OK, rpcBinder->pingBinder());
1702}
1703
Frederick Mayledc07cf82022-05-26 20:30:12 +00001704INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1705 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1706 ::testing::ValuesIn(testVersions())),
1707 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001708
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001709class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001710public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001711 // Only parameterized only server version because `RpcSession` is bypassed
1712 // in the client half of the tests.
1713 using Param =
1714 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001715 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001716
1717 // A server that handles client socket connections.
1718 class Server {
1719 public:
1720 explicit Server() {}
1721 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001722 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001723 [[nodiscard]] AssertionResult setUp(
1724 const Param& param,
1725 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001726 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001727 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001728 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001729 switch (socketType) {
1730 case SocketType::PRECONNECTED: {
1731 return AssertionFailure() << "Not supported by this test";
1732 } break;
1733 case SocketType::UNIX: {
1734 auto addr = allocateSocketAddress();
1735 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1736 if (status != OK) {
1737 return AssertionFailure()
1738 << "setupUnixDomainServer: " << statusToString(status);
1739 }
1740 mConnectToServer = [addr] {
1741 return connectTo(UnixSocketAddress(addr.c_str()));
1742 };
1743 } break;
1744 case SocketType::VSOCK: {
1745 auto port = allocateVsockPort();
1746 auto status = rpcServer->setupVsockServer(port);
1747 if (status != OK) {
1748 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1749 }
1750 mConnectToServer = [port] {
1751 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1752 };
1753 } break;
1754 case SocketType::INET: {
1755 unsigned int port;
1756 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1757 if (status != OK) {
1758 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1759 }
1760 mConnectToServer = [port] {
1761 const char* addr = kLocalInetAddress;
1762 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1763 if (aiStart == nullptr) return base::unique_fd{};
1764 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1765 auto fd = connectTo(
1766 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1767 if (fd.ok()) return fd;
1768 }
1769 ALOGE("None of the socket address resolved for %s:%u can be connected",
1770 addr, port);
1771 return base::unique_fd{};
1772 };
1773 }
1774 }
1775 mFd = rpcServer->releaseServer();
1776 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001777 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001778 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1779 mSetup = true;
1780 return AssertionSuccess();
1781 }
1782 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1783 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1784 return mCertVerifier;
1785 }
1786 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1787 void start() {
1788 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1789 mThread = std::make_unique<std::thread>(&Server::run, this);
1790 }
1791 void run() {
1792 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1793
1794 std::vector<std::thread> threads;
1795 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1796 base::unique_fd acceptedFd(
1797 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1798 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1799 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1800 }
1801
1802 for (auto& thread : threads) thread.join();
1803 }
1804 void handleOne(android::base::unique_fd acceptedFd) {
1805 ASSERT_TRUE(acceptedFd.ok());
1806 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1807 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001808 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001809 }
Yifan Honge07d2732021-09-13 21:59:14 -07001810 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001811 shutdown();
1812 join();
1813 }
1814 void shutdown() { mFdTrigger->trigger(); }
1815
1816 void setPostConnect(
1817 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1818 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001819 }
1820
1821 private:
1822 std::unique_ptr<std::thread> mThread;
1823 ConnectToServer mConnectToServer;
1824 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1825 base::unique_fd mFd;
1826 std::unique_ptr<RpcTransportCtx> mCtx;
1827 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1828 std::make_shared<RpcCertificateVerifierSimple>();
1829 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001830 // The function invoked after connection and handshake. By default, it is
1831 // |defaultPostConnect| that sends |kMessage| to the client.
1832 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1833 Server::defaultPostConnect;
1834
1835 void join() {
1836 if (mThread != nullptr) {
1837 mThread->join();
1838 mThread = nullptr;
1839 }
1840 }
1841
1842 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1843 FdTrigger* fdTrigger) {
1844 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001845 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001846 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001847 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001848 if (status != OK) return AssertionFailure() << statusToString(status);
1849 return AssertionSuccess();
1850 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001851 };
1852
1853 class Client {
1854 public:
1855 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1856 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001857 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001858 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1859 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001860 mFdTrigger = FdTrigger::make();
1861 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1862 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1863 return AssertionSuccess();
1864 }
1865 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1866 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1867 return mCertVerifier;
1868 }
Yifan Hong67519322021-09-13 18:51:16 -07001869 // connect() and do handshake
1870 bool setUpTransport() {
1871 mFd = mConnectToServer();
1872 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1873 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1874 return mClientTransport != nullptr;
1875 }
1876 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1877 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1878 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001879 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001880 status_t readStatus =
1881 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001882 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001883 if (readStatus != OK) {
1884 return AssertionFailure() << statusToString(readStatus);
1885 }
1886 if (readMessage != expectedMessage) {
1887 return AssertionFailure()
1888 << "Expected " << expectedMessage << ", actual " << readMessage;
1889 }
1890 return AssertionSuccess();
1891 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001892 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001893 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001894 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1895 return;
1896 }
1897 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001898 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001899 }
1900
1901 private:
1902 ConnectToServer mConnectToServer;
1903 base::unique_fd mFd;
1904 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1905 std::unique_ptr<RpcTransportCtx> mCtx;
1906 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1907 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001908 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001909 };
1910
1911 // Make A trust B.
1912 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001913 static status_t trust(RpcSecurity rpcSecurity,
1914 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1915 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001916 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001917 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1918 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1919 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001920 }
1921
1922 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001923};
1924
1925class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1926public:
1927 using Server = RpcTransportTestUtils::Server;
1928 using Client = RpcTransportTestUtils::Client;
1929 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001930 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001931 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1932 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001933 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001934 return ret;
1935 }
1936 static std::vector<ParamType> getRpcTranportTestParams() {
1937 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001938 for (auto serverVersion : testVersions()) {
1939 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1940 for (auto rpcSecurity : RpcSecurityValues()) {
1941 switch (rpcSecurity) {
1942 case RpcSecurity::RAW: {
1943 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1944 } break;
1945 case RpcSecurity::TLS: {
1946 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1947 serverVersion);
1948 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1949 serverVersion);
1950 } break;
1951 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001952 }
1953 }
1954 }
1955 return ret;
1956 }
1957 template <typename A, typename B>
1958 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001959 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1960 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001961 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1962 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001963 void SetUp() override {
1964 if constexpr (!kEnableRpcThreads) {
1965 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1966 }
1967 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001968};
1969
1970TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001971 auto server = std::make_unique<Server>();
1972 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001973
1974 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001975 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001976
1977 ASSERT_EQ(OK, trust(&client, server));
1978 ASSERT_EQ(OK, trust(server, &client));
1979
1980 server->start();
1981 client.run();
1982}
1983
1984TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001985 auto server = std::make_unique<Server>();
1986 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001987
1988 std::vector<Client> clients;
1989 for (int i = 0; i < 2; i++) {
1990 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001991 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001992 ASSERT_EQ(OK, trust(&client, server));
1993 ASSERT_EQ(OK, trust(server, &client));
1994 }
1995
1996 server->start();
1997 for (auto& client : clients) client.run();
1998}
1999
2000TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002001 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2002 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002003
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002004 auto untrustedServer = std::make_unique<Server>();
2005 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002006
2007 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002008 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002009
2010 ASSERT_EQ(OK, trust(untrustedServer, &client));
2011
2012 untrustedServer->start();
2013
2014 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2015 // the client can't verify the server's identity.
2016 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2017 client.run(handshakeOk);
2018}
2019TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002020 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2021 (void)serverVersion;
2022
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002023 auto validServer = std::make_unique<Server>();
2024 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002025
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002026 auto maliciousServer = std::make_unique<Server>();
2027 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002028
2029 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002030 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002031
2032 ASSERT_EQ(OK, trust(&client, validServer));
2033 ASSERT_EQ(OK, trust(validServer, &client));
2034 ASSERT_EQ(OK, trust(maliciousServer, &client));
2035
2036 maliciousServer->start();
2037
2038 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2039 // the client can't verify the server's identity.
2040 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2041 client.run(handshakeOk);
2042}
2043
2044TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002045 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2046 (void)serverVersion;
2047
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002048 auto server = std::make_unique<Server>();
2049 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002050
2051 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002052 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002053
2054 ASSERT_EQ(OK, trust(&client, server));
2055
2056 server->start();
2057
2058 // For TLS, Client should be able to verify server's identity, so client should see
2059 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2060 // identity and should drop the connection, so client shouldn't be able to read anything.
2061 bool readOk = rpcSecurity != RpcSecurity::TLS;
2062 client.run(true, readOk);
2063}
2064
2065TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002066 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2067 (void)serverVersion;
2068
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002069 auto server = std::make_unique<Server>();
2070 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002071
2072 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002073 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002074 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002075 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002076
2077 ASSERT_EQ(OK, trust(&validClient, server));
2078 ASSERT_EQ(OK, trust(&maliciousClient, server));
2079
2080 server->start();
2081
2082 // See UntrustedClient.
2083 bool readOk = rpcSecurity != RpcSecurity::TLS;
2084 maliciousClient.run(true, readOk);
2085}
2086
Yifan Hong67519322021-09-13 18:51:16 -07002087TEST_P(RpcTransportTest, Trigger) {
2088 std::string msg2 = ", world!";
2089 std::mutex writeMutex;
2090 std::condition_variable writeCv;
2091 bool shouldContinueWriting = false;
2092 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002093 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002094 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002095 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2096 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002097 if (status != OK) return AssertionFailure() << statusToString(status);
2098
2099 {
2100 std::unique_lock<std::mutex> lock(writeMutex);
2101 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2102 return AssertionFailure() << "write barrier not cleared in time!";
2103 }
2104 }
2105
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002106 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002107 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2108 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002109 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002110 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002111 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002112 << statusToString(status);
2113 return AssertionSuccess();
2114 };
2115
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002116 auto server = std::make_unique<Server>();
2117 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002118
2119 // Set up client
2120 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002121 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002122
2123 // Exchange keys
2124 ASSERT_EQ(OK, trust(&client, server));
2125 ASSERT_EQ(OK, trust(server, &client));
2126
2127 server->setPostConnect(serverPostConnect);
2128
Yifan Hong67519322021-09-13 18:51:16 -07002129 server->start();
2130 // connect() to server and do handshake
2131 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002132 // read the first message. This ensures that server has finished handshake and start handling
2133 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002134 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002135 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2136 // write is on an FdTrigger that has been shut down.
2137 server->shutdown();
2138 // Continues server thread to write the second message.
2139 {
Yifan Hong22211f82021-09-14 12:32:25 -07002140 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002141 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002142 }
Yifan Hong22211f82021-09-14 12:32:25 -07002143 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002144 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002145 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002146 // On the client side, second read fails with DEAD_OBJECT
2147 ASSERT_FALSE(client.readMessage(msg2));
2148}
2149
Yifan Hong1deca4b2021-09-10 16:16:44 -07002150INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002151 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002152 RpcTransportTest::PrintParamInfo);
2153
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002154class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002155 : public testing::TestWithParam<
2156 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002157public:
2158 template <typename A, typename B>
2159 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002160 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2161 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002162 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2163 }
2164 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002165 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2166 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2167 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002168 };
2169};
2170
2171TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002172 if constexpr (!kEnableRpcThreads) {
2173 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2174 }
2175
Frederick Mayledc07cf82022-05-26 20:30:12 +00002176 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002177
2178 std::vector<uint8_t> pkeyData, certData;
2179 {
2180 auto pkey = makeKeyPairForSelfSignedCert();
2181 ASSERT_NE(nullptr, pkey);
2182 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2183 ASSERT_NE(nullptr, cert);
2184 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2185 certData = serializeCertificate(cert.get(), certificateFormat);
2186 }
2187
2188 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2189 auto desCert = deserializeCertificate(certData, certificateFormat);
2190 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002191 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2192 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002193
2194 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2195 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2196
2197 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2198 ASSERT_TRUE(client.setUp(utilsParam));
2199
2200 ASSERT_EQ(OK, trust(&client, server));
2201 ASSERT_EQ(OK, trust(server, &client));
2202
2203 server->start();
2204 client.run();
2205}
2206
2207INSTANTIATE_TEST_CASE_P(
2208 BinderRpc, RpcTransportTlsKeyTest,
2209 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2210 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002211 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2212 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002213 RpcTransportTlsKeyTest::PrintParamInfo);
2214
Steven Morelandc1635952021-04-01 16:20:47 +00002215} // namespace android
2216
2217int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002218 ::testing::InitGoogleTest(&argc, argv);
2219 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002220
Steven Moreland5553ac42020-11-11 02:14:45 +00002221 return RUN_ALL_TESTS();
2222}