blob: 501a60402672df1a7cf90ac2d51245e430601b8e [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);
1065 if (!dr->dead) {
1066 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1067 }
1068 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1069
1070 // need to wait for the session to shutdown so we don't "Leak session"
1071 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1072 proc.expectAlreadyShutdown = true;
1073}
1074
1075TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
1076 if (singleThreaded() || !kEnableRpcThreads) {
1077 GTEST_SKIP() << "This test requires multiple threads";
1078 }
1079 class MyDeathRec : public IBinder::DeathRecipient {
1080 public:
1081 void binderDied(const wp<IBinder>& /* who */) override {
1082 dead = true;
1083 mCv.notify_one();
1084 }
1085 std::mutex mMtx;
1086 std::condition_variable mCv;
1087 bool dead = false;
1088 };
1089
1090 // Death recipient needs to have an incoming connection to be called
1091 auto proc = createRpcTestSocketServerProcess(
1092 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1093
1094 auto dr = sp<MyDeathRec>::make();
1095 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1096
1097 // Explicitly calling shutDownAndWait will cause the death recipients
1098 // to be called.
1099 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1100
1101 std::unique_lock<std::mutex> lock(dr->mMtx);
1102 if (!dr->dead) {
1103 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1104 }
1105 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1106
1107 proc.proc.host.terminate();
1108 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1109 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1110 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1111 });
1112 proc.expectAlreadyShutdown = true;
1113}
1114
1115TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1116 class MyDeathRec : public IBinder::DeathRecipient {
1117 public:
1118 void binderDied(const wp<IBinder>& /* who */) override {}
1119 };
1120
1121 auto proc = createRpcTestSocketServerProcess(
1122 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1123
1124 auto dr = sp<MyDeathRec>::make();
1125 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1126 "Cannot register a DeathRecipient without any incoming connections.");
1127}
1128
1129TEST_P(BinderRpc, UnlinkDeathRecipient) {
1130 if (singleThreaded() || !kEnableRpcThreads) {
1131 GTEST_SKIP() << "This test requires multiple threads";
1132 }
1133 class MyDeathRec : public IBinder::DeathRecipient {
1134 public:
1135 void binderDied(const wp<IBinder>& /* who */) override {
1136 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1137 }
1138 };
1139
1140 // Death recipient needs to have an incoming connection to be called
1141 auto proc = createRpcTestSocketServerProcess(
1142 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1143
1144 auto dr = sp<MyDeathRec>::make();
1145 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1146 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1147
1148 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1149 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1150 }
1151
1152 // need to wait for the session to shutdown so we don't "Leak session"
1153 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1154 proc.expectAlreadyShutdown = true;
1155}
1156
Steven Moreland195edb82021-06-08 02:44:39 +00001157TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001158 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001159 auto cb = sp<MyBinderRpcCallback>::make();
1160
1161 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1162 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1163}
1164
Steven Morelandc1635952021-04-01 16:20:47 +00001165TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001166 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001167 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001168
1169 // make sure there is some state during crash
1170 // 1. we hold their binder
1171 sp<IBinderRpcSession> session;
1172 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1173 // 2. they hold our binder
1174 sp<IBinder> binder = new BBinder();
1175 EXPECT_OK(proc.rootIface->holdBinder(binder));
1176
1177 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1178 << "Do death cleanup: " << doDeathCleanup;
1179
Frederick Maylea12b0962022-06-25 01:13:22 +00001180 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1181 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1182 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1183 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001184 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001185 }
1186}
1187
Steven Morelandd7302072021-05-15 01:32:04 +00001188TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001189 // This test only works if the current process shared the internal state of
1190 // ProcessState with the service across the call to fork(). Both the static
1191 // libraries and libbinder.so have their own separate copies of all the
1192 // globals, so the test only works when the test client and service both use
1193 // libbinder.so (when using static libraries, even a client and service
1194 // using the same kind of static library should have separate copies of the
1195 // variables).
1196 if (!kEnableSharedLibs || singleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001197 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1198 "at build time.";
1199 }
1200
Steven Moreland4313d7e2021-07-15 23:41:22 +00001201 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001202
Andrei Homescu2a298012022-06-15 01:08:54 +00001203 // we can't allocate IPCThreadState so actually the first time should
1204 // succeed :(
1205 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001206
1207 // second time! we catch the error :)
1208 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1209
Frederick Maylea12b0962022-06-25 01:13:22 +00001210 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1211 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1212 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1213 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001214 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001215}
1216
Frederick Mayle69a0c992022-05-26 20:38:39 +00001217TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1218 auto proc = createRpcTestSocketServerProcess({
1219 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1220 .serverSupportedFileDescriptorTransportModes =
1221 {RpcSession::FileDescriptorTransportMode::UNIX},
1222 .allowConnectFailure = true,
1223 });
1224 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1225 proc.proc.host.terminate();
1226 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1227 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1228 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1229 });
1230 proc.expectAlreadyShutdown = true;
1231}
1232
1233TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1234 auto proc = createRpcTestSocketServerProcess({
1235 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1236 .serverSupportedFileDescriptorTransportModes =
1237 {RpcSession::FileDescriptorTransportMode::NONE},
1238 .allowConnectFailure = true,
1239 });
1240 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1241 proc.proc.host.terminate();
1242 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1243 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1244 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1245 });
1246 proc.expectAlreadyShutdown = true;
1247}
1248
1249TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1250 auto proc = createRpcTestSocketServerProcess({
1251 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1252 .serverSupportedFileDescriptorTransportModes =
1253 {RpcSession::FileDescriptorTransportMode::NONE,
1254 RpcSession::FileDescriptorTransportMode::UNIX},
1255 });
1256
1257 android::os::ParcelFileDescriptor out;
1258 auto status = proc.rootIface->echoAsFile("hello", &out);
1259 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1260}
1261
1262TEST_P(BinderRpc, ReceiveFile) {
1263 auto proc = createRpcTestSocketServerProcess({
1264 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1265 .serverSupportedFileDescriptorTransportModes =
1266 {RpcSession::FileDescriptorTransportMode::UNIX},
1267 });
1268
1269 android::os::ParcelFileDescriptor out;
1270 auto status = proc.rootIface->echoAsFile("hello", &out);
1271 if (!supportsFdTransport()) {
1272 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1273 return;
1274 }
1275 ASSERT_TRUE(status.isOk()) << status;
1276
1277 std::string result;
1278 CHECK(android::base::ReadFdToString(out.get(), &result));
1279 EXPECT_EQ(result, "hello");
1280}
1281
1282TEST_P(BinderRpc, SendFiles) {
1283 auto proc = createRpcTestSocketServerProcess({
1284 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1285 .serverSupportedFileDescriptorTransportModes =
1286 {RpcSession::FileDescriptorTransportMode::UNIX},
1287 });
1288
1289 std::vector<android::os::ParcelFileDescriptor> files;
1290 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1291 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1292 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1293 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1294
1295 android::os::ParcelFileDescriptor out;
1296 auto status = proc.rootIface->concatFiles(files, &out);
1297 if (!supportsFdTransport()) {
1298 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1299 return;
1300 }
1301 ASSERT_TRUE(status.isOk()) << status;
1302
1303 std::string result;
1304 CHECK(android::base::ReadFdToString(out.get(), &result));
1305 EXPECT_EQ(result, "123abcd");
1306}
1307
1308TEST_P(BinderRpc, SendMaxFiles) {
1309 if (!supportsFdTransport()) {
1310 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1311 }
1312
1313 auto proc = createRpcTestSocketServerProcess({
1314 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1315 .serverSupportedFileDescriptorTransportModes =
1316 {RpcSession::FileDescriptorTransportMode::UNIX},
1317 });
1318
1319 std::vector<android::os::ParcelFileDescriptor> files;
1320 for (int i = 0; i < 253; i++) {
1321 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1322 }
1323
1324 android::os::ParcelFileDescriptor out;
1325 auto status = proc.rootIface->concatFiles(files, &out);
1326 ASSERT_TRUE(status.isOk()) << status;
1327
1328 std::string result;
1329 CHECK(android::base::ReadFdToString(out.get(), &result));
1330 EXPECT_EQ(result, std::string(253, 'a'));
1331}
1332
1333TEST_P(BinderRpc, SendTooManyFiles) {
1334 if (!supportsFdTransport()) {
1335 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1336 }
1337
1338 auto proc = createRpcTestSocketServerProcess({
1339 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1340 .serverSupportedFileDescriptorTransportModes =
1341 {RpcSession::FileDescriptorTransportMode::UNIX},
1342 });
1343
1344 std::vector<android::os::ParcelFileDescriptor> files;
1345 for (int i = 0; i < 254; i++) {
1346 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1347 }
1348
1349 android::os::ParcelFileDescriptor out;
1350 auto status = proc.rootIface->concatFiles(files, &out);
1351 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1352}
1353
Steven Moreland37aff182021-03-26 02:04:16 +00001354TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001355 if constexpr (!kEnableSharedLibs) {
1356 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1357 }
1358
Steven Moreland4313d7e2021-07-15 23:41:22 +00001359 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001360
1361 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1362 ASSERT_NE(binder, nullptr);
1363
1364 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1365}
1366
1367TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001368 if constexpr (!kEnableSharedLibs) {
1369 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1370 }
1371
Steven Moreland4313d7e2021-07-15 23:41:22 +00001372 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001373
1374 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1375 ASSERT_NE(binder, nullptr);
1376
1377 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1378 ASSERT_NE(ndkBinder, nullptr);
1379
1380 std::string out;
1381 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1382 ASSERT_TRUE(status.isOk()) << status.getDescription();
1383 ASSERT_EQ("aoeuaoeu", out);
1384}
1385
Steven Moreland5553ac42020-11-11 02:14:45 +00001386ssize_t countFds() {
1387 DIR* dir = opendir("/proc/self/fd/");
1388 if (dir == nullptr) return -1;
1389 ssize_t ret = 0;
1390 dirent* ent;
1391 while ((ent = readdir(dir)) != nullptr) ret++;
1392 closedir(dir);
1393 return ret;
1394}
1395
Andrei Homescu12106de2022-04-27 04:42:21 +00001396TEST_P(BinderRpcThreads, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001397 ssize_t beforeFds = countFds();
1398 ASSERT_GE(beforeFds, 0);
1399 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001400 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001401 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1402 }
1403 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1404}
1405
Devin Moore800b2252021-10-15 16:22:57 +00001406TEST_P(BinderRpc, AidlDelegatorTest) {
1407 auto proc = createRpcTestSocketServerProcess({});
1408 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1409 ASSERT_NE(nullptr, myDelegator);
1410
1411 std::string doubled;
1412 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1413 EXPECT_EQ("cool cool ", doubled);
1414}
1415
Steven Morelandda573042021-06-12 01:13:45 +00001416static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001417 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001418 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001419
Andrei Homescu992a4052022-06-28 21:26:18 +00001420 android::base::unique_fd serverFd(
1421 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1422 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1423
1424 sockaddr_vm serverAddr{
1425 .svm_family = AF_VSOCK,
1426 .svm_port = vsockPort,
1427 .svm_cid = VMADDR_CID_ANY,
1428 };
1429 int ret = TEMP_FAILURE_RETRY(
1430 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1431 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1432 strerror(errno));
1433
1434 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1435 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1436 strerror(errno));
1437
1438 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1439 // to see if the kernel supports it. It's safe to use a blocking
1440 // connect because vsock sockets have a 2 second connection timeout,
1441 // and they return ETIMEDOUT after that.
1442 android::base::unique_fd connectFd(
1443 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1444 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1445 strerror(errno));
1446
1447 bool success = false;
1448 sockaddr_vm connectAddr{
1449 .svm_family = AF_VSOCK,
1450 .svm_port = vsockPort,
1451 .svm_cid = VMADDR_CID_LOCAL,
1452 };
1453 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1454 sizeof(connectAddr)));
1455 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1456 android::base::unique_fd acceptFd;
1457 while (true) {
1458 pollfd pfd[]{
1459 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1460 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1461 };
1462 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1463 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1464
1465 if (pfd[0].revents & POLLIN) {
1466 sockaddr_vm acceptAddr;
1467 socklen_t acceptAddrLen = sizeof(acceptAddr);
1468 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1469 reinterpret_cast<sockaddr*>(&acceptAddr),
1470 &acceptAddrLen, SOCK_CLOEXEC));
1471 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1472 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1473 "Truncated address");
1474
1475 // Store the fd in acceptFd so we keep the connection alive
1476 // while polling connectFd
1477 acceptFd.reset(ret);
1478 }
1479
1480 if (pfd[1].revents & POLLOUT) {
1481 // Connect either succeeded or timed out
1482 int connectErrno;
1483 socklen_t connectErrnoLen = sizeof(connectErrno);
1484 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1485 &connectErrnoLen);
1486 LOG_ALWAYS_FATAL_IF(ret == -1,
1487 "Could not getsockopt() after connect() "
1488 "on non-blocking socket: %s.",
1489 strerror(errno));
1490
1491 // We're done, this is all we wanted
1492 success = connectErrno == 0;
1493 break;
1494 }
1495 }
1496 } else {
1497 success = ret == 0;
1498 }
1499
1500 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1501
1502 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001503}
1504
Yifan Hong1deca4b2021-09-10 16:16:44 -07001505static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1506 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1507
1508 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001509
1510 static bool hasVsockLoopback = testSupportVsockLoopback();
1511
1512 if (hasVsockLoopback) {
1513 ret.push_back(SocketType::VSOCK);
1514 }
1515
1516 return ret;
1517}
1518
Frederick Mayledc07cf82022-05-26 20:30:12 +00001519static std::vector<uint32_t> testVersions() {
1520 std::vector<uint32_t> versions;
1521 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1522 versions.push_back(i);
1523 }
1524 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1525 return versions;
1526}
1527
Yifan Hong702115c2021-06-24 15:39:18 -07001528INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1529 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001530 ::testing::ValuesIn(RpcSecurityValues()),
1531 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001532 ::testing::ValuesIn(testVersions()),
1533 ::testing::Values(false, true),
1534 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001535 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001536
Andrei Homescu12106de2022-04-27 04:42:21 +00001537INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpcThreads,
1538 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1539 ::testing::ValuesIn(RpcSecurityValues()),
1540 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001541 ::testing::ValuesIn(testVersions()),
1542 ::testing::Values(false),
1543 ::testing::Values(false, true)),
Andrei Homescu12106de2022-04-27 04:42:21 +00001544 BinderRpc::PrintParamInfo);
1545
Yifan Hong702115c2021-06-24 15:39:18 -07001546class BinderRpcServerRootObject
1547 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001548
1549TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1550 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1551 auto setRootObject = [](bool isStrong) -> SetFn {
1552 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1553 };
1554
Yifan Hong702115c2021-06-24 15:39:18 -07001555 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1556 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001557 auto binder1 = sp<BBinder>::make();
1558 IBinder* binderRaw1 = binder1.get();
1559 setRootObject(isStrong1)(server.get(), binder1);
1560 EXPECT_EQ(binderRaw1, server->getRootObject());
1561 binder1.clear();
1562 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1563
1564 auto binder2 = sp<BBinder>::make();
1565 IBinder* binderRaw2 = binder2.get();
1566 setRootObject(isStrong2)(server.get(), binder2);
1567 EXPECT_EQ(binderRaw2, server->getRootObject());
1568 binder2.clear();
1569 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1570}
1571
1572INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001573 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1574 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001575
Yifan Hong1a235852021-05-13 16:07:47 -07001576class OneOffSignal {
1577public:
1578 // If notify() was previously called, or is called within |duration|, return true; else false.
1579 template <typename R, typename P>
1580 bool wait(std::chrono::duration<R, P> duration) {
1581 std::unique_lock<std::mutex> lock(mMutex);
1582 return mCv.wait_for(lock, duration, [this] { return mValue; });
1583 }
1584 void notify() {
1585 std::unique_lock<std::mutex> lock(mMutex);
1586 mValue = true;
1587 lock.unlock();
1588 mCv.notify_all();
1589 }
1590
1591private:
1592 std::mutex mMutex;
1593 std::condition_variable mCv;
1594 bool mValue = false;
1595};
1596
Frederick Mayledc07cf82022-05-26 20:30:12 +00001597TEST_P(BinderRpcServerOnly, Shutdown) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001598 if constexpr (!kEnableRpcThreads) {
1599 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1600 }
1601
Yifan Hong1a235852021-05-13 16:07:47 -07001602 auto addr = allocateSocketAddress();
Frederick Mayledc07cf82022-05-26 20:30:12 +00001603 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1604 server->setProtocolVersion(std::get<1>(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001605 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001606 auto joinEnds = std::make_shared<OneOffSignal>();
1607
1608 // If things are broken and the thread never stops, don't block other tests. Because the thread
1609 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1610 // shared pointers are passed.
1611 std::thread([server, joinEnds] {
1612 server->join();
1613 joinEnds->notify();
1614 }).detach();
1615
1616 bool shutdown = false;
1617 for (int i = 0; i < 10 && !shutdown; i++) {
1618 usleep(300 * 1000); // 300ms; total 3s
1619 if (server->shutdown()) shutdown = true;
1620 }
1621 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1622
1623 ASSERT_TRUE(joinEnds->wait(2s))
1624 << "After server->shutdown() returns true, join() did not stop after 2s";
1625}
1626
Yifan Hong194acf22021-06-29 18:44:56 -07001627TEST(BinderRpc, Java) {
1628#if !defined(__ANDROID__)
1629 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1630 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1631 "to binderHostDeviceTest. Hence, just disable this test on host.";
1632#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001633 if constexpr (!kEnableKernelIpc) {
1634 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1635 "at build time.";
1636 }
1637
Yifan Hong194acf22021-06-29 18:44:56 -07001638 sp<IServiceManager> sm = defaultServiceManager();
1639 ASSERT_NE(nullptr, sm);
1640 // Any Java service with non-empty getInterfaceDescriptor() would do.
1641 // Let's pick batteryproperties.
1642 auto binder = sm->checkService(String16("batteryproperties"));
1643 ASSERT_NE(nullptr, binder);
1644 auto descriptor = binder->getInterfaceDescriptor();
1645 ASSERT_GE(descriptor.size(), 0);
1646 ASSERT_EQ(OK, binder->pingBinder());
1647
1648 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001649 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001650 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001651 auto socket = rpcServer->releaseServer();
1652
1653 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001654 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1655
Yifan Honge3caaf22022-01-12 14:46:56 -08001656 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1657 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001658 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001659 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1660 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001661 << statusToString(setRpcClientDebugStatus);
1662 GTEST_SKIP();
1663 }
1664
1665 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001666
1667 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001668 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001669 auto rpcBinder = rpcSession->getRootObject();
1670 ASSERT_NE(nullptr, rpcBinder);
1671
1672 ASSERT_EQ(OK, rpcBinder->pingBinder());
1673
1674 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1675 << "getInterfaceDescriptor should not crash system_server";
1676 ASSERT_EQ(OK, rpcBinder->pingBinder());
1677}
1678
Frederick Mayledc07cf82022-05-26 20:30:12 +00001679INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1680 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1681 ::testing::ValuesIn(testVersions())),
1682 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001683
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001684class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001685public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001686 // Only parameterized only server version because `RpcSession` is bypassed
1687 // in the client half of the tests.
1688 using Param =
1689 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001690 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001691
1692 // A server that handles client socket connections.
1693 class Server {
1694 public:
1695 explicit Server() {}
1696 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001697 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001698 [[nodiscard]] AssertionResult setUp(
1699 const Param& param,
1700 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001701 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001702 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001703 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001704 switch (socketType) {
1705 case SocketType::PRECONNECTED: {
1706 return AssertionFailure() << "Not supported by this test";
1707 } break;
1708 case SocketType::UNIX: {
1709 auto addr = allocateSocketAddress();
1710 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1711 if (status != OK) {
1712 return AssertionFailure()
1713 << "setupUnixDomainServer: " << statusToString(status);
1714 }
1715 mConnectToServer = [addr] {
1716 return connectTo(UnixSocketAddress(addr.c_str()));
1717 };
1718 } break;
1719 case SocketType::VSOCK: {
1720 auto port = allocateVsockPort();
1721 auto status = rpcServer->setupVsockServer(port);
1722 if (status != OK) {
1723 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1724 }
1725 mConnectToServer = [port] {
1726 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1727 };
1728 } break;
1729 case SocketType::INET: {
1730 unsigned int port;
1731 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1732 if (status != OK) {
1733 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1734 }
1735 mConnectToServer = [port] {
1736 const char* addr = kLocalInetAddress;
1737 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1738 if (aiStart == nullptr) return base::unique_fd{};
1739 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1740 auto fd = connectTo(
1741 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1742 if (fd.ok()) return fd;
1743 }
1744 ALOGE("None of the socket address resolved for %s:%u can be connected",
1745 addr, port);
1746 return base::unique_fd{};
1747 };
1748 }
1749 }
1750 mFd = rpcServer->releaseServer();
1751 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001752 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001753 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1754 mSetup = true;
1755 return AssertionSuccess();
1756 }
1757 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1758 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1759 return mCertVerifier;
1760 }
1761 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1762 void start() {
1763 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1764 mThread = std::make_unique<std::thread>(&Server::run, this);
1765 }
1766 void run() {
1767 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1768
1769 std::vector<std::thread> threads;
1770 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1771 base::unique_fd acceptedFd(
1772 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1773 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1774 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1775 }
1776
1777 for (auto& thread : threads) thread.join();
1778 }
1779 void handleOne(android::base::unique_fd acceptedFd) {
1780 ASSERT_TRUE(acceptedFd.ok());
1781 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1782 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001783 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001784 }
Yifan Honge07d2732021-09-13 21:59:14 -07001785 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001786 shutdown();
1787 join();
1788 }
1789 void shutdown() { mFdTrigger->trigger(); }
1790
1791 void setPostConnect(
1792 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1793 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001794 }
1795
1796 private:
1797 std::unique_ptr<std::thread> mThread;
1798 ConnectToServer mConnectToServer;
1799 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1800 base::unique_fd mFd;
1801 std::unique_ptr<RpcTransportCtx> mCtx;
1802 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1803 std::make_shared<RpcCertificateVerifierSimple>();
1804 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001805 // The function invoked after connection and handshake. By default, it is
1806 // |defaultPostConnect| that sends |kMessage| to the client.
1807 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1808 Server::defaultPostConnect;
1809
1810 void join() {
1811 if (mThread != nullptr) {
1812 mThread->join();
1813 mThread = nullptr;
1814 }
1815 }
1816
1817 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1818 FdTrigger* fdTrigger) {
1819 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001820 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001821 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001822 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001823 if (status != OK) return AssertionFailure() << statusToString(status);
1824 return AssertionSuccess();
1825 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001826 };
1827
1828 class Client {
1829 public:
1830 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1831 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001832 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001833 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1834 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001835 mFdTrigger = FdTrigger::make();
1836 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1837 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1838 return AssertionSuccess();
1839 }
1840 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1841 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1842 return mCertVerifier;
1843 }
Yifan Hong67519322021-09-13 18:51:16 -07001844 // connect() and do handshake
1845 bool setUpTransport() {
1846 mFd = mConnectToServer();
1847 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1848 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1849 return mClientTransport != nullptr;
1850 }
1851 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1852 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1853 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001854 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001855 status_t readStatus =
1856 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001857 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001858 if (readStatus != OK) {
1859 return AssertionFailure() << statusToString(readStatus);
1860 }
1861 if (readMessage != expectedMessage) {
1862 return AssertionFailure()
1863 << "Expected " << expectedMessage << ", actual " << readMessage;
1864 }
1865 return AssertionSuccess();
1866 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001867 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001868 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001869 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1870 return;
1871 }
1872 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001873 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001874 }
1875
1876 private:
1877 ConnectToServer mConnectToServer;
1878 base::unique_fd mFd;
1879 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1880 std::unique_ptr<RpcTransportCtx> mCtx;
1881 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1882 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001883 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001884 };
1885
1886 // Make A trust B.
1887 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001888 static status_t trust(RpcSecurity rpcSecurity,
1889 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1890 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001891 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001892 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1893 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1894 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001895 }
1896
1897 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001898};
1899
1900class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1901public:
1902 using Server = RpcTransportTestUtils::Server;
1903 using Client = RpcTransportTestUtils::Client;
1904 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001905 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001906 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1907 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001908 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001909 return ret;
1910 }
1911 static std::vector<ParamType> getRpcTranportTestParams() {
1912 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001913 for (auto serverVersion : testVersions()) {
1914 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1915 for (auto rpcSecurity : RpcSecurityValues()) {
1916 switch (rpcSecurity) {
1917 case RpcSecurity::RAW: {
1918 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1919 } break;
1920 case RpcSecurity::TLS: {
1921 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1922 serverVersion);
1923 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1924 serverVersion);
1925 } break;
1926 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001927 }
1928 }
1929 }
1930 return ret;
1931 }
1932 template <typename A, typename B>
1933 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001934 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1935 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001936 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1937 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001938 void SetUp() override {
1939 if constexpr (!kEnableRpcThreads) {
1940 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1941 }
1942 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001943};
1944
1945TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001946 auto server = std::make_unique<Server>();
1947 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001948
1949 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001950 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001951
1952 ASSERT_EQ(OK, trust(&client, server));
1953 ASSERT_EQ(OK, trust(server, &client));
1954
1955 server->start();
1956 client.run();
1957}
1958
1959TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001960 auto server = std::make_unique<Server>();
1961 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001962
1963 std::vector<Client> clients;
1964 for (int i = 0; i < 2; i++) {
1965 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001966 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001967 ASSERT_EQ(OK, trust(&client, server));
1968 ASSERT_EQ(OK, trust(server, &client));
1969 }
1970
1971 server->start();
1972 for (auto& client : clients) client.run();
1973}
1974
1975TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001976 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1977 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001978
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001979 auto untrustedServer = std::make_unique<Server>();
1980 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001981
1982 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001983 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001984
1985 ASSERT_EQ(OK, trust(untrustedServer, &client));
1986
1987 untrustedServer->start();
1988
1989 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1990 // the client can't verify the server's identity.
1991 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1992 client.run(handshakeOk);
1993}
1994TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001995 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1996 (void)serverVersion;
1997
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001998 auto validServer = std::make_unique<Server>();
1999 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002000
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002001 auto maliciousServer = std::make_unique<Server>();
2002 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002003
2004 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002005 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002006
2007 ASSERT_EQ(OK, trust(&client, validServer));
2008 ASSERT_EQ(OK, trust(validServer, &client));
2009 ASSERT_EQ(OK, trust(maliciousServer, &client));
2010
2011 maliciousServer->start();
2012
2013 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2014 // the client can't verify the server's identity.
2015 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2016 client.run(handshakeOk);
2017}
2018
2019TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002020 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2021 (void)serverVersion;
2022
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002023 auto server = std::make_unique<Server>();
2024 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002025
2026 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002027 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002028
2029 ASSERT_EQ(OK, trust(&client, server));
2030
2031 server->start();
2032
2033 // For TLS, Client should be able to verify server's identity, so client should see
2034 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2035 // identity and should drop the connection, so client shouldn't be able to read anything.
2036 bool readOk = rpcSecurity != RpcSecurity::TLS;
2037 client.run(true, readOk);
2038}
2039
2040TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002041 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2042 (void)serverVersion;
2043
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002044 auto server = std::make_unique<Server>();
2045 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002046
2047 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002048 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002049 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002050 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002051
2052 ASSERT_EQ(OK, trust(&validClient, server));
2053 ASSERT_EQ(OK, trust(&maliciousClient, server));
2054
2055 server->start();
2056
2057 // See UntrustedClient.
2058 bool readOk = rpcSecurity != RpcSecurity::TLS;
2059 maliciousClient.run(true, readOk);
2060}
2061
Yifan Hong67519322021-09-13 18:51:16 -07002062TEST_P(RpcTransportTest, Trigger) {
2063 std::string msg2 = ", world!";
2064 std::mutex writeMutex;
2065 std::condition_variable writeCv;
2066 bool shouldContinueWriting = false;
2067 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002068 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002069 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002070 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2071 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002072 if (status != OK) return AssertionFailure() << statusToString(status);
2073
2074 {
2075 std::unique_lock<std::mutex> lock(writeMutex);
2076 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2077 return AssertionFailure() << "write barrier not cleared in time!";
2078 }
2079 }
2080
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002081 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002082 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2083 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002084 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002085 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002086 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002087 << statusToString(status);
2088 return AssertionSuccess();
2089 };
2090
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002091 auto server = std::make_unique<Server>();
2092 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002093
2094 // Set up client
2095 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002096 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002097
2098 // Exchange keys
2099 ASSERT_EQ(OK, trust(&client, server));
2100 ASSERT_EQ(OK, trust(server, &client));
2101
2102 server->setPostConnect(serverPostConnect);
2103
Yifan Hong67519322021-09-13 18:51:16 -07002104 server->start();
2105 // connect() to server and do handshake
2106 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002107 // read the first message. This ensures that server has finished handshake and start handling
2108 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002109 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002110 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2111 // write is on an FdTrigger that has been shut down.
2112 server->shutdown();
2113 // Continues server thread to write the second message.
2114 {
Yifan Hong22211f82021-09-14 12:32:25 -07002115 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002116 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002117 }
Yifan Hong22211f82021-09-14 12:32:25 -07002118 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002119 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002120 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002121 // On the client side, second read fails with DEAD_OBJECT
2122 ASSERT_FALSE(client.readMessage(msg2));
2123}
2124
Yifan Hong1deca4b2021-09-10 16:16:44 -07002125INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002126 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002127 RpcTransportTest::PrintParamInfo);
2128
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002129class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002130 : public testing::TestWithParam<
2131 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002132public:
2133 template <typename A, typename B>
2134 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002135 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2136 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002137 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2138 }
2139 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002140 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2141 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2142 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002143 };
2144};
2145
2146TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002147 if constexpr (!kEnableRpcThreads) {
2148 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2149 }
2150
Frederick Mayledc07cf82022-05-26 20:30:12 +00002151 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002152
2153 std::vector<uint8_t> pkeyData, certData;
2154 {
2155 auto pkey = makeKeyPairForSelfSignedCert();
2156 ASSERT_NE(nullptr, pkey);
2157 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2158 ASSERT_NE(nullptr, cert);
2159 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2160 certData = serializeCertificate(cert.get(), certificateFormat);
2161 }
2162
2163 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2164 auto desCert = deserializeCertificate(certData, certificateFormat);
2165 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002166 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2167 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002168
2169 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2170 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2171
2172 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2173 ASSERT_TRUE(client.setUp(utilsParam));
2174
2175 ASSERT_EQ(OK, trust(&client, server));
2176 ASSERT_EQ(OK, trust(server, &client));
2177
2178 server->start();
2179 client.run();
2180}
2181
2182INSTANTIATE_TEST_CASE_P(
2183 BinderRpc, RpcTransportTlsKeyTest,
2184 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2185 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002186 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2187 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002188 RpcTransportTlsKeyTest::PrintParamInfo);
2189
Steven Morelandc1635952021-04-01 16:20:47 +00002190} // namespace android
2191
2192int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002193 ::testing::InitGoogleTest(&argc, argv);
2194 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002195
Steven Moreland5553ac42020-11-11 02:14:45 +00002196 return RUN_ALL_TESTS();
2197}