blob: 87c204f9e31d4bd92077ed404e207667312db742 [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Frederick Maylea12b0962022-06-25 01:13:22 +000017#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000018#include <gtest/gtest.h>
19
Steven Morelandc1635952021-04-01 16:20:47 +000020#include <chrono>
21#include <cstdlib>
22#include <iostream>
23#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000024#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000025
Andrei Homescu2a298012022-06-15 01:08:54 +000026#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070027#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000029#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000030
Andrei Homescu2a298012022-06-15 01:08:54 +000031#include "binderRpcTestCommon.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000032
Yifan Hong1a235852021-05-13 16:07:47 -070033using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070034using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070035using testing::AssertionFailure;
36using testing::AssertionResult;
37using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070038
Steven Moreland5553ac42020-11-11 02:14:45 +000039namespace android {
40
Andrei Homescu12106de2022-04-27 04:42:21 +000041#ifdef BINDER_TEST_NO_SHARED_LIBS
42constexpr bool kEnableSharedLibs = false;
43#else
44constexpr bool kEnableSharedLibs = true;
45#endif
46
Steven Morelandbf57bce2021-07-26 15:26:12 -070047static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
48 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Frederick Mayle69a0c992022-05-26 20:38:39 +000049
Steven Moreland1fda67b2021-04-02 18:35:50 +000050TEST(BinderRpcParcel, EntireParcelFormatted) {
51 Parcel p;
52 p.writeInt32(3);
53
Devin Moore66d5b7a2022-07-07 21:42:10 +000054 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "format must be set before data is written");
Steven Moreland1fda67b2021-04-02 18:35:50 +000055}
56
Frederick Mayledc07cf82022-05-26 20:30:12 +000057class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
Yifan Hong702115c2021-06-24 15:39:18 -070058public:
59 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +000060 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
61 std::to_string(std::get<1>(info.param));
Yifan Hong702115c2021-06-24 15:39:18 -070062 }
63};
64
Frederick Mayledc07cf82022-05-26 20:30:12 +000065TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -070066 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
67 int sinkFd = sink.get();
Frederick Mayledc07cf82022-05-26 20:30:12 +000068 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
69 server->setProtocolVersion(std::get<1>(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -070070 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -070071 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -070072 ASSERT_TRUE(server->hasServer());
73 base::unique_fd retrieved = server->releaseServer();
74 ASSERT_FALSE(server->hasServer());
75 ASSERT_EQ(sinkFd, retrieved.get());
76}
77
Steven Morelandbf57bce2021-07-26 15:26:12 -070078TEST(BinderRpc, CannotUseNextWireVersion) {
79 auto session = RpcSession::make();
80 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
81 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
82 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
83 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
84}
85
86TEST(BinderRpc, CanUseExperimentalWireVersion) {
87 auto session = RpcSession::make();
88 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
89}
90
Steven Moreland5553ac42020-11-11 02:14:45 +000091using android::binder::Status;
92
93#define EXPECT_OK(status) \
94 do { \
95 Status stat = (status); \
96 EXPECT_TRUE(stat.isOk()) << stat; \
97 } while (false)
98
Frederick Maylea12b0962022-06-25 01:13:22 +000099static std::string WaitStatusToString(int wstatus) {
100 if (WIFEXITED(wstatus)) {
101 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
102 }
103 if (WIFSIGNALED(wstatus)) {
104 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
105 }
106 return base::StringPrintf("unexpected state %d", wstatus);
107}
108
Steven Moreland5553ac42020-11-11 02:14:45 +0000109class Process {
110public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700111 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700112 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
113 android::base::borrowed_fd /* readEnd */)>& f) {
114 android::base::unique_fd childWriteEnd;
115 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +0000116 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
117 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000118 if (0 == (mPid = fork())) {
119 // racey: assume parent doesn't crash before this is set
120 prctl(PR_SET_PDEATHSIG, SIGHUP);
121
Yifan Hong1deca4b2021-09-10 16:16:44 -0700122 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000123
124 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000125 }
126 }
127 ~Process() {
128 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000129 int wstatus;
130 waitpid(mPid, &wstatus, 0);
131 if (mCustomExitStatusCheck) {
132 mCustomExitStatusCheck(wstatus);
133 } else {
134 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
135 << "server process failed: " << WaitStatusToString(wstatus);
136 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000137 }
138 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700139 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700140 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000141
Frederick Maylea12b0962022-06-25 01:13:22 +0000142 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
143 mCustomExitStatusCheck = std::move(f);
144 }
145
Frederick Mayle69a0c992022-05-26 20:38:39 +0000146 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
147 void terminate() { kill(mPid, SIGTERM); }
148
Steven Moreland5553ac42020-11-11 02:14:45 +0000149private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000150 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000151 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700152 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700153 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000154};
155
156static std::string allocateSocketAddress() {
157 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000158 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700159 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
160 unlink(ret.c_str());
161 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000162};
163
Steven Morelandda573042021-06-12 01:13:45 +0000164static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000165 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000166 return vsockPort++;
167}
168
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000169struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000170 // reference to process hosting a socket server
171 Process host;
172
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000173 struct SessionInfo {
174 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000175 sp<IBinder> root;
176 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000177
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000178 // client session objects associated with other process
179 // each one represents a separate session
180 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000181
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000182 ProcessSession(ProcessSession&&) = default;
183 ~ProcessSession() {
184 for (auto& session : sessions) {
185 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000186 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000187
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000188 for (auto& info : sessions) {
189 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000190
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000191 EXPECT_NE(nullptr, session);
192 EXPECT_NE(nullptr, session->state());
193 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000194
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000195 wp<RpcSession> weakSession = session;
196 session = nullptr;
197 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000198 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000199 }
200};
201
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000202// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000203// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000204struct BinderRpcTestProcessSession {
205 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000206
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000207 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000208 sp<IBinder> rootBinder;
209
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000210 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000211 sp<IBinderRpcTest> rootIface;
212
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000213 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000214 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000215
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000216 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
217 ~BinderRpcTestProcessSession() {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000218 if (!expectAlreadyShutdown) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000219 EXPECT_NE(nullptr, rootIface);
220 if (rootIface == nullptr) return;
221
Steven Moreland736664b2021-05-01 04:27:25 +0000222 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000223 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000224 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000225 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000226 for (auto remoteCount : remoteCounts) {
227 EXPECT_EQ(remoteCount, 1);
228 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000229
Steven Moreland798e0d12021-07-14 23:19:25 +0000230 // even though it is on another thread, shutdown races with
231 // the transaction reply being written
232 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
233 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
234 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000235 }
236
237 rootIface = nullptr;
238 rootBinder = nullptr;
239 }
240};
241
Yifan Hong1deca4b2021-09-10 16:16:44 -0700242static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700243 base::unique_fd serverFd(
244 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
245 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700246 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
247 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700248
249 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
250 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700251 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
252 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700253 }
254 return serverFd;
255}
256
Andrei Homescu2a298012022-06-15 01:08:54 +0000257using RunServiceFn = void (*)(android::base::borrowed_fd writeEnd,
258 android::base::borrowed_fd readEnd);
259
260class BinderRpc : public ::testing::TestWithParam<
261 std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t, bool, bool>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000262public:
Frederick Mayle69a0c992022-05-26 20:38:39 +0000263 SocketType socketType() const { return std::get<0>(GetParam()); }
264 RpcSecurity rpcSecurity() const { return std::get<1>(GetParam()); }
265 uint32_t clientVersion() const { return std::get<2>(GetParam()); }
266 uint32_t serverVersion() const { return std::get<3>(GetParam()); }
Andrei Homescu2a298012022-06-15 01:08:54 +0000267 bool singleThreaded() const { return std::get<4>(GetParam()); }
268 bool noKernel() const { return std::get<5>(GetParam()); }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000269
270 // Whether the test params support sending FDs in parcels.
271 bool supportsFdTransport() const {
272 return clientVersion() >= 1 && serverVersion() >= 1 && rpcSecurity() != RpcSecurity::TLS &&
273 (socketType() == SocketType::PRECONNECTED || socketType() == SocketType::UNIX);
274 }
275
Yifan Hong702115c2021-06-24 15:39:18 -0700276 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000277 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
278 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
Frederick Mayledc07cf82022-05-26 20:30:12 +0000279 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Andrei Homescu2a298012022-06-15 01:08:54 +0000280 if (singleThreaded) {
281 ret += "_single_threaded";
282 }
283 if (noKernel) {
284 ret += "_no_kernel";
285 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700286 return ret;
287 }
288
Steven Morelandc1635952021-04-01 16:20:47 +0000289 // This creates a new process serving an interface on a certain number of
290 // threads.
Andrei Homescu2a298012022-06-15 01:08:54 +0000291 ProcessSession createRpcTestSocketServerProcessEtc(const BinderRpcOptions& options) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000292 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000293
Yifan Hong702115c2021-06-24 15:39:18 -0700294 SocketType socketType = std::get<0>(GetParam());
295 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000296 uint32_t clientVersion = std::get<2>(GetParam());
297 uint32_t serverVersion = std::get<3>(GetParam());
Andrei Homescu2a298012022-06-15 01:08:54 +0000298 bool singleThreaded = std::get<4>(GetParam());
299 bool noKernel = std::get<5>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000300
Andrei Homescu2a298012022-06-15 01:08:54 +0000301 std::string path = android::base::GetExecutableDirectory();
302 auto servicePath =
303 android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
304 singleThreaded ? "_single_threaded" : "",
305 noKernel ? "_no_kernel" : "");
Steven Morelandc1635952021-04-01 16:20:47 +0000306
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000307 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000308 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700309 android::base::borrowed_fd readEnd) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000310 auto writeFd = std::to_string(writeEnd.get());
311 auto readFd = std::to_string(readEnd.get());
312 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
313 NULL);
Steven Morelandc1635952021-04-01 16:20:47 +0000314 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000315 };
316
Andrei Homescu2a298012022-06-15 01:08:54 +0000317 BinderRpcTestServerConfig serverConfig;
318 serverConfig.numThreads = options.numThreads;
319 serverConfig.socketType = static_cast<int32_t>(socketType);
320 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
321 serverConfig.serverVersion = serverVersion;
322 serverConfig.vsockPort = allocateVsockPort();
323 serverConfig.addr = allocateSocketAddress();
324 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
325 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
326 static_cast<int32_t>(mode));
327 }
328 writeToFd(ret.host.writeEnd(), serverConfig);
329
Yifan Hong1deca4b2021-09-10 16:16:44 -0700330 std::vector<sp<RpcSession>> sessions;
331 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
332 for (size_t i = 0; i < options.numSessions; i++) {
333 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
334 }
335
336 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
337 BinderRpcTestClientInfo clientInfo;
338 for (const auto& session : sessions) {
339 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700340 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700341 }
342 writeToFd(ret.host.writeEnd(), clientInfo);
343
344 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700345 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700346 CHECK_NE(0, serverInfo.port);
347 }
348
349 if (rpcSecurity == RpcSecurity::TLS) {
350 const auto& serverCert = serverInfo.cert.data;
351 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700352 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
353 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700354 }
355
Steven Moreland2372f9d2021-08-05 15:42:01 -0700356 status_t status;
357
Yifan Hong1deca4b2021-09-10 16:16:44 -0700358 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000359 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700360 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700361 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000362 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Moreland659416d2021-05-11 00:47:50 +0000363
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000364 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700365 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700366 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000367 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700368 });
Steven Moreland4198a122021-08-03 17:37:58 -0700369 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000370 case SocketType::UNIX:
Andrei Homescu2a298012022-06-15 01:08:54 +0000371 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000372 break;
373 case SocketType::VSOCK:
Andrei Homescu2a298012022-06-15 01:08:54 +0000374 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000375 break;
376 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700377 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000378 break;
379 default:
380 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000381 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000382 if (options.allowConnectFailure && status != OK) {
383 ret.sessions.clear();
384 break;
385 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700386 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000387 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000388 }
Steven Morelandc1635952021-04-01 16:20:47 +0000389 return ret;
390 }
391
Andrei Homescu2a298012022-06-15 01:08:54 +0000392 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const BinderRpcOptions& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000393 BinderRpcTestProcessSession ret{
Andrei Homescu2a298012022-06-15 01:08:54 +0000394 .proc = createRpcTestSocketServerProcessEtc(options),
Steven Morelandc1635952021-04-01 16:20:47 +0000395 };
396
Frederick Mayle69a0c992022-05-26 20:38:39 +0000397 ret.rootBinder = ret.proc.sessions.empty() ? nullptr : ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000398 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
399
400 return ret;
401 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700402
403 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
404 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000405};
406
Andrei Homescu12106de2022-04-27 04:42:21 +0000407// Test fixture for tests that start multiple threads.
408// This includes tests with one thread but multiple sessions,
409// since a server uses one thread per session.
410class BinderRpcThreads : public BinderRpc {
411public:
412 void SetUp() override {
413 if constexpr (!kEnableRpcThreads) {
414 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
415 }
416 }
417};
418
Steven Morelandc1635952021-04-01 16:20:47 +0000419TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000420 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000421 ASSERT_NE(proc.rootBinder, nullptr);
422 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
423}
424
Steven Moreland4cf688f2021-03-31 01:48:58 +0000425TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000426 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000427 ASSERT_NE(proc.rootBinder, nullptr);
428 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
429}
430
Andrei Homescu12106de2022-04-27 04:42:21 +0000431TEST_P(BinderRpcThreads, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000432 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000433 for (auto session : proc.proc.sessions) {
434 ASSERT_NE(nullptr, session.root);
435 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000436 }
437}
438
Andrei Homescu12106de2022-04-27 04:42:21 +0000439TEST_P(BinderRpcThreads, SeparateRootObject) {
Steven Moreland51c44a92021-10-14 16:50:35 -0700440 SocketType type = std::get<0>(GetParam());
441 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
442 // we can't get port numbers for unix sockets
443 return;
444 }
445
446 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
447
448 int port1 = 0;
449 EXPECT_OK(proc.rootIface->getClientPort(&port1));
450
451 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
452 int port2;
453 EXPECT_OK(rootIface2->getClientPort(&port2));
454
455 // we should have a different IBinderRpcTest object created for each
456 // session, because we use setPerSessionRootObject
457 EXPECT_NE(port1, port2);
458}
459
Steven Morelandc1635952021-04-01 16:20:47 +0000460TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000461 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000462 Parcel data;
463 Parcel reply;
464 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
465}
466
Steven Moreland67753c32021-04-02 18:45:19 +0000467TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700468 auto proc1 = createRpcTestSocketServerProcess({});
469 auto proc2 = createRpcTestSocketServerProcess({});
470
471 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000472
473 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700474 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000475 p1.writeInt32(3);
476
Frederick Maylea4ed5672022-06-17 22:03:38 +0000477 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700478 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
479
Steven Moreland67753c32021-04-02 18:45:19 +0000480 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700481 p2.markForBinder(proc2.rootBinder);
482 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000483
484 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
485 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
486}
487
Steven Morelandc1635952021-04-01 16:20:47 +0000488TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000489 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000490 Parcel data;
491 data.markForBinder(proc.rootBinder);
492 Parcel reply;
493 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
494}
495
Steven Morelandc1635952021-04-01 16:20:47 +0000496TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000497 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000498 EXPECT_OK(proc.rootIface->sendString("asdf"));
499}
500
Steven Morelandc1635952021-04-01 16:20:47 +0000501TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000502 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000503 std::string doubled;
504 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
505 EXPECT_EQ("cool cool ", doubled);
506}
507
Steven Morelandc1635952021-04-01 16:20:47 +0000508TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000509 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000510 std::string single = std::string(1024, 'a');
511 std::string doubled;
512 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
513 EXPECT_EQ(single + single, doubled);
514}
515
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000516TEST_P(BinderRpc, InvalidNullBinderReturn) {
517 auto proc = createRpcTestSocketServerProcess({});
518
519 sp<IBinder> outBinder;
520 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
521}
522
Steven Morelandc1635952021-04-01 16:20:47 +0000523TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000524 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000525
526 int32_t pingResult;
527 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
528 EXPECT_EQ(OK, pingResult);
529
530 EXPECT_EQ(0, MyBinderRpcSession::gNum);
531}
532
Steven Morelandc1635952021-04-01 16:20:47 +0000533TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000534 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000535
536 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
537 sp<IBinder> outBinder;
538 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
539 EXPECT_EQ(inBinder, outBinder);
540
541 wp<IBinder> weak = inBinder;
542 inBinder = nullptr;
543 outBinder = nullptr;
544
545 // Force reading a reply, to process any pending dec refs from the other
546 // process (the other process will process dec refs there before processing
547 // the ping here).
548 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
549
550 EXPECT_EQ(nullptr, weak.promote());
551
552 EXPECT_EQ(0, MyBinderRpcSession::gNum);
553}
554
Steven Morelandc1635952021-04-01 16:20:47 +0000555TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000556 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000557
558 sp<IBinderRpcSession> session;
559 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
560
561 sp<IBinder> inBinder = IInterface::asBinder(session);
562 sp<IBinder> outBinder;
563 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
564 EXPECT_EQ(inBinder, outBinder);
565
566 wp<IBinder> weak = inBinder;
567 session = nullptr;
568 inBinder = nullptr;
569 outBinder = nullptr;
570
571 // Force reading a reply, to process any pending dec refs from the other
572 // process (the other process will process dec refs there before processing
573 // the ping here).
574 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
575
576 EXPECT_EQ(nullptr, weak.promote());
577}
578
Steven Morelandc1635952021-04-01 16:20:47 +0000579TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000580 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000581
582 sp<IBinder> outBinder;
583 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
584 EXPECT_EQ(nullptr, outBinder);
585}
586
Steven Morelandc1635952021-04-01 16:20:47 +0000587TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000588 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000589
590 IBinder* ptr = nullptr;
591 {
592 sp<IBinder> binder = new BBinder();
593 ptr = binder.get();
594 EXPECT_OK(proc.rootIface->holdBinder(binder));
595 }
596
597 sp<IBinder> held;
598 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
599
600 EXPECT_EQ(held.get(), ptr);
601
602 // stop holding binder, because we test to make sure references are cleaned
603 // up
604 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
605 // and flush ref counts
606 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
607}
608
609// START TESTS FOR LIMITATIONS OF SOCKET BINDER
610// These are behavioral differences form regular binder, where certain usecases
611// aren't supported.
612
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000613TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000614 auto proc1 = createRpcTestSocketServerProcess({});
615 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000616
617 sp<IBinder> outBinder;
618 EXPECT_EQ(INVALID_OPERATION,
619 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
620}
621
Andrei Homescu12106de2022-04-27 04:42:21 +0000622TEST_P(BinderRpcThreads, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000623 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000624
625 sp<IBinder> outBinder;
626 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000627 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000628 .transactionError());
629}
630
Steven Morelandc1635952021-04-01 16:20:47 +0000631TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000632 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000633 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
634 "at build time.";
635 }
636
Steven Moreland4313d7e2021-07-15 23:41:22 +0000637 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000638
639 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
640 sp<IBinder> outBinder;
641 EXPECT_EQ(INVALID_OPERATION,
642 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
643}
644
Steven Morelandc1635952021-04-01 16:20:47 +0000645TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000646 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000647 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
648 "at build time.";
649 }
650
Steven Moreland4313d7e2021-07-15 23:41:22 +0000651 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000652
653 // for historical reasons, IServiceManager interface only returns the
654 // exception code
655 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
656 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
657}
658
659// END TESTS FOR LIMITATIONS OF SOCKET BINDER
660
Steven Morelandc1635952021-04-01 16:20:47 +0000661TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000662 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000663
664 sp<IBinder> outBinder;
665 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
666 EXPECT_EQ(proc.rootBinder, outBinder);
667}
668
Steven Morelandc1635952021-04-01 16:20:47 +0000669TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000670 auto proc = createRpcTestSocketServerProcess({
671 // Enable FD support because it uses more stack space and so represents
672 // something closer to a worst case scenario.
673 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
674 .serverSupportedFileDescriptorTransportModes =
675 {RpcSession::FileDescriptorTransportMode::UNIX},
676 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000677
678 auto nastyNester = sp<MyBinderRpcTest>::make();
679 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
680
681 wp<IBinder> weak = nastyNester;
682 nastyNester = nullptr;
683 EXPECT_EQ(nullptr, weak.promote());
684}
685
Steven Morelandc1635952021-04-01 16:20:47 +0000686TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000687 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000688
689 sp<IBinder> a;
690 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
691
692 sp<IBinder> b;
693 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
694
695 EXPECT_EQ(a, b);
696}
697
Steven Morelandc1635952021-04-01 16:20:47 +0000698TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000699 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000700
701 sp<IBinder> a;
702 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
703 wp<IBinder> weak = a;
704 a = nullptr;
705
706 sp<IBinder> b;
707 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
708
709 // this is the wrong behavior, since BpBinder
710 // doesn't implement onIncStrongAttempted
711 // but make sure there is no crash
712 EXPECT_EQ(nullptr, weak.promote());
713
714 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
715
716 // In order to fix this:
717 // - need to have incStrongAttempted reflected across IPC boundary (wait for
718 // response to promote - round trip...)
719 // - sendOnLastWeakRef, to delete entries out of RpcState table
720 EXPECT_EQ(b, weak.promote());
721}
722
723#define expectSessions(expected, iface) \
724 do { \
725 int session; \
726 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
727 EXPECT_EQ(expected, session); \
728 } while (false)
729
Steven Morelandc1635952021-04-01 16:20:47 +0000730TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000731 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000732
733 sp<IBinderRpcSession> session;
734 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
735 std::string out;
736 EXPECT_OK(session->getName(&out));
737 EXPECT_EQ("aoeu", out);
738
739 expectSessions(1, proc.rootIface);
740 session = nullptr;
741 expectSessions(0, proc.rootIface);
742}
743
Steven Morelandc1635952021-04-01 16:20:47 +0000744TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000745 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000746
747 std::vector<sp<IBinderRpcSession>> sessions;
748
749 for (size_t i = 0; i < 15; i++) {
750 expectSessions(i, proc.rootIface);
751 sp<IBinderRpcSession> session;
752 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
753 sessions.push_back(session);
754 }
755 expectSessions(sessions.size(), proc.rootIface);
756 for (size_t i = 0; i < sessions.size(); i++) {
757 std::string out;
758 EXPECT_OK(sessions.at(i)->getName(&out));
759 EXPECT_EQ(std::to_string(i), out);
760 }
761 expectSessions(sessions.size(), proc.rootIface);
762
763 while (!sessions.empty()) {
764 sessions.pop_back();
765 expectSessions(sessions.size(), proc.rootIface);
766 }
767 expectSessions(0, proc.rootIface);
768}
769
770size_t epochMillis() {
771 using std::chrono::duration_cast;
772 using std::chrono::milliseconds;
773 using std::chrono::seconds;
774 using std::chrono::system_clock;
775 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
776}
777
Andrei Homescu12106de2022-04-27 04:42:21 +0000778TEST_P(BinderRpcThreads, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000779 constexpr size_t kNumThreads = 10;
780
Steven Moreland4313d7e2021-07-15 23:41:22 +0000781 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000782
783 EXPECT_OK(proc.rootIface->lock());
784
785 // block all but one thread taking locks
786 std::vector<std::thread> ts;
787 for (size_t i = 0; i < kNumThreads - 1; i++) {
788 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
789 }
790
791 usleep(100000); // give chance for calls on other threads
792
793 // other calls still work
794 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
795
796 constexpr size_t blockTimeMs = 500;
797 size_t epochMsBefore = epochMillis();
798 // after this, we should never see a response within this time
799 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
800
801 // this call should be blocked for blockTimeMs
802 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
803
804 size_t epochMsAfter = epochMillis();
805 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
806
807 for (auto& t : ts) t.join();
808}
809
Yifan Hong1f44f982021-10-08 17:16:47 -0700810void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
811 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000812 size_t epochMsBefore = epochMillis();
813
814 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700815 for (size_t i = 0; i < numCalls; i++) {
816 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000817 }
818
819 for (auto& t : ts) t.join();
820
821 size_t epochMsAfter = epochMillis();
822
Yifan Hong1f44f982021-10-08 17:16:47 -0700823 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000824
825 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700826 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
827}
828
Andrei Homescu12106de2022-04-27 04:42:21 +0000829TEST_P(BinderRpcThreads, ThreadPoolOverSaturated) {
Yifan Hong1f44f982021-10-08 17:16:47 -0700830 constexpr size_t kNumThreads = 10;
831 constexpr size_t kNumCalls = kNumThreads + 3;
832 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
833 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
834}
835
Andrei Homescu12106de2022-04-27 04:42:21 +0000836TEST_P(BinderRpcThreads, ThreadPoolLimitOutgoing) {
Yifan Hong1f44f982021-10-08 17:16:47 -0700837 constexpr size_t kNumThreads = 20;
838 constexpr size_t kNumOutgoingConnections = 10;
839 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
840 auto proc = createRpcTestSocketServerProcess(
841 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
842 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000843}
844
Andrei Homescu12106de2022-04-27 04:42:21 +0000845TEST_P(BinderRpcThreads, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000846 constexpr size_t kNumClientThreads = 10;
847 constexpr size_t kNumServerThreads = 10;
848 constexpr size_t kNumCalls = 100;
849
Steven Moreland4313d7e2021-07-15 23:41:22 +0000850 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000851
852 std::vector<std::thread> threads;
853 for (size_t i = 0; i < kNumClientThreads; i++) {
854 threads.push_back(std::thread([&] {
855 for (size_t j = 0; j < kNumCalls; j++) {
856 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000857 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000858 EXPECT_EQ(proc.rootBinder, out);
859 }
860 }));
861 }
862
863 for (auto& t : threads) t.join();
864}
865
Steven Moreland925ba0a2021-09-17 18:06:32 -0700866static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
867 std::vector<std::thread> threads;
868 for (size_t i = 0; i < threadCount; i++) {
869 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
870 }
871 for (auto& t : threads) t.join();
872}
873
Andrei Homescu12106de2022-04-27 04:42:21 +0000874TEST_P(BinderRpcThreads, OnewayStressTest) {
Steven Morelandc6046982021-04-20 00:49:42 +0000875 constexpr size_t kNumClientThreads = 10;
876 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700877 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000878
Steven Moreland4313d7e2021-07-15 23:41:22 +0000879 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000880
881 std::vector<std::thread> threads;
882 for (size_t i = 0; i < kNumClientThreads; i++) {
883 threads.push_back(std::thread([&] {
884 for (size_t j = 0; j < kNumCalls; j++) {
885 EXPECT_OK(proc.rootIface->sendString("a"));
886 }
Steven Morelandc6046982021-04-20 00:49:42 +0000887 }));
888 }
889
890 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700891
892 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000893}
894
Steven Morelandc1635952021-04-01 16:20:47 +0000895TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000896 constexpr size_t kReallyLongTimeMs = 100;
897 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
898
Steven Moreland4313d7e2021-07-15 23:41:22 +0000899 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000900
901 size_t epochMsBefore = epochMillis();
902
903 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
904
905 size_t epochMsAfter = epochMillis();
906 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
907}
908
Andrei Homescu12106de2022-04-27 04:42:21 +0000909TEST_P(BinderRpcThreads, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000910 constexpr size_t kNumSleeps = 10;
911 constexpr size_t kNumExtraServerThreads = 4;
912 constexpr size_t kSleepMs = 50;
913
914 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000915 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000916
917 EXPECT_OK(proc.rootIface->lock());
918
Steven Moreland1c678802021-09-17 16:48:47 -0700919 size_t epochMsBefore = epochMillis();
920
921 // all these *Async commands should be queued on the server sequentially,
922 // even though there are multiple threads.
923 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000924 proc.rootIface->sleepMsAsync(kSleepMs);
925 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000926 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
927
Steven Moreland1c678802021-09-17 16:48:47 -0700928 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000929 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700930
Steven Moreland5553ac42020-11-11 02:14:45 +0000931 size_t epochMsAfter = epochMillis();
932
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000933 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000934
Steven Moreland925ba0a2021-09-17 18:06:32 -0700935 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000936}
937
Andrei Homescu12106de2022-04-27 04:42:21 +0000938TEST_P(BinderRpcThreads, OnewayCallExhaustion) {
Steven Morelandd45be622021-06-04 02:19:37 +0000939 constexpr size_t kNumClients = 2;
940 constexpr size_t kTooLongMs = 1000;
941
Steven Moreland4313d7e2021-07-15 23:41:22 +0000942 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000943
944 // Build up oneway calls on the second session to make sure it terminates
945 // and shuts down. The first session should be unaffected (proc destructor
946 // checks the first session).
947 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
948
949 std::vector<std::thread> threads;
950 for (size_t i = 0; i < kNumClients; i++) {
951 // one of these threads will get stuck queueing a transaction once the
952 // socket fills up, the other will be able to fill up transactions on
953 // this object
954 threads.push_back(std::thread([&] {
955 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
956 }
957 }));
958 }
959 for (auto& t : threads) t.join();
960
961 Status status = iface->sleepMsAsync(kTooLongMs);
962 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
963
Steven Moreland798e0d12021-07-14 23:19:25 +0000964 // now that it has died, wait for the remote session to shutdown
965 std::vector<int32_t> remoteCounts;
966 do {
967 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
968 } while (remoteCounts.size() == kNumClients);
969
Steven Morelandd45be622021-06-04 02:19:37 +0000970 // the second session should be shutdown in the other process by the time we
971 // are able to join above (it'll only be hung up once it finishes processing
972 // any pending commands). We need to erase this session from the record
973 // here, so that the destructor for our session won't check that this
974 // session is valid, but we still want it to test the other session.
975 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
976}
977
Steven Moreland659416d2021-05-11 00:47:50 +0000978TEST_P(BinderRpc, Callbacks) {
979 const static std::string kTestString = "good afternoon!";
980
Andrei Homescu2a298012022-06-15 01:08:54 +0000981 bool bothSingleThreaded = !kEnableRpcThreads || singleThreaded();
982
Steven Morelandc7d40132021-06-10 03:42:11 +0000983 for (bool callIsOneway : {true, false}) {
984 for (bool callbackIsOneway : {true, false}) {
985 for (bool delayed : {true, false}) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000986 if (bothSingleThreaded && (callIsOneway || callbackIsOneway || delayed)) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000987 // we have no incoming connections to receive the callback
988 continue;
989 }
990
Andrei Homescu2a298012022-06-15 01:08:54 +0000991 size_t numIncomingConnections = bothSingleThreaded ? 0 : 1;
Steven Moreland4313d7e2021-07-15 23:41:22 +0000992 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +0000993 {.numThreads = 1,
994 .numSessions = 1,
Andrei Homescu2a298012022-06-15 01:08:54 +0000995 .numIncomingConnections = numIncomingConnections});
Steven Morelandc7d40132021-06-10 03:42:11 +0000996 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +0000997
Steven Morelandc7d40132021-06-10 03:42:11 +0000998 if (callIsOneway) {
999 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1000 kTestString));
1001 } else {
1002 EXPECT_OK(
1003 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1004 }
Steven Moreland659416d2021-05-11 00:47:50 +00001005
Steven Moreland03ecce62022-05-13 23:22:05 +00001006 // if both transactions are synchronous and the response is sent back on the
1007 // same thread, everything should have happened in a nested call. Otherwise,
1008 // the callback will be processed on another thread.
1009 if (callIsOneway || callbackIsOneway || delayed) {
1010 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001011 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001012 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1013 }
Steven Moreland659416d2021-05-11 00:47:50 +00001014
Steven Morelandc7d40132021-06-10 03:42:11 +00001015 EXPECT_EQ(cb->mValues.size(), 1)
1016 << "callIsOneway: " << callIsOneway
1017 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1018 if (cb->mValues.empty()) continue;
1019 EXPECT_EQ(cb->mValues.at(0), kTestString)
1020 << "callIsOneway: " << callIsOneway
1021 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001022
Steven Morelandc7d40132021-06-10 03:42:11 +00001023 // since we are severing the connection, we need to go ahead and
1024 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001025 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1026 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1027 }
Steven Moreland659416d2021-05-11 00:47:50 +00001028
Steven Moreland1b304292021-07-15 22:59:34 +00001029 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001030 // need to manually shut it down
1031 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Morelandc7d40132021-06-10 03:42:11 +00001032 proc.expectAlreadyShutdown = true;
1033 }
Steven Moreland659416d2021-05-11 00:47:50 +00001034 }
1035 }
1036}
1037
Devin Moore66d5b7a2022-07-07 21:42:10 +00001038TEST_P(BinderRpc, SingleDeathRecipient) {
1039 if (singleThreaded() || !kEnableRpcThreads) {
1040 GTEST_SKIP() << "This test requires multiple threads";
1041 }
1042 class MyDeathRec : public IBinder::DeathRecipient {
1043 public:
1044 void binderDied(const wp<IBinder>& /* who */) override {
1045 dead = true;
1046 mCv.notify_one();
1047 }
1048 std::mutex mMtx;
1049 std::condition_variable mCv;
1050 bool dead = false;
1051 };
1052
1053 // Death recipient needs to have an incoming connection to be called
1054 auto proc = createRpcTestSocketServerProcess(
1055 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1056
1057 auto dr = sp<MyDeathRec>::make();
1058 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1059
1060 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1061 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1062 }
1063
1064 std::unique_lock<std::mutex> lock(dr->mMtx);
Devin Moore47a12012022-08-19 21:16:17 +00001065 ASSERT_TRUE(dr->mCv.wait_for(lock, 1000ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001066
1067 // need to wait for the session to shutdown so we don't "Leak session"
1068 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1069 proc.expectAlreadyShutdown = true;
1070}
1071
1072TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
1073 if (singleThreaded() || !kEnableRpcThreads) {
1074 GTEST_SKIP() << "This test requires multiple threads";
1075 }
1076 class MyDeathRec : public IBinder::DeathRecipient {
1077 public:
1078 void binderDied(const wp<IBinder>& /* who */) override {
1079 dead = true;
1080 mCv.notify_one();
1081 }
1082 std::mutex mMtx;
1083 std::condition_variable mCv;
1084 bool dead = false;
1085 };
1086
1087 // Death recipient needs to have an incoming connection to be called
1088 auto proc = createRpcTestSocketServerProcess(
1089 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1090
1091 auto dr = sp<MyDeathRec>::make();
1092 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1093
1094 // Explicitly calling shutDownAndWait will cause the death recipients
1095 // to be called.
1096 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1097
1098 std::unique_lock<std::mutex> lock(dr->mMtx);
1099 if (!dr->dead) {
1100 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1101 }
1102 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1103
1104 proc.proc.host.terminate();
1105 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1106 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1107 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1108 });
1109 proc.expectAlreadyShutdown = true;
1110}
1111
1112TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1113 class MyDeathRec : public IBinder::DeathRecipient {
1114 public:
1115 void binderDied(const wp<IBinder>& /* who */) override {}
1116 };
1117
1118 auto proc = createRpcTestSocketServerProcess(
1119 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1120
1121 auto dr = sp<MyDeathRec>::make();
1122 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1123 "Cannot register a DeathRecipient without any incoming connections.");
1124}
1125
1126TEST_P(BinderRpc, UnlinkDeathRecipient) {
1127 if (singleThreaded() || !kEnableRpcThreads) {
1128 GTEST_SKIP() << "This test requires multiple threads";
1129 }
1130 class MyDeathRec : public IBinder::DeathRecipient {
1131 public:
1132 void binderDied(const wp<IBinder>& /* who */) override {
1133 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1134 }
1135 };
1136
1137 // Death recipient needs to have an incoming connection to be called
1138 auto proc = createRpcTestSocketServerProcess(
1139 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1140
1141 auto dr = sp<MyDeathRec>::make();
1142 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1143 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1144
1145 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1146 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1147 }
1148
1149 // need to wait for the session to shutdown so we don't "Leak session"
1150 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1151 proc.expectAlreadyShutdown = true;
1152}
1153
Steven Moreland195edb82021-06-08 02:44:39 +00001154TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001155 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001156 auto cb = sp<MyBinderRpcCallback>::make();
1157
1158 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1159 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1160}
1161
Steven Morelandc1635952021-04-01 16:20:47 +00001162TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001163 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001164 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001165
1166 // make sure there is some state during crash
1167 // 1. we hold their binder
1168 sp<IBinderRpcSession> session;
1169 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1170 // 2. they hold our binder
1171 sp<IBinder> binder = new BBinder();
1172 EXPECT_OK(proc.rootIface->holdBinder(binder));
1173
1174 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1175 << "Do death cleanup: " << doDeathCleanup;
1176
Frederick Maylea12b0962022-06-25 01:13:22 +00001177 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1178 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1179 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1180 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001181 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001182 }
1183}
1184
Steven Morelandd7302072021-05-15 01:32:04 +00001185TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001186 // This test only works if the current process shared the internal state of
1187 // ProcessState with the service across the call to fork(). Both the static
1188 // libraries and libbinder.so have their own separate copies of all the
1189 // globals, so the test only works when the test client and service both use
1190 // libbinder.so (when using static libraries, even a client and service
1191 // using the same kind of static library should have separate copies of the
1192 // variables).
1193 if (!kEnableSharedLibs || singleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001194 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1195 "at build time.";
1196 }
1197
Steven Moreland4313d7e2021-07-15 23:41:22 +00001198 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001199
Andrei Homescu2a298012022-06-15 01:08:54 +00001200 // we can't allocate IPCThreadState so actually the first time should
1201 // succeed :(
1202 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001203
1204 // second time! we catch the error :)
1205 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1206
Frederick Maylea12b0962022-06-25 01:13:22 +00001207 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1208 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1209 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1210 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001211 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001212}
1213
Frederick Mayle69a0c992022-05-26 20:38:39 +00001214TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1215 auto proc = createRpcTestSocketServerProcess({
1216 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1217 .serverSupportedFileDescriptorTransportModes =
1218 {RpcSession::FileDescriptorTransportMode::UNIX},
1219 .allowConnectFailure = true,
1220 });
1221 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1222 proc.proc.host.terminate();
1223 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1224 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1225 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1226 });
1227 proc.expectAlreadyShutdown = true;
1228}
1229
1230TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1231 auto proc = createRpcTestSocketServerProcess({
1232 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1233 .serverSupportedFileDescriptorTransportModes =
1234 {RpcSession::FileDescriptorTransportMode::NONE},
1235 .allowConnectFailure = true,
1236 });
1237 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1238 proc.proc.host.terminate();
1239 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1240 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1241 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1242 });
1243 proc.expectAlreadyShutdown = true;
1244}
1245
1246TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1247 auto proc = createRpcTestSocketServerProcess({
1248 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1249 .serverSupportedFileDescriptorTransportModes =
1250 {RpcSession::FileDescriptorTransportMode::NONE,
1251 RpcSession::FileDescriptorTransportMode::UNIX},
1252 });
1253
1254 android::os::ParcelFileDescriptor out;
1255 auto status = proc.rootIface->echoAsFile("hello", &out);
1256 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1257}
1258
1259TEST_P(BinderRpc, ReceiveFile) {
1260 auto proc = createRpcTestSocketServerProcess({
1261 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1262 .serverSupportedFileDescriptorTransportModes =
1263 {RpcSession::FileDescriptorTransportMode::UNIX},
1264 });
1265
1266 android::os::ParcelFileDescriptor out;
1267 auto status = proc.rootIface->echoAsFile("hello", &out);
1268 if (!supportsFdTransport()) {
1269 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1270 return;
1271 }
1272 ASSERT_TRUE(status.isOk()) << status;
1273
1274 std::string result;
1275 CHECK(android::base::ReadFdToString(out.get(), &result));
1276 EXPECT_EQ(result, "hello");
1277}
1278
1279TEST_P(BinderRpc, SendFiles) {
1280 auto proc = createRpcTestSocketServerProcess({
1281 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1282 .serverSupportedFileDescriptorTransportModes =
1283 {RpcSession::FileDescriptorTransportMode::UNIX},
1284 });
1285
1286 std::vector<android::os::ParcelFileDescriptor> files;
1287 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1288 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1289 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1290 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1291
1292 android::os::ParcelFileDescriptor out;
1293 auto status = proc.rootIface->concatFiles(files, &out);
1294 if (!supportsFdTransport()) {
1295 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1296 return;
1297 }
1298 ASSERT_TRUE(status.isOk()) << status;
1299
1300 std::string result;
1301 CHECK(android::base::ReadFdToString(out.get(), &result));
1302 EXPECT_EQ(result, "123abcd");
1303}
1304
1305TEST_P(BinderRpc, SendMaxFiles) {
1306 if (!supportsFdTransport()) {
1307 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1308 }
1309
1310 auto proc = createRpcTestSocketServerProcess({
1311 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1312 .serverSupportedFileDescriptorTransportModes =
1313 {RpcSession::FileDescriptorTransportMode::UNIX},
1314 });
1315
1316 std::vector<android::os::ParcelFileDescriptor> files;
1317 for (int i = 0; i < 253; i++) {
1318 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1319 }
1320
1321 android::os::ParcelFileDescriptor out;
1322 auto status = proc.rootIface->concatFiles(files, &out);
1323 ASSERT_TRUE(status.isOk()) << status;
1324
1325 std::string result;
1326 CHECK(android::base::ReadFdToString(out.get(), &result));
1327 EXPECT_EQ(result, std::string(253, 'a'));
1328}
1329
1330TEST_P(BinderRpc, SendTooManyFiles) {
1331 if (!supportsFdTransport()) {
1332 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1333 }
1334
1335 auto proc = createRpcTestSocketServerProcess({
1336 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1337 .serverSupportedFileDescriptorTransportModes =
1338 {RpcSession::FileDescriptorTransportMode::UNIX},
1339 });
1340
1341 std::vector<android::os::ParcelFileDescriptor> files;
1342 for (int i = 0; i < 254; i++) {
1343 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1344 }
1345
1346 android::os::ParcelFileDescriptor out;
1347 auto status = proc.rootIface->concatFiles(files, &out);
1348 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1349}
1350
Steven Moreland37aff182021-03-26 02:04:16 +00001351TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001352 if constexpr (!kEnableSharedLibs) {
1353 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1354 }
1355
Steven Moreland4313d7e2021-07-15 23:41:22 +00001356 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001357
1358 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1359 ASSERT_NE(binder, nullptr);
1360
1361 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1362}
1363
1364TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001365 if constexpr (!kEnableSharedLibs) {
1366 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1367 }
1368
Steven Moreland4313d7e2021-07-15 23:41:22 +00001369 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001370
1371 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1372 ASSERT_NE(binder, nullptr);
1373
1374 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1375 ASSERT_NE(ndkBinder, nullptr);
1376
1377 std::string out;
1378 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1379 ASSERT_TRUE(status.isOk()) << status.getDescription();
1380 ASSERT_EQ("aoeuaoeu", out);
1381}
1382
Steven Moreland5553ac42020-11-11 02:14:45 +00001383ssize_t countFds() {
1384 DIR* dir = opendir("/proc/self/fd/");
1385 if (dir == nullptr) return -1;
1386 ssize_t ret = 0;
1387 dirent* ent;
1388 while ((ent = readdir(dir)) != nullptr) ret++;
1389 closedir(dir);
1390 return ret;
1391}
1392
Andrei Homescu12106de2022-04-27 04:42:21 +00001393TEST_P(BinderRpcThreads, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001394 ssize_t beforeFds = countFds();
1395 ASSERT_GE(beforeFds, 0);
1396 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001397 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001398 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1399 }
1400 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1401}
1402
Devin Moore800b2252021-10-15 16:22:57 +00001403TEST_P(BinderRpc, AidlDelegatorTest) {
1404 auto proc = createRpcTestSocketServerProcess({});
1405 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1406 ASSERT_NE(nullptr, myDelegator);
1407
1408 std::string doubled;
1409 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1410 EXPECT_EQ("cool cool ", doubled);
1411}
1412
Steven Morelandda573042021-06-12 01:13:45 +00001413static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001414 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001415 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001416
Andrei Homescu992a4052022-06-28 21:26:18 +00001417 android::base::unique_fd serverFd(
1418 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1419 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1420
1421 sockaddr_vm serverAddr{
1422 .svm_family = AF_VSOCK,
1423 .svm_port = vsockPort,
1424 .svm_cid = VMADDR_CID_ANY,
1425 };
1426 int ret = TEMP_FAILURE_RETRY(
1427 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1428 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1429 strerror(errno));
1430
1431 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1432 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1433 strerror(errno));
1434
1435 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1436 // to see if the kernel supports it. It's safe to use a blocking
1437 // connect because vsock sockets have a 2 second connection timeout,
1438 // and they return ETIMEDOUT after that.
1439 android::base::unique_fd connectFd(
1440 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1441 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1442 strerror(errno));
1443
1444 bool success = false;
1445 sockaddr_vm connectAddr{
1446 .svm_family = AF_VSOCK,
1447 .svm_port = vsockPort,
1448 .svm_cid = VMADDR_CID_LOCAL,
1449 };
1450 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1451 sizeof(connectAddr)));
1452 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1453 android::base::unique_fd acceptFd;
1454 while (true) {
1455 pollfd pfd[]{
1456 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1457 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1458 };
1459 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1460 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1461
1462 if (pfd[0].revents & POLLIN) {
1463 sockaddr_vm acceptAddr;
1464 socklen_t acceptAddrLen = sizeof(acceptAddr);
1465 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1466 reinterpret_cast<sockaddr*>(&acceptAddr),
1467 &acceptAddrLen, SOCK_CLOEXEC));
1468 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1469 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1470 "Truncated address");
1471
1472 // Store the fd in acceptFd so we keep the connection alive
1473 // while polling connectFd
1474 acceptFd.reset(ret);
1475 }
1476
1477 if (pfd[1].revents & POLLOUT) {
1478 // Connect either succeeded or timed out
1479 int connectErrno;
1480 socklen_t connectErrnoLen = sizeof(connectErrno);
1481 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1482 &connectErrnoLen);
1483 LOG_ALWAYS_FATAL_IF(ret == -1,
1484 "Could not getsockopt() after connect() "
1485 "on non-blocking socket: %s.",
1486 strerror(errno));
1487
1488 // We're done, this is all we wanted
1489 success = connectErrno == 0;
1490 break;
1491 }
1492 }
1493 } else {
1494 success = ret == 0;
1495 }
1496
1497 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1498
1499 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001500}
1501
Yifan Hong1deca4b2021-09-10 16:16:44 -07001502static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1503 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1504
1505 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001506
1507 static bool hasVsockLoopback = testSupportVsockLoopback();
1508
1509 if (hasVsockLoopback) {
1510 ret.push_back(SocketType::VSOCK);
1511 }
1512
1513 return ret;
1514}
1515
Frederick Mayledc07cf82022-05-26 20:30:12 +00001516static std::vector<uint32_t> testVersions() {
1517 std::vector<uint32_t> versions;
1518 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1519 versions.push_back(i);
1520 }
1521 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1522 return versions;
1523}
1524
Yifan Hong702115c2021-06-24 15:39:18 -07001525INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1526 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001527 ::testing::ValuesIn(RpcSecurityValues()),
1528 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001529 ::testing::ValuesIn(testVersions()),
1530 ::testing::Values(false, true),
1531 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001532 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001533
Andrei Homescu12106de2022-04-27 04:42:21 +00001534INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpcThreads,
1535 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1536 ::testing::ValuesIn(RpcSecurityValues()),
1537 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001538 ::testing::ValuesIn(testVersions()),
1539 ::testing::Values(false),
1540 ::testing::Values(false, true)),
Andrei Homescu12106de2022-04-27 04:42:21 +00001541 BinderRpc::PrintParamInfo);
1542
Yifan Hong702115c2021-06-24 15:39:18 -07001543class BinderRpcServerRootObject
1544 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001545
1546TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1547 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1548 auto setRootObject = [](bool isStrong) -> SetFn {
1549 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1550 };
1551
Yifan Hong702115c2021-06-24 15:39:18 -07001552 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1553 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001554 auto binder1 = sp<BBinder>::make();
1555 IBinder* binderRaw1 = binder1.get();
1556 setRootObject(isStrong1)(server.get(), binder1);
1557 EXPECT_EQ(binderRaw1, server->getRootObject());
1558 binder1.clear();
1559 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1560
1561 auto binder2 = sp<BBinder>::make();
1562 IBinder* binderRaw2 = binder2.get();
1563 setRootObject(isStrong2)(server.get(), binder2);
1564 EXPECT_EQ(binderRaw2, server->getRootObject());
1565 binder2.clear();
1566 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1567}
1568
1569INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001570 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1571 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001572
Yifan Hong1a235852021-05-13 16:07:47 -07001573class OneOffSignal {
1574public:
1575 // If notify() was previously called, or is called within |duration|, return true; else false.
1576 template <typename R, typename P>
1577 bool wait(std::chrono::duration<R, P> duration) {
1578 std::unique_lock<std::mutex> lock(mMutex);
1579 return mCv.wait_for(lock, duration, [this] { return mValue; });
1580 }
1581 void notify() {
1582 std::unique_lock<std::mutex> lock(mMutex);
1583 mValue = true;
1584 lock.unlock();
1585 mCv.notify_all();
1586 }
1587
1588private:
1589 std::mutex mMutex;
1590 std::condition_variable mCv;
1591 bool mValue = false;
1592};
1593
Frederick Mayledc07cf82022-05-26 20:30:12 +00001594TEST_P(BinderRpcServerOnly, Shutdown) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001595 if constexpr (!kEnableRpcThreads) {
1596 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1597 }
1598
Yifan Hong1a235852021-05-13 16:07:47 -07001599 auto addr = allocateSocketAddress();
Frederick Mayledc07cf82022-05-26 20:30:12 +00001600 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1601 server->setProtocolVersion(std::get<1>(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001602 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001603 auto joinEnds = std::make_shared<OneOffSignal>();
1604
1605 // If things are broken and the thread never stops, don't block other tests. Because the thread
1606 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1607 // shared pointers are passed.
1608 std::thread([server, joinEnds] {
1609 server->join();
1610 joinEnds->notify();
1611 }).detach();
1612
1613 bool shutdown = false;
1614 for (int i = 0; i < 10 && !shutdown; i++) {
1615 usleep(300 * 1000); // 300ms; total 3s
1616 if (server->shutdown()) shutdown = true;
1617 }
1618 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1619
1620 ASSERT_TRUE(joinEnds->wait(2s))
1621 << "After server->shutdown() returns true, join() did not stop after 2s";
1622}
1623
Yifan Hong194acf22021-06-29 18:44:56 -07001624TEST(BinderRpc, Java) {
1625#if !defined(__ANDROID__)
1626 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1627 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1628 "to binderHostDeviceTest. Hence, just disable this test on host.";
1629#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001630 if constexpr (!kEnableKernelIpc) {
1631 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1632 "at build time.";
1633 }
1634
Yifan Hong194acf22021-06-29 18:44:56 -07001635 sp<IServiceManager> sm = defaultServiceManager();
1636 ASSERT_NE(nullptr, sm);
1637 // Any Java service with non-empty getInterfaceDescriptor() would do.
1638 // Let's pick batteryproperties.
1639 auto binder = sm->checkService(String16("batteryproperties"));
1640 ASSERT_NE(nullptr, binder);
1641 auto descriptor = binder->getInterfaceDescriptor();
1642 ASSERT_GE(descriptor.size(), 0);
1643 ASSERT_EQ(OK, binder->pingBinder());
1644
1645 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001646 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001647 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001648 auto socket = rpcServer->releaseServer();
1649
1650 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001651 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1652
Yifan Honge3caaf22022-01-12 14:46:56 -08001653 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1654 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001655 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001656 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1657 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001658 << statusToString(setRpcClientDebugStatus);
1659 GTEST_SKIP();
1660 }
1661
1662 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001663
1664 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001665 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001666 auto rpcBinder = rpcSession->getRootObject();
1667 ASSERT_NE(nullptr, rpcBinder);
1668
1669 ASSERT_EQ(OK, rpcBinder->pingBinder());
1670
1671 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1672 << "getInterfaceDescriptor should not crash system_server";
1673 ASSERT_EQ(OK, rpcBinder->pingBinder());
1674}
1675
Frederick Mayledc07cf82022-05-26 20:30:12 +00001676INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1677 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1678 ::testing::ValuesIn(testVersions())),
1679 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001680
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001681class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001682public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001683 // Only parameterized only server version because `RpcSession` is bypassed
1684 // in the client half of the tests.
1685 using Param =
1686 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001687 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001688
1689 // A server that handles client socket connections.
1690 class Server {
1691 public:
1692 explicit Server() {}
1693 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001694 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001695 [[nodiscard]] AssertionResult setUp(
1696 const Param& param,
1697 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001698 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001699 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001700 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001701 switch (socketType) {
1702 case SocketType::PRECONNECTED: {
1703 return AssertionFailure() << "Not supported by this test";
1704 } break;
1705 case SocketType::UNIX: {
1706 auto addr = allocateSocketAddress();
1707 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1708 if (status != OK) {
1709 return AssertionFailure()
1710 << "setupUnixDomainServer: " << statusToString(status);
1711 }
1712 mConnectToServer = [addr] {
1713 return connectTo(UnixSocketAddress(addr.c_str()));
1714 };
1715 } break;
1716 case SocketType::VSOCK: {
1717 auto port = allocateVsockPort();
1718 auto status = rpcServer->setupVsockServer(port);
1719 if (status != OK) {
1720 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1721 }
1722 mConnectToServer = [port] {
1723 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1724 };
1725 } break;
1726 case SocketType::INET: {
1727 unsigned int port;
1728 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1729 if (status != OK) {
1730 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1731 }
1732 mConnectToServer = [port] {
1733 const char* addr = kLocalInetAddress;
1734 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1735 if (aiStart == nullptr) return base::unique_fd{};
1736 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1737 auto fd = connectTo(
1738 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1739 if (fd.ok()) return fd;
1740 }
1741 ALOGE("None of the socket address resolved for %s:%u can be connected",
1742 addr, port);
1743 return base::unique_fd{};
1744 };
1745 }
1746 }
1747 mFd = rpcServer->releaseServer();
1748 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001749 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001750 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1751 mSetup = true;
1752 return AssertionSuccess();
1753 }
1754 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1755 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1756 return mCertVerifier;
1757 }
1758 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1759 void start() {
1760 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1761 mThread = std::make_unique<std::thread>(&Server::run, this);
1762 }
1763 void run() {
1764 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1765
1766 std::vector<std::thread> threads;
1767 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1768 base::unique_fd acceptedFd(
1769 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1770 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1771 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1772 }
1773
1774 for (auto& thread : threads) thread.join();
1775 }
1776 void handleOne(android::base::unique_fd acceptedFd) {
1777 ASSERT_TRUE(acceptedFd.ok());
1778 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1779 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001780 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001781 }
Yifan Honge07d2732021-09-13 21:59:14 -07001782 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001783 shutdown();
1784 join();
1785 }
1786 void shutdown() { mFdTrigger->trigger(); }
1787
1788 void setPostConnect(
1789 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1790 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001791 }
1792
1793 private:
1794 std::unique_ptr<std::thread> mThread;
1795 ConnectToServer mConnectToServer;
1796 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1797 base::unique_fd mFd;
1798 std::unique_ptr<RpcTransportCtx> mCtx;
1799 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1800 std::make_shared<RpcCertificateVerifierSimple>();
1801 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001802 // The function invoked after connection and handshake. By default, it is
1803 // |defaultPostConnect| that sends |kMessage| to the client.
1804 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1805 Server::defaultPostConnect;
1806
1807 void join() {
1808 if (mThread != nullptr) {
1809 mThread->join();
1810 mThread = nullptr;
1811 }
1812 }
1813
1814 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1815 FdTrigger* fdTrigger) {
1816 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001817 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001818 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001819 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001820 if (status != OK) return AssertionFailure() << statusToString(status);
1821 return AssertionSuccess();
1822 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001823 };
1824
1825 class Client {
1826 public:
1827 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1828 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001829 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001830 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1831 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001832 mFdTrigger = FdTrigger::make();
1833 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1834 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1835 return AssertionSuccess();
1836 }
1837 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1838 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1839 return mCertVerifier;
1840 }
Yifan Hong67519322021-09-13 18:51:16 -07001841 // connect() and do handshake
1842 bool setUpTransport() {
1843 mFd = mConnectToServer();
1844 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1845 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1846 return mClientTransport != nullptr;
1847 }
1848 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1849 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1850 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001851 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001852 status_t readStatus =
1853 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001854 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001855 if (readStatus != OK) {
1856 return AssertionFailure() << statusToString(readStatus);
1857 }
1858 if (readMessage != expectedMessage) {
1859 return AssertionFailure()
1860 << "Expected " << expectedMessage << ", actual " << readMessage;
1861 }
1862 return AssertionSuccess();
1863 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001864 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001865 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001866 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1867 return;
1868 }
1869 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001870 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001871 }
1872
1873 private:
1874 ConnectToServer mConnectToServer;
1875 base::unique_fd mFd;
1876 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1877 std::unique_ptr<RpcTransportCtx> mCtx;
1878 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1879 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001880 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001881 };
1882
1883 // Make A trust B.
1884 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001885 static status_t trust(RpcSecurity rpcSecurity,
1886 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1887 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001888 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001889 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1890 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1891 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001892 }
1893
1894 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001895};
1896
1897class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1898public:
1899 using Server = RpcTransportTestUtils::Server;
1900 using Client = RpcTransportTestUtils::Client;
1901 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001902 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001903 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1904 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001905 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001906 return ret;
1907 }
1908 static std::vector<ParamType> getRpcTranportTestParams() {
1909 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001910 for (auto serverVersion : testVersions()) {
1911 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1912 for (auto rpcSecurity : RpcSecurityValues()) {
1913 switch (rpcSecurity) {
1914 case RpcSecurity::RAW: {
1915 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1916 } break;
1917 case RpcSecurity::TLS: {
1918 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1919 serverVersion);
1920 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1921 serverVersion);
1922 } break;
1923 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001924 }
1925 }
1926 }
1927 return ret;
1928 }
1929 template <typename A, typename B>
1930 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001931 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1932 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001933 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1934 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001935 void SetUp() override {
1936 if constexpr (!kEnableRpcThreads) {
1937 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1938 }
1939 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001940};
1941
1942TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001943 auto server = std::make_unique<Server>();
1944 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001945
1946 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001947 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001948
1949 ASSERT_EQ(OK, trust(&client, server));
1950 ASSERT_EQ(OK, trust(server, &client));
1951
1952 server->start();
1953 client.run();
1954}
1955
1956TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001957 auto server = std::make_unique<Server>();
1958 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001959
1960 std::vector<Client> clients;
1961 for (int i = 0; i < 2; i++) {
1962 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001963 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001964 ASSERT_EQ(OK, trust(&client, server));
1965 ASSERT_EQ(OK, trust(server, &client));
1966 }
1967
1968 server->start();
1969 for (auto& client : clients) client.run();
1970}
1971
1972TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001973 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1974 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001975
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001976 auto untrustedServer = std::make_unique<Server>();
1977 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001978
1979 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001980 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001981
1982 ASSERT_EQ(OK, trust(untrustedServer, &client));
1983
1984 untrustedServer->start();
1985
1986 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1987 // the client can't verify the server's identity.
1988 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1989 client.run(handshakeOk);
1990}
1991TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001992 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1993 (void)serverVersion;
1994
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001995 auto validServer = std::make_unique<Server>();
1996 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001997
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001998 auto maliciousServer = std::make_unique<Server>();
1999 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002000
2001 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002002 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002003
2004 ASSERT_EQ(OK, trust(&client, validServer));
2005 ASSERT_EQ(OK, trust(validServer, &client));
2006 ASSERT_EQ(OK, trust(maliciousServer, &client));
2007
2008 maliciousServer->start();
2009
2010 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2011 // the client can't verify the server's identity.
2012 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2013 client.run(handshakeOk);
2014}
2015
2016TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002017 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2018 (void)serverVersion;
2019
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002020 auto server = std::make_unique<Server>();
2021 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002022
2023 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002024 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002025
2026 ASSERT_EQ(OK, trust(&client, server));
2027
2028 server->start();
2029
2030 // For TLS, Client should be able to verify server's identity, so client should see
2031 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2032 // identity and should drop the connection, so client shouldn't be able to read anything.
2033 bool readOk = rpcSecurity != RpcSecurity::TLS;
2034 client.run(true, readOk);
2035}
2036
2037TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002038 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2039 (void)serverVersion;
2040
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002041 auto server = std::make_unique<Server>();
2042 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002043
2044 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002045 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002046 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002047 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002048
2049 ASSERT_EQ(OK, trust(&validClient, server));
2050 ASSERT_EQ(OK, trust(&maliciousClient, server));
2051
2052 server->start();
2053
2054 // See UntrustedClient.
2055 bool readOk = rpcSecurity != RpcSecurity::TLS;
2056 maliciousClient.run(true, readOk);
2057}
2058
Yifan Hong67519322021-09-13 18:51:16 -07002059TEST_P(RpcTransportTest, Trigger) {
2060 std::string msg2 = ", world!";
2061 std::mutex writeMutex;
2062 std::condition_variable writeCv;
2063 bool shouldContinueWriting = false;
2064 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002065 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002066 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002067 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2068 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002069 if (status != OK) return AssertionFailure() << statusToString(status);
2070
2071 {
2072 std::unique_lock<std::mutex> lock(writeMutex);
2073 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2074 return AssertionFailure() << "write barrier not cleared in time!";
2075 }
2076 }
2077
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002078 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002079 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2080 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002081 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002082 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002083 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002084 << statusToString(status);
2085 return AssertionSuccess();
2086 };
2087
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002088 auto server = std::make_unique<Server>();
2089 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002090
2091 // Set up client
2092 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002093 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002094
2095 // Exchange keys
2096 ASSERT_EQ(OK, trust(&client, server));
2097 ASSERT_EQ(OK, trust(server, &client));
2098
2099 server->setPostConnect(serverPostConnect);
2100
Yifan Hong67519322021-09-13 18:51:16 -07002101 server->start();
2102 // connect() to server and do handshake
2103 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002104 // read the first message. This ensures that server has finished handshake and start handling
2105 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002106 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002107 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2108 // write is on an FdTrigger that has been shut down.
2109 server->shutdown();
2110 // Continues server thread to write the second message.
2111 {
Yifan Hong22211f82021-09-14 12:32:25 -07002112 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002113 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002114 }
Yifan Hong22211f82021-09-14 12:32:25 -07002115 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002116 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002117 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002118 // On the client side, second read fails with DEAD_OBJECT
2119 ASSERT_FALSE(client.readMessage(msg2));
2120}
2121
Yifan Hong1deca4b2021-09-10 16:16:44 -07002122INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002123 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002124 RpcTransportTest::PrintParamInfo);
2125
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002126class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002127 : public testing::TestWithParam<
2128 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002129public:
2130 template <typename A, typename B>
2131 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002132 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2133 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002134 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2135 }
2136 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002137 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2138 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2139 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002140 };
2141};
2142
2143TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002144 if constexpr (!kEnableRpcThreads) {
2145 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2146 }
2147
Frederick Mayledc07cf82022-05-26 20:30:12 +00002148 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002149
2150 std::vector<uint8_t> pkeyData, certData;
2151 {
2152 auto pkey = makeKeyPairForSelfSignedCert();
2153 ASSERT_NE(nullptr, pkey);
2154 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2155 ASSERT_NE(nullptr, cert);
2156 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2157 certData = serializeCertificate(cert.get(), certificateFormat);
2158 }
2159
2160 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2161 auto desCert = deserializeCertificate(certData, certificateFormat);
2162 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002163 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2164 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002165
2166 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2167 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2168
2169 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2170 ASSERT_TRUE(client.setUp(utilsParam));
2171
2172 ASSERT_EQ(OK, trust(&client, server));
2173 ASSERT_EQ(OK, trust(server, &client));
2174
2175 server->start();
2176 client.run();
2177}
2178
2179INSTANTIATE_TEST_CASE_P(
2180 BinderRpc, RpcTransportTlsKeyTest,
2181 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2182 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002183 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2184 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002185 RpcTransportTlsKeyTest::PrintParamInfo);
2186
Steven Morelandc1635952021-04-01 16:20:47 +00002187} // namespace android
2188
2189int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002190 ::testing::InitGoogleTest(&argc, argv);
2191 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002192
Steven Moreland5553ac42020-11-11 02:14:45 +00002193 return RUN_ALL_TESTS();
2194}