blob: cfdfdf890765b992701cec7719bf5f5212168e1a [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
Steven Morelandbf57bce2021-07-26 15:26:12 -070057TEST(BinderRpc, CannotUseNextWireVersion) {
58 auto session = RpcSession::make();
59 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
60 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
61 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
62 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
63}
64
65TEST(BinderRpc, CanUseExperimentalWireVersion) {
66 auto session = RpcSession::make();
67 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
68}
69
Steven Moreland5553ac42020-11-11 02:14:45 +000070using android::binder::Status;
71
72#define EXPECT_OK(status) \
73 do { \
74 Status stat = (status); \
75 EXPECT_TRUE(stat.isOk()) << stat; \
76 } while (false)
77
Frederick Maylea12b0962022-06-25 01:13:22 +000078static std::string WaitStatusToString(int wstatus) {
79 if (WIFEXITED(wstatus)) {
80 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
81 }
82 if (WIFSIGNALED(wstatus)) {
83 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
84 }
85 return base::StringPrintf("unexpected state %d", wstatus);
86}
87
Steven Moreland5553ac42020-11-11 02:14:45 +000088class Process {
89public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -070090 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -070091 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
92 android::base::borrowed_fd /* readEnd */)>& f) {
93 android::base::unique_fd childWriteEnd;
94 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +000095 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
96 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +000097 if (0 == (mPid = fork())) {
98 // racey: assume parent doesn't crash before this is set
99 prctl(PR_SET_PDEATHSIG, SIGHUP);
100
Yifan Hong1deca4b2021-09-10 16:16:44 -0700101 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000102
103 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000104 }
105 }
106 ~Process() {
107 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000108 int wstatus;
109 waitpid(mPid, &wstatus, 0);
110 if (mCustomExitStatusCheck) {
111 mCustomExitStatusCheck(wstatus);
112 } else {
113 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
114 << "server process failed: " << WaitStatusToString(wstatus);
115 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000116 }
117 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700118 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700119 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000120
Frederick Maylea12b0962022-06-25 01:13:22 +0000121 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
122 mCustomExitStatusCheck = std::move(f);
123 }
124
Frederick Mayle69a0c992022-05-26 20:38:39 +0000125 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
126 void terminate() { kill(mPid, SIGTERM); }
127
Steven Moreland5553ac42020-11-11 02:14:45 +0000128private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000129 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000130 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700131 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700132 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000133};
134
135static std::string allocateSocketAddress() {
136 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000137 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700138 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
139 unlink(ret.c_str());
140 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000141};
142
Steven Morelandda573042021-06-12 01:13:45 +0000143static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000144 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000145 return vsockPort++;
146}
147
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000148struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000149 // reference to process hosting a socket server
150 Process host;
151
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000152 struct SessionInfo {
153 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000154 sp<IBinder> root;
155 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000156
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000157 // client session objects associated with other process
158 // each one represents a separate session
159 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000160
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000161 ProcessSession(ProcessSession&&) = default;
162 ~ProcessSession() {
163 for (auto& session : sessions) {
164 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000165 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000166
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000167 for (auto& info : sessions) {
168 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000169
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000170 EXPECT_NE(nullptr, session);
171 EXPECT_NE(nullptr, session->state());
172 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000173
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000174 wp<RpcSession> weakSession = session;
175 session = nullptr;
176 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000177 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000178 }
179};
180
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000181// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000182// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000183struct BinderRpcTestProcessSession {
184 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000185
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000186 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000187 sp<IBinder> rootBinder;
188
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000189 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000190 sp<IBinderRpcTest> rootIface;
191
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000192 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000193 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000194
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000195 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
196 ~BinderRpcTestProcessSession() {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000197 if (!expectAlreadyShutdown) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000198 EXPECT_NE(nullptr, rootIface);
199 if (rootIface == nullptr) return;
200
Steven Moreland736664b2021-05-01 04:27:25 +0000201 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000202 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000203 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000204 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000205 for (auto remoteCount : remoteCounts) {
206 EXPECT_EQ(remoteCount, 1);
207 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000208
Steven Moreland798e0d12021-07-14 23:19:25 +0000209 // even though it is on another thread, shutdown races with
210 // the transaction reply being written
211 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
212 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
213 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000214 }
215
216 rootIface = nullptr;
217 rootBinder = nullptr;
218 }
219};
220
Yifan Hong1deca4b2021-09-10 16:16:44 -0700221static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700222 base::unique_fd serverFd(
223 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
224 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700225 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
226 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700227
228 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
229 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700230 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
231 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700232 }
233 return serverFd;
234}
235
Andrei Homescu2a298012022-06-15 01:08:54 +0000236using RunServiceFn = void (*)(android::base::borrowed_fd writeEnd,
237 android::base::borrowed_fd readEnd);
238
239class BinderRpc : public ::testing::TestWithParam<
240 std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t, bool, bool>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000241public:
Frederick Mayle69a0c992022-05-26 20:38:39 +0000242 SocketType socketType() const { return std::get<0>(GetParam()); }
243 RpcSecurity rpcSecurity() const { return std::get<1>(GetParam()); }
244 uint32_t clientVersion() const { return std::get<2>(GetParam()); }
245 uint32_t serverVersion() const { return std::get<3>(GetParam()); }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000246 bool serverSingleThreaded() const { return std::get<4>(GetParam()); }
Andrei Homescu2a298012022-06-15 01:08:54 +0000247 bool noKernel() const { return std::get<5>(GetParam()); }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000248
Andrei Homescua858b0e2022-08-01 23:43:09 +0000249 bool clientOrServerSingleThreaded() const {
250 return !kEnableRpcThreads || serverSingleThreaded();
251 }
252
Frederick Mayle69a0c992022-05-26 20:38:39 +0000253 // Whether the test params support sending FDs in parcels.
254 bool supportsFdTransport() const {
255 return clientVersion() >= 1 && serverVersion() >= 1 && rpcSecurity() != RpcSecurity::TLS &&
256 (socketType() == SocketType::PRECONNECTED || socketType() == SocketType::UNIX);
257 }
258
Yifan Hong702115c2021-06-24 15:39:18 -0700259 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000260 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
261 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
Frederick Mayledc07cf82022-05-26 20:30:12 +0000262 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Andrei Homescu2a298012022-06-15 01:08:54 +0000263 if (singleThreaded) {
264 ret += "_single_threaded";
265 }
266 if (noKernel) {
267 ret += "_no_kernel";
268 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700269 return ret;
270 }
271
Steven Morelandc1635952021-04-01 16:20:47 +0000272 // This creates a new process serving an interface on a certain number of
273 // threads.
Andrei Homescu2a298012022-06-15 01:08:54 +0000274 ProcessSession createRpcTestSocketServerProcessEtc(const BinderRpcOptions& options) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000275 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000276
Yifan Hong702115c2021-06-24 15:39:18 -0700277 SocketType socketType = std::get<0>(GetParam());
278 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000279 uint32_t clientVersion = std::get<2>(GetParam());
280 uint32_t serverVersion = std::get<3>(GetParam());
Andrei Homescu2a298012022-06-15 01:08:54 +0000281 bool singleThreaded = std::get<4>(GetParam());
282 bool noKernel = std::get<5>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000283
Andrei Homescu2a298012022-06-15 01:08:54 +0000284 std::string path = android::base::GetExecutableDirectory();
285 auto servicePath =
286 android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
287 singleThreaded ? "_single_threaded" : "",
288 noKernel ? "_no_kernel" : "");
Steven Morelandc1635952021-04-01 16:20:47 +0000289
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000290 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000291 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700292 android::base::borrowed_fd readEnd) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000293 auto writeFd = std::to_string(writeEnd.get());
294 auto readFd = std::to_string(readEnd.get());
295 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
296 NULL);
Steven Morelandc1635952021-04-01 16:20:47 +0000297 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000298 };
299
Andrei Homescu2a298012022-06-15 01:08:54 +0000300 BinderRpcTestServerConfig serverConfig;
301 serverConfig.numThreads = options.numThreads;
302 serverConfig.socketType = static_cast<int32_t>(socketType);
303 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
304 serverConfig.serverVersion = serverVersion;
305 serverConfig.vsockPort = allocateVsockPort();
306 serverConfig.addr = allocateSocketAddress();
307 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
308 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
309 static_cast<int32_t>(mode));
310 }
311 writeToFd(ret.host.writeEnd(), serverConfig);
312
Yifan Hong1deca4b2021-09-10 16:16:44 -0700313 std::vector<sp<RpcSession>> sessions;
314 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
315 for (size_t i = 0; i < options.numSessions; i++) {
316 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
317 }
318
319 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
320 BinderRpcTestClientInfo clientInfo;
321 for (const auto& session : sessions) {
322 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700323 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700324 }
325 writeToFd(ret.host.writeEnd(), clientInfo);
326
327 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700328 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700329 CHECK_NE(0, serverInfo.port);
330 }
331
332 if (rpcSecurity == RpcSecurity::TLS) {
333 const auto& serverCert = serverInfo.cert.data;
334 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700335 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
336 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700337 }
338
Steven Moreland2372f9d2021-08-05 15:42:01 -0700339 status_t status;
340
Yifan Hong1deca4b2021-09-10 16:16:44 -0700341 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000342 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700343 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700344 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000345 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Moreland659416d2021-05-11 00:47:50 +0000346
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000347 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700348 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700349 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000350 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700351 });
Steven Moreland4198a122021-08-03 17:37:58 -0700352 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000353 case SocketType::UNIX:
Andrei Homescu2a298012022-06-15 01:08:54 +0000354 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000355 break;
356 case SocketType::VSOCK:
Andrei Homescu2a298012022-06-15 01:08:54 +0000357 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000358 break;
359 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700360 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000361 break;
362 default:
363 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000364 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000365 if (options.allowConnectFailure && status != OK) {
366 ret.sessions.clear();
367 break;
368 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700369 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000370 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000371 }
Steven Morelandc1635952021-04-01 16:20:47 +0000372 return ret;
373 }
374
Andrei Homescu2a298012022-06-15 01:08:54 +0000375 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const BinderRpcOptions& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000376 BinderRpcTestProcessSession ret{
Andrei Homescu2a298012022-06-15 01:08:54 +0000377 .proc = createRpcTestSocketServerProcessEtc(options),
Steven Morelandc1635952021-04-01 16:20:47 +0000378 };
379
Frederick Mayle69a0c992022-05-26 20:38:39 +0000380 ret.rootBinder = ret.proc.sessions.empty() ? nullptr : ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000381 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
382
383 return ret;
384 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700385
386 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
387 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000388};
389
Steven Morelandc1635952021-04-01 16:20:47 +0000390TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000391 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000392 ASSERT_NE(proc.rootBinder, nullptr);
393 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
394}
395
Steven Moreland4cf688f2021-03-31 01:48:58 +0000396TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000397 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000398 ASSERT_NE(proc.rootBinder, nullptr);
399 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
400}
401
Andrei Homescua858b0e2022-08-01 23:43:09 +0000402TEST_P(BinderRpc, MultipleSessions) {
403 if (serverSingleThreaded()) {
404 // Tests with multiple sessions require a multi-threaded service,
405 // but work fine on a single-threaded client
406 GTEST_SKIP() << "This test requires a multi-threaded service";
407 }
408
Steven Moreland4313d7e2021-07-15 23:41:22 +0000409 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000410 for (auto session : proc.proc.sessions) {
411 ASSERT_NE(nullptr, session.root);
412 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000413 }
414}
415
Andrei Homescua858b0e2022-08-01 23:43:09 +0000416TEST_P(BinderRpc, SeparateRootObject) {
417 if (serverSingleThreaded()) {
418 GTEST_SKIP() << "This test requires a multi-threaded service";
419 }
420
Steven Moreland51c44a92021-10-14 16:50:35 -0700421 SocketType type = std::get<0>(GetParam());
422 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
423 // we can't get port numbers for unix sockets
424 return;
425 }
426
427 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
428
429 int port1 = 0;
430 EXPECT_OK(proc.rootIface->getClientPort(&port1));
431
432 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
433 int port2;
434 EXPECT_OK(rootIface2->getClientPort(&port2));
435
436 // we should have a different IBinderRpcTest object created for each
437 // session, because we use setPerSessionRootObject
438 EXPECT_NE(port1, port2);
439}
440
Steven Morelandc1635952021-04-01 16:20:47 +0000441TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000442 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000443 Parcel data;
444 Parcel reply;
445 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
446}
447
Steven Moreland67753c32021-04-02 18:45:19 +0000448TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700449 auto proc1 = createRpcTestSocketServerProcess({});
450 auto proc2 = createRpcTestSocketServerProcess({});
451
452 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000453
454 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700455 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000456 p1.writeInt32(3);
457
Frederick Maylea4ed5672022-06-17 22:03:38 +0000458 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700459 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
460
Steven Moreland67753c32021-04-02 18:45:19 +0000461 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700462 p2.markForBinder(proc2.rootBinder);
463 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000464
465 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
466 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
467}
468
Steven Morelandc1635952021-04-01 16:20:47 +0000469TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000470 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000471 Parcel data;
472 data.markForBinder(proc.rootBinder);
473 Parcel reply;
474 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
475}
476
Steven Morelandc1635952021-04-01 16:20:47 +0000477TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000478 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000479 EXPECT_OK(proc.rootIface->sendString("asdf"));
480}
481
Steven Morelandc1635952021-04-01 16:20:47 +0000482TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000483 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000484 std::string doubled;
485 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
486 EXPECT_EQ("cool cool ", doubled);
487}
488
Steven Morelandc1635952021-04-01 16:20:47 +0000489TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000490 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000491 std::string single = std::string(1024, 'a');
492 std::string doubled;
493 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
494 EXPECT_EQ(single + single, doubled);
495}
496
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000497TEST_P(BinderRpc, InvalidNullBinderReturn) {
498 auto proc = createRpcTestSocketServerProcess({});
499
500 sp<IBinder> outBinder;
501 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
502}
503
Steven Morelandc1635952021-04-01 16:20:47 +0000504TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000505 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000506
507 int32_t pingResult;
508 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
509 EXPECT_EQ(OK, pingResult);
510
511 EXPECT_EQ(0, MyBinderRpcSession::gNum);
512}
513
Steven Morelandc1635952021-04-01 16:20:47 +0000514TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000515 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000516
517 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
518 sp<IBinder> outBinder;
519 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
520 EXPECT_EQ(inBinder, outBinder);
521
522 wp<IBinder> weak = inBinder;
523 inBinder = nullptr;
524 outBinder = nullptr;
525
526 // Force reading a reply, to process any pending dec refs from the other
527 // process (the other process will process dec refs there before processing
528 // the ping here).
529 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
530
531 EXPECT_EQ(nullptr, weak.promote());
532
533 EXPECT_EQ(0, MyBinderRpcSession::gNum);
534}
535
Steven Morelandc1635952021-04-01 16:20:47 +0000536TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000537 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000538
539 sp<IBinderRpcSession> session;
540 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
541
542 sp<IBinder> inBinder = IInterface::asBinder(session);
543 sp<IBinder> outBinder;
544 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
545 EXPECT_EQ(inBinder, outBinder);
546
547 wp<IBinder> weak = inBinder;
548 session = nullptr;
549 inBinder = nullptr;
550 outBinder = nullptr;
551
552 // Force reading a reply, to process any pending dec refs from the other
553 // process (the other process will process dec refs there before processing
554 // the ping here).
555 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
556
557 EXPECT_EQ(nullptr, weak.promote());
558}
559
Steven Morelandc1635952021-04-01 16:20:47 +0000560TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000561 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000562
563 sp<IBinder> outBinder;
564 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
565 EXPECT_EQ(nullptr, outBinder);
566}
567
Steven Morelandc1635952021-04-01 16:20:47 +0000568TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000569 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000570
571 IBinder* ptr = nullptr;
572 {
573 sp<IBinder> binder = new BBinder();
574 ptr = binder.get();
575 EXPECT_OK(proc.rootIface->holdBinder(binder));
576 }
577
578 sp<IBinder> held;
579 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
580
581 EXPECT_EQ(held.get(), ptr);
582
583 // stop holding binder, because we test to make sure references are cleaned
584 // up
585 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
586 // and flush ref counts
587 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
588}
589
590// START TESTS FOR LIMITATIONS OF SOCKET BINDER
591// These are behavioral differences form regular binder, where certain usecases
592// aren't supported.
593
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000594TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000595 auto proc1 = createRpcTestSocketServerProcess({});
596 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000597
598 sp<IBinder> outBinder;
599 EXPECT_EQ(INVALID_OPERATION,
600 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
601}
602
Andrei Homescua858b0e2022-08-01 23:43:09 +0000603TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
604 if (serverSingleThreaded()) {
605 GTEST_SKIP() << "This test requires a multi-threaded service";
606 }
607
Steven Moreland4313d7e2021-07-15 23:41:22 +0000608 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000609
610 sp<IBinder> outBinder;
611 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000612 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000613 .transactionError());
614}
615
Steven Morelandc1635952021-04-01 16:20:47 +0000616TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000617 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000618 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
619 "at build time.";
620 }
621
Steven Moreland4313d7e2021-07-15 23:41:22 +0000622 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000623
624 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
625 sp<IBinder> outBinder;
626 EXPECT_EQ(INVALID_OPERATION,
627 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
628}
629
Steven Morelandc1635952021-04-01 16:20:47 +0000630TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000631 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000632 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
633 "at build time.";
634 }
635
Steven Moreland4313d7e2021-07-15 23:41:22 +0000636 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000637
638 // for historical reasons, IServiceManager interface only returns the
639 // exception code
640 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
641 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
642}
643
644// END TESTS FOR LIMITATIONS OF SOCKET BINDER
645
Steven Morelandc1635952021-04-01 16:20:47 +0000646TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000647 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000648
649 sp<IBinder> outBinder;
650 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
651 EXPECT_EQ(proc.rootBinder, outBinder);
652}
653
Steven Morelandc1635952021-04-01 16:20:47 +0000654TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000655 auto proc = createRpcTestSocketServerProcess({
656 // Enable FD support because it uses more stack space and so represents
657 // something closer to a worst case scenario.
658 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
659 .serverSupportedFileDescriptorTransportModes =
660 {RpcSession::FileDescriptorTransportMode::UNIX},
661 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000662
663 auto nastyNester = sp<MyBinderRpcTest>::make();
664 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
665
666 wp<IBinder> weak = nastyNester;
667 nastyNester = nullptr;
668 EXPECT_EQ(nullptr, weak.promote());
669}
670
Steven Morelandc1635952021-04-01 16:20:47 +0000671TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000672 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000673
674 sp<IBinder> a;
675 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
676
677 sp<IBinder> b;
678 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
679
680 EXPECT_EQ(a, b);
681}
682
Steven Morelandc1635952021-04-01 16:20:47 +0000683TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000684 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000685
686 sp<IBinder> a;
687 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
688 wp<IBinder> weak = a;
689 a = nullptr;
690
691 sp<IBinder> b;
692 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
693
694 // this is the wrong behavior, since BpBinder
695 // doesn't implement onIncStrongAttempted
696 // but make sure there is no crash
697 EXPECT_EQ(nullptr, weak.promote());
698
699 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
700
701 // In order to fix this:
702 // - need to have incStrongAttempted reflected across IPC boundary (wait for
703 // response to promote - round trip...)
704 // - sendOnLastWeakRef, to delete entries out of RpcState table
705 EXPECT_EQ(b, weak.promote());
706}
707
708#define expectSessions(expected, iface) \
709 do { \
710 int session; \
711 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
712 EXPECT_EQ(expected, session); \
713 } while (false)
714
Steven Morelandc1635952021-04-01 16:20:47 +0000715TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000716 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000717
718 sp<IBinderRpcSession> session;
719 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
720 std::string out;
721 EXPECT_OK(session->getName(&out));
722 EXPECT_EQ("aoeu", out);
723
724 expectSessions(1, proc.rootIface);
725 session = nullptr;
726 expectSessions(0, proc.rootIface);
727}
728
Steven Morelandc1635952021-04-01 16:20:47 +0000729TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000730 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000731
732 std::vector<sp<IBinderRpcSession>> sessions;
733
734 for (size_t i = 0; i < 15; i++) {
735 expectSessions(i, proc.rootIface);
736 sp<IBinderRpcSession> session;
737 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
738 sessions.push_back(session);
739 }
740 expectSessions(sessions.size(), proc.rootIface);
741 for (size_t i = 0; i < sessions.size(); i++) {
742 std::string out;
743 EXPECT_OK(sessions.at(i)->getName(&out));
744 EXPECT_EQ(std::to_string(i), out);
745 }
746 expectSessions(sessions.size(), proc.rootIface);
747
748 while (!sessions.empty()) {
749 sessions.pop_back();
750 expectSessions(sessions.size(), proc.rootIface);
751 }
752 expectSessions(0, proc.rootIface);
753}
754
755size_t epochMillis() {
756 using std::chrono::duration_cast;
757 using std::chrono::milliseconds;
758 using std::chrono::seconds;
759 using std::chrono::system_clock;
760 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
761}
762
Andrei Homescua858b0e2022-08-01 23:43:09 +0000763TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
764 if (clientOrServerSingleThreaded()) {
765 GTEST_SKIP() << "This test requires multiple threads";
766 }
767
Steven Moreland5553ac42020-11-11 02:14:45 +0000768 constexpr size_t kNumThreads = 10;
769
Steven Moreland4313d7e2021-07-15 23:41:22 +0000770 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000771
772 EXPECT_OK(proc.rootIface->lock());
773
774 // block all but one thread taking locks
775 std::vector<std::thread> ts;
776 for (size_t i = 0; i < kNumThreads - 1; i++) {
777 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
778 }
779
780 usleep(100000); // give chance for calls on other threads
781
782 // other calls still work
783 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
784
785 constexpr size_t blockTimeMs = 500;
786 size_t epochMsBefore = epochMillis();
787 // after this, we should never see a response within this time
788 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
789
790 // this call should be blocked for blockTimeMs
791 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
792
793 size_t epochMsAfter = epochMillis();
794 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
795
796 for (auto& t : ts) t.join();
797}
798
Yifan Hong1f44f982021-10-08 17:16:47 -0700799void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
800 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000801 size_t epochMsBefore = epochMillis();
802
803 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700804 for (size_t i = 0; i < numCalls; i++) {
805 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000806 }
807
808 for (auto& t : ts) t.join();
809
810 size_t epochMsAfter = epochMillis();
811
Yifan Hong1f44f982021-10-08 17:16:47 -0700812 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000813
814 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700815 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
816}
817
Andrei Homescua858b0e2022-08-01 23:43:09 +0000818TEST_P(BinderRpc, ThreadPoolOverSaturated) {
819 if (clientOrServerSingleThreaded()) {
820 GTEST_SKIP() << "This test requires multiple threads";
821 }
822
Yifan Hong1f44f982021-10-08 17:16:47 -0700823 constexpr size_t kNumThreads = 10;
824 constexpr size_t kNumCalls = kNumThreads + 3;
825 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
826 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
827}
828
Andrei Homescua858b0e2022-08-01 23:43:09 +0000829TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
830 if (clientOrServerSingleThreaded()) {
831 GTEST_SKIP() << "This test requires multiple threads";
832 }
833
Yifan Hong1f44f982021-10-08 17:16:47 -0700834 constexpr size_t kNumThreads = 20;
835 constexpr size_t kNumOutgoingConnections = 10;
836 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
837 auto proc = createRpcTestSocketServerProcess(
838 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
839 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000840}
841
Andrei Homescua858b0e2022-08-01 23:43:09 +0000842TEST_P(BinderRpc, ThreadingStressTest) {
843 if (clientOrServerSingleThreaded()) {
844 GTEST_SKIP() << "This test requires multiple threads";
845 }
846
Steven Moreland5553ac42020-11-11 02:14:45 +0000847 constexpr size_t kNumClientThreads = 10;
848 constexpr size_t kNumServerThreads = 10;
849 constexpr size_t kNumCalls = 100;
850
Steven Moreland4313d7e2021-07-15 23:41:22 +0000851 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000852
853 std::vector<std::thread> threads;
854 for (size_t i = 0; i < kNumClientThreads; i++) {
855 threads.push_back(std::thread([&] {
856 for (size_t j = 0; j < kNumCalls; j++) {
857 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000858 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000859 EXPECT_EQ(proc.rootBinder, out);
860 }
861 }));
862 }
863
864 for (auto& t : threads) t.join();
865}
866
Steven Moreland925ba0a2021-09-17 18:06:32 -0700867static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
868 std::vector<std::thread> threads;
869 for (size_t i = 0; i < threadCount; i++) {
870 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
871 }
872 for (auto& t : threads) t.join();
873}
874
Andrei Homescua858b0e2022-08-01 23:43:09 +0000875TEST_P(BinderRpc, OnewayStressTest) {
876 if (clientOrServerSingleThreaded()) {
877 GTEST_SKIP() << "This test requires multiple threads";
878 }
879
Steven Morelandc6046982021-04-20 00:49:42 +0000880 constexpr size_t kNumClientThreads = 10;
881 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700882 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000883
Steven Moreland4313d7e2021-07-15 23:41:22 +0000884 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000885
886 std::vector<std::thread> threads;
887 for (size_t i = 0; i < kNumClientThreads; i++) {
888 threads.push_back(std::thread([&] {
889 for (size_t j = 0; j < kNumCalls; j++) {
890 EXPECT_OK(proc.rootIface->sendString("a"));
891 }
Steven Morelandc6046982021-04-20 00:49:42 +0000892 }));
893 }
894
895 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700896
897 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000898}
899
Steven Morelandc1635952021-04-01 16:20:47 +0000900TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000901 constexpr size_t kReallyLongTimeMs = 100;
902 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
903
Steven Moreland4313d7e2021-07-15 23:41:22 +0000904 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000905
906 size_t epochMsBefore = epochMillis();
907
908 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
909
910 size_t epochMsAfter = epochMillis();
911 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
912}
913
Andrei Homescua858b0e2022-08-01 23:43:09 +0000914TEST_P(BinderRpc, OnewayCallQueueing) {
915 if (clientOrServerSingleThreaded()) {
916 GTEST_SKIP() << "This test requires multiple threads";
917 }
918
Steven Moreland5553ac42020-11-11 02:14:45 +0000919 constexpr size_t kNumSleeps = 10;
920 constexpr size_t kNumExtraServerThreads = 4;
921 constexpr size_t kSleepMs = 50;
922
923 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000924 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000925
926 EXPECT_OK(proc.rootIface->lock());
927
Steven Moreland1c678802021-09-17 16:48:47 -0700928 size_t epochMsBefore = epochMillis();
929
930 // all these *Async commands should be queued on the server sequentially,
931 // even though there are multiple threads.
932 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000933 proc.rootIface->sleepMsAsync(kSleepMs);
934 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000935 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
936
Steven Moreland1c678802021-09-17 16:48:47 -0700937 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000938 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700939
Steven Moreland5553ac42020-11-11 02:14:45 +0000940 size_t epochMsAfter = epochMillis();
941
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000942 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000943
Steven Moreland925ba0a2021-09-17 18:06:32 -0700944 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000945}
946
Andrei Homescua858b0e2022-08-01 23:43:09 +0000947TEST_P(BinderRpc, OnewayCallExhaustion) {
948 if (clientOrServerSingleThreaded()) {
949 GTEST_SKIP() << "This test requires multiple threads";
950 }
951
Steven Morelandd45be622021-06-04 02:19:37 +0000952 constexpr size_t kNumClients = 2;
953 constexpr size_t kTooLongMs = 1000;
954
Steven Moreland4313d7e2021-07-15 23:41:22 +0000955 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000956
957 // Build up oneway calls on the second session to make sure it terminates
958 // and shuts down. The first session should be unaffected (proc destructor
959 // checks the first session).
960 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
961
962 std::vector<std::thread> threads;
963 for (size_t i = 0; i < kNumClients; i++) {
964 // one of these threads will get stuck queueing a transaction once the
965 // socket fills up, the other will be able to fill up transactions on
966 // this object
967 threads.push_back(std::thread([&] {
968 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
969 }
970 }));
971 }
972 for (auto& t : threads) t.join();
973
974 Status status = iface->sleepMsAsync(kTooLongMs);
975 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
976
Steven Moreland798e0d12021-07-14 23:19:25 +0000977 // now that it has died, wait for the remote session to shutdown
978 std::vector<int32_t> remoteCounts;
979 do {
980 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
981 } while (remoteCounts.size() == kNumClients);
982
Steven Morelandd45be622021-06-04 02:19:37 +0000983 // the second session should be shutdown in the other process by the time we
984 // are able to join above (it'll only be hung up once it finishes processing
985 // any pending commands). We need to erase this session from the record
986 // here, so that the destructor for our session won't check that this
987 // session is valid, but we still want it to test the other session.
988 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
989}
990
Steven Moreland659416d2021-05-11 00:47:50 +0000991TEST_P(BinderRpc, Callbacks) {
992 const static std::string kTestString = "good afternoon!";
993
Steven Morelandc7d40132021-06-10 03:42:11 +0000994 for (bool callIsOneway : {true, false}) {
995 for (bool callbackIsOneway : {true, false}) {
996 for (bool delayed : {true, false}) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000997 if (clientOrServerSingleThreaded() &&
998 (callIsOneway || callbackIsOneway || delayed)) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000999 // we have no incoming connections to receive the callback
1000 continue;
1001 }
1002
Andrei Homescua858b0e2022-08-01 23:43:09 +00001003 size_t numIncomingConnections = clientOrServerSingleThreaded() ? 0 : 1;
Steven Moreland4313d7e2021-07-15 23:41:22 +00001004 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +00001005 {.numThreads = 1,
1006 .numSessions = 1,
Andrei Homescu2a298012022-06-15 01:08:54 +00001007 .numIncomingConnections = numIncomingConnections});
Steven Morelandc7d40132021-06-10 03:42:11 +00001008 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001009
Steven Morelandc7d40132021-06-10 03:42:11 +00001010 if (callIsOneway) {
1011 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1012 kTestString));
1013 } else {
1014 EXPECT_OK(
1015 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1016 }
Steven Moreland659416d2021-05-11 00:47:50 +00001017
Steven Moreland03ecce62022-05-13 23:22:05 +00001018 // if both transactions are synchronous and the response is sent back on the
1019 // same thread, everything should have happened in a nested call. Otherwise,
1020 // the callback will be processed on another thread.
1021 if (callIsOneway || callbackIsOneway || delayed) {
1022 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001023 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001024 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1025 }
Steven Moreland659416d2021-05-11 00:47:50 +00001026
Steven Morelandc7d40132021-06-10 03:42:11 +00001027 EXPECT_EQ(cb->mValues.size(), 1)
1028 << "callIsOneway: " << callIsOneway
1029 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1030 if (cb->mValues.empty()) continue;
1031 EXPECT_EQ(cb->mValues.at(0), kTestString)
1032 << "callIsOneway: " << callIsOneway
1033 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001034
Steven Morelandc7d40132021-06-10 03:42:11 +00001035 // since we are severing the connection, we need to go ahead and
1036 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001037 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1038 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1039 }
Steven Moreland659416d2021-05-11 00:47:50 +00001040
Steven Moreland1b304292021-07-15 22:59:34 +00001041 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001042 // need to manually shut it down
1043 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Morelandc7d40132021-06-10 03:42:11 +00001044 proc.expectAlreadyShutdown = true;
1045 }
Steven Moreland659416d2021-05-11 00:47:50 +00001046 }
1047 }
1048}
1049
Devin Moore66d5b7a2022-07-07 21:42:10 +00001050TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001051 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001052 GTEST_SKIP() << "This test requires multiple threads";
1053 }
1054 class MyDeathRec : public IBinder::DeathRecipient {
1055 public:
1056 void binderDied(const wp<IBinder>& /* who */) override {
1057 dead = true;
1058 mCv.notify_one();
1059 }
1060 std::mutex mMtx;
1061 std::condition_variable mCv;
1062 bool dead = false;
1063 };
1064
1065 // Death recipient needs to have an incoming connection to be called
1066 auto proc = createRpcTestSocketServerProcess(
1067 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1068
1069 auto dr = sp<MyDeathRec>::make();
1070 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1071
1072 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1073 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1074 }
1075
1076 std::unique_lock<std::mutex> lock(dr->mMtx);
Devin Moore47a12012022-08-19 21:16:17 +00001077 ASSERT_TRUE(dr->mCv.wait_for(lock, 1000ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001078
1079 // need to wait for the session to shutdown so we don't "Leak session"
1080 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1081 proc.expectAlreadyShutdown = true;
1082}
1083
1084TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001085 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001086 GTEST_SKIP() << "This test requires multiple threads";
1087 }
1088 class MyDeathRec : public IBinder::DeathRecipient {
1089 public:
1090 void binderDied(const wp<IBinder>& /* who */) override {
1091 dead = true;
1092 mCv.notify_one();
1093 }
1094 std::mutex mMtx;
1095 std::condition_variable mCv;
1096 bool dead = false;
1097 };
1098
1099 // Death recipient needs to have an incoming connection to be called
1100 auto proc = createRpcTestSocketServerProcess(
1101 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1102
1103 auto dr = sp<MyDeathRec>::make();
1104 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1105
1106 // Explicitly calling shutDownAndWait will cause the death recipients
1107 // to be called.
1108 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1109
1110 std::unique_lock<std::mutex> lock(dr->mMtx);
1111 if (!dr->dead) {
1112 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1113 }
1114 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1115
1116 proc.proc.host.terminate();
1117 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1118 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1119 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1120 });
1121 proc.expectAlreadyShutdown = true;
1122}
1123
1124TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1125 class MyDeathRec : public IBinder::DeathRecipient {
1126 public:
1127 void binderDied(const wp<IBinder>& /* who */) override {}
1128 };
1129
1130 auto proc = createRpcTestSocketServerProcess(
1131 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1132
1133 auto dr = sp<MyDeathRec>::make();
1134 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1135 "Cannot register a DeathRecipient without any incoming connections.");
1136}
1137
1138TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001139 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001140 GTEST_SKIP() << "This test requires multiple threads";
1141 }
1142 class MyDeathRec : public IBinder::DeathRecipient {
1143 public:
1144 void binderDied(const wp<IBinder>& /* who */) override {
1145 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1146 }
1147 };
1148
1149 // Death recipient needs to have an incoming connection to be called
1150 auto proc = createRpcTestSocketServerProcess(
1151 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1152
1153 auto dr = sp<MyDeathRec>::make();
1154 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1155 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1156
1157 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1158 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1159 }
1160
1161 // need to wait for the session to shutdown so we don't "Leak session"
1162 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1163 proc.expectAlreadyShutdown = true;
1164}
1165
Steven Moreland195edb82021-06-08 02:44:39 +00001166TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001167 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001168 auto cb = sp<MyBinderRpcCallback>::make();
1169
1170 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1171 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1172}
1173
Steven Morelandc1635952021-04-01 16:20:47 +00001174TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001175 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001176 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001177
1178 // make sure there is some state during crash
1179 // 1. we hold their binder
1180 sp<IBinderRpcSession> session;
1181 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1182 // 2. they hold our binder
1183 sp<IBinder> binder = new BBinder();
1184 EXPECT_OK(proc.rootIface->holdBinder(binder));
1185
1186 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1187 << "Do death cleanup: " << doDeathCleanup;
1188
Frederick Maylea12b0962022-06-25 01:13:22 +00001189 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1190 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1191 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1192 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001193 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001194 }
1195}
1196
Steven Morelandd7302072021-05-15 01:32:04 +00001197TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001198 // This test only works if the current process shared the internal state of
1199 // ProcessState with the service across the call to fork(). Both the static
1200 // libraries and libbinder.so have their own separate copies of all the
1201 // globals, so the test only works when the test client and service both use
1202 // libbinder.so (when using static libraries, even a client and service
1203 // using the same kind of static library should have separate copies of the
1204 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +00001205 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001206 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1207 "at build time.";
1208 }
1209
Steven Moreland4313d7e2021-07-15 23:41:22 +00001210 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001211
Andrei Homescu2a298012022-06-15 01:08:54 +00001212 // we can't allocate IPCThreadState so actually the first time should
1213 // succeed :(
1214 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001215
1216 // second time! we catch the error :)
1217 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1218
Frederick Maylea12b0962022-06-25 01:13:22 +00001219 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1220 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1221 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1222 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001223 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001224}
1225
Frederick Mayle69a0c992022-05-26 20:38:39 +00001226TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1227 auto proc = createRpcTestSocketServerProcess({
1228 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1229 .serverSupportedFileDescriptorTransportModes =
1230 {RpcSession::FileDescriptorTransportMode::UNIX},
1231 .allowConnectFailure = true,
1232 });
1233 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1234 proc.proc.host.terminate();
1235 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1236 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1237 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1238 });
1239 proc.expectAlreadyShutdown = true;
1240}
1241
1242TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1243 auto proc = createRpcTestSocketServerProcess({
1244 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1245 .serverSupportedFileDescriptorTransportModes =
1246 {RpcSession::FileDescriptorTransportMode::NONE},
1247 .allowConnectFailure = true,
1248 });
1249 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1250 proc.proc.host.terminate();
1251 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1252 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1253 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1254 });
1255 proc.expectAlreadyShutdown = true;
1256}
1257
1258TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1259 auto proc = createRpcTestSocketServerProcess({
1260 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1261 .serverSupportedFileDescriptorTransportModes =
1262 {RpcSession::FileDescriptorTransportMode::NONE,
1263 RpcSession::FileDescriptorTransportMode::UNIX},
1264 });
1265
1266 android::os::ParcelFileDescriptor out;
1267 auto status = proc.rootIface->echoAsFile("hello", &out);
1268 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1269}
1270
1271TEST_P(BinderRpc, ReceiveFile) {
1272 auto proc = createRpcTestSocketServerProcess({
1273 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1274 .serverSupportedFileDescriptorTransportModes =
1275 {RpcSession::FileDescriptorTransportMode::UNIX},
1276 });
1277
1278 android::os::ParcelFileDescriptor out;
1279 auto status = proc.rootIface->echoAsFile("hello", &out);
1280 if (!supportsFdTransport()) {
1281 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1282 return;
1283 }
1284 ASSERT_TRUE(status.isOk()) << status;
1285
1286 std::string result;
1287 CHECK(android::base::ReadFdToString(out.get(), &result));
1288 EXPECT_EQ(result, "hello");
1289}
1290
1291TEST_P(BinderRpc, SendFiles) {
1292 auto proc = createRpcTestSocketServerProcess({
1293 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1294 .serverSupportedFileDescriptorTransportModes =
1295 {RpcSession::FileDescriptorTransportMode::UNIX},
1296 });
1297
1298 std::vector<android::os::ParcelFileDescriptor> files;
1299 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1300 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1301 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1302 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1303
1304 android::os::ParcelFileDescriptor out;
1305 auto status = proc.rootIface->concatFiles(files, &out);
1306 if (!supportsFdTransport()) {
1307 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1308 return;
1309 }
1310 ASSERT_TRUE(status.isOk()) << status;
1311
1312 std::string result;
1313 CHECK(android::base::ReadFdToString(out.get(), &result));
1314 EXPECT_EQ(result, "123abcd");
1315}
1316
1317TEST_P(BinderRpc, SendMaxFiles) {
1318 if (!supportsFdTransport()) {
1319 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1320 }
1321
1322 auto proc = createRpcTestSocketServerProcess({
1323 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1324 .serverSupportedFileDescriptorTransportModes =
1325 {RpcSession::FileDescriptorTransportMode::UNIX},
1326 });
1327
1328 std::vector<android::os::ParcelFileDescriptor> files;
1329 for (int i = 0; i < 253; i++) {
1330 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1331 }
1332
1333 android::os::ParcelFileDescriptor out;
1334 auto status = proc.rootIface->concatFiles(files, &out);
1335 ASSERT_TRUE(status.isOk()) << status;
1336
1337 std::string result;
1338 CHECK(android::base::ReadFdToString(out.get(), &result));
1339 EXPECT_EQ(result, std::string(253, 'a'));
1340}
1341
1342TEST_P(BinderRpc, SendTooManyFiles) {
1343 if (!supportsFdTransport()) {
1344 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1345 }
1346
1347 auto proc = createRpcTestSocketServerProcess({
1348 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1349 .serverSupportedFileDescriptorTransportModes =
1350 {RpcSession::FileDescriptorTransportMode::UNIX},
1351 });
1352
1353 std::vector<android::os::ParcelFileDescriptor> files;
1354 for (int i = 0; i < 254; i++) {
1355 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1356 }
1357
1358 android::os::ParcelFileDescriptor out;
1359 auto status = proc.rootIface->concatFiles(files, &out);
1360 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1361}
1362
Steven Moreland37aff182021-03-26 02:04:16 +00001363TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001364 if constexpr (!kEnableSharedLibs) {
1365 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1366 }
1367
Steven Moreland4313d7e2021-07-15 23:41:22 +00001368 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001369
1370 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1371 ASSERT_NE(binder, nullptr);
1372
1373 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1374}
1375
1376TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001377 if constexpr (!kEnableSharedLibs) {
1378 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1379 }
1380
Steven Moreland4313d7e2021-07-15 23:41:22 +00001381 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001382
1383 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1384 ASSERT_NE(binder, nullptr);
1385
1386 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1387 ASSERT_NE(ndkBinder, nullptr);
1388
1389 std::string out;
1390 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1391 ASSERT_TRUE(status.isOk()) << status.getDescription();
1392 ASSERT_EQ("aoeuaoeu", out);
1393}
1394
Steven Moreland5553ac42020-11-11 02:14:45 +00001395ssize_t countFds() {
1396 DIR* dir = opendir("/proc/self/fd/");
1397 if (dir == nullptr) return -1;
1398 ssize_t ret = 0;
1399 dirent* ent;
1400 while ((ent = readdir(dir)) != nullptr) ret++;
1401 closedir(dir);
1402 return ret;
1403}
1404
Andrei Homescua858b0e2022-08-01 23:43:09 +00001405TEST_P(BinderRpc, Fds) {
1406 if (serverSingleThreaded()) {
1407 GTEST_SKIP() << "This test requires multiple threads";
1408 }
1409
Steven Moreland5553ac42020-11-11 02:14:45 +00001410 ssize_t beforeFds = countFds();
1411 ASSERT_GE(beforeFds, 0);
1412 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001413 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001414 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1415 }
1416 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1417}
1418
Devin Moore800b2252021-10-15 16:22:57 +00001419TEST_P(BinderRpc, AidlDelegatorTest) {
1420 auto proc = createRpcTestSocketServerProcess({});
1421 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1422 ASSERT_NE(nullptr, myDelegator);
1423
1424 std::string doubled;
1425 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1426 EXPECT_EQ("cool cool ", doubled);
1427}
1428
Steven Morelandda573042021-06-12 01:13:45 +00001429static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001430 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001431 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001432
Andrei Homescu992a4052022-06-28 21:26:18 +00001433 android::base::unique_fd serverFd(
1434 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1435 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1436
1437 sockaddr_vm serverAddr{
1438 .svm_family = AF_VSOCK,
1439 .svm_port = vsockPort,
1440 .svm_cid = VMADDR_CID_ANY,
1441 };
1442 int ret = TEMP_FAILURE_RETRY(
1443 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1444 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1445 strerror(errno));
1446
1447 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1448 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1449 strerror(errno));
1450
1451 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1452 // to see if the kernel supports it. It's safe to use a blocking
1453 // connect because vsock sockets have a 2 second connection timeout,
1454 // and they return ETIMEDOUT after that.
1455 android::base::unique_fd connectFd(
1456 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1457 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1458 strerror(errno));
1459
1460 bool success = false;
1461 sockaddr_vm connectAddr{
1462 .svm_family = AF_VSOCK,
1463 .svm_port = vsockPort,
1464 .svm_cid = VMADDR_CID_LOCAL,
1465 };
1466 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1467 sizeof(connectAddr)));
1468 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1469 android::base::unique_fd acceptFd;
1470 while (true) {
1471 pollfd pfd[]{
1472 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1473 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1474 };
1475 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1476 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1477
1478 if (pfd[0].revents & POLLIN) {
1479 sockaddr_vm acceptAddr;
1480 socklen_t acceptAddrLen = sizeof(acceptAddr);
1481 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1482 reinterpret_cast<sockaddr*>(&acceptAddr),
1483 &acceptAddrLen, SOCK_CLOEXEC));
1484 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1485 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1486 "Truncated address");
1487
1488 // Store the fd in acceptFd so we keep the connection alive
1489 // while polling connectFd
1490 acceptFd.reset(ret);
1491 }
1492
1493 if (pfd[1].revents & POLLOUT) {
1494 // Connect either succeeded or timed out
1495 int connectErrno;
1496 socklen_t connectErrnoLen = sizeof(connectErrno);
1497 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1498 &connectErrnoLen);
1499 LOG_ALWAYS_FATAL_IF(ret == -1,
1500 "Could not getsockopt() after connect() "
1501 "on non-blocking socket: %s.",
1502 strerror(errno));
1503
1504 // We're done, this is all we wanted
1505 success = connectErrno == 0;
1506 break;
1507 }
1508 }
1509 } else {
1510 success = ret == 0;
1511 }
1512
1513 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1514
1515 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001516}
1517
Yifan Hong1deca4b2021-09-10 16:16:44 -07001518static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1519 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1520
1521 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001522
1523 static bool hasVsockLoopback = testSupportVsockLoopback();
1524
1525 if (hasVsockLoopback) {
1526 ret.push_back(SocketType::VSOCK);
1527 }
1528
1529 return ret;
1530}
1531
Frederick Mayledc07cf82022-05-26 20:30:12 +00001532static std::vector<uint32_t> testVersions() {
1533 std::vector<uint32_t> versions;
1534 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1535 versions.push_back(i);
1536 }
1537 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1538 return versions;
1539}
1540
Yifan Hong702115c2021-06-24 15:39:18 -07001541INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1542 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001543 ::testing::ValuesIn(RpcSecurityValues()),
1544 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001545 ::testing::ValuesIn(testVersions()),
1546 ::testing::Values(false, true),
1547 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001548 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001549
Yifan Hong702115c2021-06-24 15:39:18 -07001550class BinderRpcServerRootObject
1551 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001552
1553TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1554 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1555 auto setRootObject = [](bool isStrong) -> SetFn {
1556 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1557 };
1558
Yifan Hong702115c2021-06-24 15:39:18 -07001559 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1560 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001561 auto binder1 = sp<BBinder>::make();
1562 IBinder* binderRaw1 = binder1.get();
1563 setRootObject(isStrong1)(server.get(), binder1);
1564 EXPECT_EQ(binderRaw1, server->getRootObject());
1565 binder1.clear();
1566 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1567
1568 auto binder2 = sp<BBinder>::make();
1569 IBinder* binderRaw2 = binder2.get();
1570 setRootObject(isStrong2)(server.get(), binder2);
1571 EXPECT_EQ(binderRaw2, server->getRootObject());
1572 binder2.clear();
1573 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1574}
1575
1576INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001577 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1578 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001579
Yifan Hong1a235852021-05-13 16:07:47 -07001580class OneOffSignal {
1581public:
1582 // If notify() was previously called, or is called within |duration|, return true; else false.
1583 template <typename R, typename P>
1584 bool wait(std::chrono::duration<R, P> duration) {
1585 std::unique_lock<std::mutex> lock(mMutex);
1586 return mCv.wait_for(lock, duration, [this] { return mValue; });
1587 }
1588 void notify() {
1589 std::unique_lock<std::mutex> lock(mMutex);
1590 mValue = true;
1591 lock.unlock();
1592 mCv.notify_all();
1593 }
1594
1595private:
1596 std::mutex mMutex;
1597 std::condition_variable mCv;
1598 bool mValue = false;
1599};
1600
Yifan Hong194acf22021-06-29 18:44:56 -07001601TEST(BinderRpc, Java) {
1602#if !defined(__ANDROID__)
1603 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1604 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1605 "to binderHostDeviceTest. Hence, just disable this test on host.";
1606#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001607 if constexpr (!kEnableKernelIpc) {
1608 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1609 "at build time.";
1610 }
1611
Yifan Hong194acf22021-06-29 18:44:56 -07001612 sp<IServiceManager> sm = defaultServiceManager();
1613 ASSERT_NE(nullptr, sm);
1614 // Any Java service with non-empty getInterfaceDescriptor() would do.
1615 // Let's pick batteryproperties.
1616 auto binder = sm->checkService(String16("batteryproperties"));
1617 ASSERT_NE(nullptr, binder);
1618 auto descriptor = binder->getInterfaceDescriptor();
1619 ASSERT_GE(descriptor.size(), 0);
1620 ASSERT_EQ(OK, binder->pingBinder());
1621
1622 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001623 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001624 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001625 auto socket = rpcServer->releaseServer();
1626
1627 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001628 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1629
Yifan Honge3caaf22022-01-12 14:46:56 -08001630 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1631 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001632 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001633 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1634 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001635 << statusToString(setRpcClientDebugStatus);
1636 GTEST_SKIP();
1637 }
1638
1639 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001640
1641 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001642 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001643 auto rpcBinder = rpcSession->getRootObject();
1644 ASSERT_NE(nullptr, rpcBinder);
1645
1646 ASSERT_EQ(OK, rpcBinder->pingBinder());
1647
1648 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1649 << "getInterfaceDescriptor should not crash system_server";
1650 ASSERT_EQ(OK, rpcBinder->pingBinder());
1651}
1652
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001653class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1654public:
1655 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1656 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1657 std::to_string(std::get<1>(info.param));
1658 }
1659};
1660
1661TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1662 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1663 int sinkFd = sink.get();
1664 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1665 server->setProtocolVersion(std::get<1>(GetParam()));
1666 ASSERT_FALSE(server->hasServer());
1667 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1668 ASSERT_TRUE(server->hasServer());
1669 base::unique_fd retrieved = server->releaseServer();
1670 ASSERT_FALSE(server->hasServer());
1671 ASSERT_EQ(sinkFd, retrieved.get());
1672}
1673
1674TEST_P(BinderRpcServerOnly, Shutdown) {
1675 if constexpr (!kEnableRpcThreads) {
1676 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1677 }
1678
1679 auto addr = allocateSocketAddress();
1680 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1681 server->setProtocolVersion(std::get<1>(GetParam()));
1682 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1683 auto joinEnds = std::make_shared<OneOffSignal>();
1684
1685 // If things are broken and the thread never stops, don't block other tests. Because the thread
1686 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1687 // shared pointers are passed.
1688 std::thread([server, joinEnds] {
1689 server->join();
1690 joinEnds->notify();
1691 }).detach();
1692
1693 bool shutdown = false;
1694 for (int i = 0; i < 10 && !shutdown; i++) {
1695 usleep(300 * 1000); // 300ms; total 3s
1696 if (server->shutdown()) shutdown = true;
1697 }
1698 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1699
1700 ASSERT_TRUE(joinEnds->wait(2s))
1701 << "After server->shutdown() returns true, join() did not stop after 2s";
1702}
1703
Frederick Mayledc07cf82022-05-26 20:30:12 +00001704INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1705 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1706 ::testing::ValuesIn(testVersions())),
1707 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001708
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001709class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001710public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001711 // Only parameterized only server version because `RpcSession` is bypassed
1712 // in the client half of the tests.
1713 using Param =
1714 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001715 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001716
1717 // A server that handles client socket connections.
1718 class Server {
1719 public:
1720 explicit Server() {}
1721 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001722 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001723 [[nodiscard]] AssertionResult setUp(
1724 const Param& param,
1725 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001726 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001727 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001728 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001729 switch (socketType) {
1730 case SocketType::PRECONNECTED: {
1731 return AssertionFailure() << "Not supported by this test";
1732 } break;
1733 case SocketType::UNIX: {
1734 auto addr = allocateSocketAddress();
1735 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1736 if (status != OK) {
1737 return AssertionFailure()
1738 << "setupUnixDomainServer: " << statusToString(status);
1739 }
1740 mConnectToServer = [addr] {
1741 return connectTo(UnixSocketAddress(addr.c_str()));
1742 };
1743 } break;
1744 case SocketType::VSOCK: {
1745 auto port = allocateVsockPort();
1746 auto status = rpcServer->setupVsockServer(port);
1747 if (status != OK) {
1748 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1749 }
1750 mConnectToServer = [port] {
1751 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1752 };
1753 } break;
1754 case SocketType::INET: {
1755 unsigned int port;
1756 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1757 if (status != OK) {
1758 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1759 }
1760 mConnectToServer = [port] {
1761 const char* addr = kLocalInetAddress;
1762 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1763 if (aiStart == nullptr) return base::unique_fd{};
1764 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1765 auto fd = connectTo(
1766 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1767 if (fd.ok()) return fd;
1768 }
1769 ALOGE("None of the socket address resolved for %s:%u can be connected",
1770 addr, port);
1771 return base::unique_fd{};
1772 };
1773 }
1774 }
1775 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001776 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001777 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001778 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1779 mSetup = true;
1780 return AssertionSuccess();
1781 }
1782 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1783 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1784 return mCertVerifier;
1785 }
1786 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1787 void start() {
1788 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1789 mThread = std::make_unique<std::thread>(&Server::run, this);
1790 }
1791 void run() {
1792 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1793
1794 std::vector<std::thread> threads;
1795 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1796 base::unique_fd acceptedFd(
Pawan49d74cb2022-08-03 21:19:11 +00001797 TEMP_FAILURE_RETRY(accept4(mFd.fd.get(), nullptr, nullptr /*length*/,
Yifan Hong1deca4b2021-09-10 16:16:44 -07001798 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1799 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1800 }
1801
1802 for (auto& thread : threads) thread.join();
1803 }
1804 void handleOne(android::base::unique_fd acceptedFd) {
1805 ASSERT_TRUE(acceptedFd.ok());
Pawan49d74cb2022-08-03 21:19:11 +00001806 TransportFd transportFd(std::move(acceptedFd));
1807 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001808 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001809 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001810 }
Yifan Honge07d2732021-09-13 21:59:14 -07001811 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001812 shutdown();
1813 join();
1814 }
1815 void shutdown() { mFdTrigger->trigger(); }
1816
1817 void setPostConnect(
1818 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1819 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001820 }
1821
1822 private:
1823 std::unique_ptr<std::thread> mThread;
1824 ConnectToServer mConnectToServer;
1825 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
Pawan49d74cb2022-08-03 21:19:11 +00001826 TransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001827 std::unique_ptr<RpcTransportCtx> mCtx;
1828 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1829 std::make_shared<RpcCertificateVerifierSimple>();
1830 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001831 // The function invoked after connection and handshake. By default, it is
1832 // |defaultPostConnect| that sends |kMessage| to the client.
1833 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1834 Server::defaultPostConnect;
1835
1836 void join() {
1837 if (mThread != nullptr) {
1838 mThread->join();
1839 mThread = nullptr;
1840 }
1841 }
1842
1843 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1844 FdTrigger* fdTrigger) {
1845 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001846 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001847 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001848 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001849 if (status != OK) return AssertionFailure() << statusToString(status);
1850 return AssertionSuccess();
1851 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001852 };
1853
1854 class Client {
1855 public:
1856 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1857 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001858 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001859 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1860 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001861 mFdTrigger = FdTrigger::make();
1862 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1863 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1864 return AssertionSuccess();
1865 }
1866 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1867 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1868 return mCertVerifier;
1869 }
Yifan Hong67519322021-09-13 18:51:16 -07001870 // connect() and do handshake
1871 bool setUpTransport() {
1872 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001873 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001874 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1875 return mClientTransport != nullptr;
1876 }
1877 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1878 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1879 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001880 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001881 status_t readStatus =
1882 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001883 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001884 if (readStatus != OK) {
1885 return AssertionFailure() << statusToString(readStatus);
1886 }
1887 if (readMessage != expectedMessage) {
1888 return AssertionFailure()
1889 << "Expected " << expectedMessage << ", actual " << readMessage;
1890 }
1891 return AssertionSuccess();
1892 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001893 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001894 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001895 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1896 return;
1897 }
1898 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001899 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001900 }
1901
Pawan49d74cb2022-08-03 21:19:11 +00001902 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1903
Yifan Hong1deca4b2021-09-10 16:16:44 -07001904 private:
1905 ConnectToServer mConnectToServer;
Pawan49d74cb2022-08-03 21:19:11 +00001906 TransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001907 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1908 std::unique_ptr<RpcTransportCtx> mCtx;
1909 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1910 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001911 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001912 };
1913
1914 // Make A trust B.
1915 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001916 static status_t trust(RpcSecurity rpcSecurity,
1917 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1918 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001919 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001920 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1921 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1922 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001923 }
1924
1925 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001926};
1927
1928class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1929public:
1930 using Server = RpcTransportTestUtils::Server;
1931 using Client = RpcTransportTestUtils::Client;
1932 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001933 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001934 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1935 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001936 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001937 return ret;
1938 }
1939 static std::vector<ParamType> getRpcTranportTestParams() {
1940 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001941 for (auto serverVersion : testVersions()) {
1942 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1943 for (auto rpcSecurity : RpcSecurityValues()) {
1944 switch (rpcSecurity) {
1945 case RpcSecurity::RAW: {
1946 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1947 } break;
1948 case RpcSecurity::TLS: {
1949 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1950 serverVersion);
1951 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1952 serverVersion);
1953 } break;
1954 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001955 }
1956 }
1957 }
1958 return ret;
1959 }
1960 template <typename A, typename B>
1961 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001962 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1963 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001964 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1965 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001966 void SetUp() override {
1967 if constexpr (!kEnableRpcThreads) {
1968 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1969 }
1970 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001971};
1972
1973TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001974 auto server = std::make_unique<Server>();
1975 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001976
1977 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001978 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001979
1980 ASSERT_EQ(OK, trust(&client, server));
1981 ASSERT_EQ(OK, trust(server, &client));
1982
1983 server->start();
1984 client.run();
1985}
1986
1987TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001988 auto server = std::make_unique<Server>();
1989 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001990
1991 std::vector<Client> clients;
1992 for (int i = 0; i < 2; i++) {
1993 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001994 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001995 ASSERT_EQ(OK, trust(&client, server));
1996 ASSERT_EQ(OK, trust(server, &client));
1997 }
1998
1999 server->start();
2000 for (auto& client : clients) client.run();
2001}
2002
2003TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002004 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2005 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002006
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002007 auto untrustedServer = std::make_unique<Server>();
2008 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002009
2010 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002011 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002012
2013 ASSERT_EQ(OK, trust(untrustedServer, &client));
2014
2015 untrustedServer->start();
2016
2017 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2018 // the client can't verify the server's identity.
2019 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2020 client.run(handshakeOk);
2021}
2022TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002023 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2024 (void)serverVersion;
2025
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002026 auto validServer = std::make_unique<Server>();
2027 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002028
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002029 auto maliciousServer = std::make_unique<Server>();
2030 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002031
2032 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002033 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002034
2035 ASSERT_EQ(OK, trust(&client, validServer));
2036 ASSERT_EQ(OK, trust(validServer, &client));
2037 ASSERT_EQ(OK, trust(maliciousServer, &client));
2038
2039 maliciousServer->start();
2040
2041 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2042 // the client can't verify the server's identity.
2043 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2044 client.run(handshakeOk);
2045}
2046
2047TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002048 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2049 (void)serverVersion;
2050
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002051 auto server = std::make_unique<Server>();
2052 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002053
2054 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002055 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002056
2057 ASSERT_EQ(OK, trust(&client, server));
2058
2059 server->start();
2060
2061 // For TLS, Client should be able to verify server's identity, so client should see
2062 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2063 // identity and should drop the connection, so client shouldn't be able to read anything.
2064 bool readOk = rpcSecurity != RpcSecurity::TLS;
2065 client.run(true, readOk);
2066}
2067
2068TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002069 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2070 (void)serverVersion;
2071
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002072 auto server = std::make_unique<Server>();
2073 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002074
2075 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002076 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002077 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002078 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002079
2080 ASSERT_EQ(OK, trust(&validClient, server));
2081 ASSERT_EQ(OK, trust(&maliciousClient, server));
2082
2083 server->start();
2084
2085 // See UntrustedClient.
2086 bool readOk = rpcSecurity != RpcSecurity::TLS;
2087 maliciousClient.run(true, readOk);
2088}
2089
Yifan Hong67519322021-09-13 18:51:16 -07002090TEST_P(RpcTransportTest, Trigger) {
2091 std::string msg2 = ", world!";
2092 std::mutex writeMutex;
2093 std::condition_variable writeCv;
2094 bool shouldContinueWriting = false;
2095 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002096 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002097 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002098 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2099 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002100 if (status != OK) return AssertionFailure() << statusToString(status);
2101
2102 {
2103 std::unique_lock<std::mutex> lock(writeMutex);
2104 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2105 return AssertionFailure() << "write barrier not cleared in time!";
2106 }
2107 }
2108
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002109 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002110 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2111 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002112 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002113 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002114 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002115 << statusToString(status);
2116 return AssertionSuccess();
2117 };
2118
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002119 auto server = std::make_unique<Server>();
2120 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002121
2122 // Set up client
2123 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002124 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002125
2126 // Exchange keys
2127 ASSERT_EQ(OK, trust(&client, server));
2128 ASSERT_EQ(OK, trust(server, &client));
2129
2130 server->setPostConnect(serverPostConnect);
2131
Yifan Hong67519322021-09-13 18:51:16 -07002132 server->start();
2133 // connect() to server and do handshake
2134 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002135 // read the first message. This ensures that server has finished handshake and start handling
2136 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002137 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002138 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2139 // write is on an FdTrigger that has been shut down.
2140 server->shutdown();
2141 // Continues server thread to write the second message.
2142 {
Yifan Hong22211f82021-09-14 12:32:25 -07002143 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002144 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002145 }
Yifan Hong22211f82021-09-14 12:32:25 -07002146 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002147 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002148 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002149 // On the client side, second read fails with DEAD_OBJECT
2150 ASSERT_FALSE(client.readMessage(msg2));
2151}
2152
Pawan49d74cb2022-08-03 21:19:11 +00002153TEST_P(RpcTransportTest, CheckWaitingForRead) {
2154 std::mutex readMutex;
2155 std::condition_variable readCv;
2156 bool shouldContinueReading = false;
2157 // Server will write data on transport once its started
2158 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
2159 std::string message(RpcTransportTestUtils::kMessage);
2160 iovec messageIov{message.data(), message.size()};
2161 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2162 std::nullopt, nullptr);
2163 if (status != OK) return AssertionFailure() << statusToString(status);
2164
2165 {
2166 std::unique_lock<std::mutex> lock(readMutex);
2167 shouldContinueReading = true;
2168 lock.unlock();
2169 readCv.notify_all();
2170 }
2171 return AssertionSuccess();
2172 };
2173
2174 // Setup Server and client
2175 auto server = std::make_unique<Server>();
2176 ASSERT_TRUE(server->setUp(GetParam()));
2177
2178 Client client(server->getConnectToServerFn());
2179 ASSERT_TRUE(client.setUp(GetParam()));
2180
2181 ASSERT_EQ(OK, trust(&client, server));
2182 ASSERT_EQ(OK, trust(server, &client));
2183 server->setPostConnect(serverPostConnect);
2184
2185 server->start();
2186 ASSERT_TRUE(client.setUpTransport());
2187 {
2188 // Wait till server writes data
2189 std::unique_lock<std::mutex> lock(readMutex);
2190 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2191 }
2192
2193 // Since there is no read polling here, we will get polling count 0
2194 ASSERT_FALSE(client.isTransportWaiting());
2195 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2196 // Thread should increment polling count, read and decrement polling count
2197 // Again, polling count should be zero here
2198 ASSERT_FALSE(client.isTransportWaiting());
2199
2200 server->shutdown();
2201}
2202
Yifan Hong1deca4b2021-09-10 16:16:44 -07002203INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002204 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002205 RpcTransportTest::PrintParamInfo);
2206
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002207class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002208 : public testing::TestWithParam<
2209 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002210public:
2211 template <typename A, typename B>
2212 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002213 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2214 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002215 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2216 }
2217 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002218 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2219 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2220 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002221 };
2222};
2223
2224TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002225 if constexpr (!kEnableRpcThreads) {
2226 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2227 }
2228
Frederick Mayledc07cf82022-05-26 20:30:12 +00002229 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002230
2231 std::vector<uint8_t> pkeyData, certData;
2232 {
2233 auto pkey = makeKeyPairForSelfSignedCert();
2234 ASSERT_NE(nullptr, pkey);
2235 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2236 ASSERT_NE(nullptr, cert);
2237 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2238 certData = serializeCertificate(cert.get(), certificateFormat);
2239 }
2240
2241 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2242 auto desCert = deserializeCertificate(certData, certificateFormat);
2243 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002244 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2245 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002246
2247 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2248 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2249
2250 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2251 ASSERT_TRUE(client.setUp(utilsParam));
2252
2253 ASSERT_EQ(OK, trust(&client, server));
2254 ASSERT_EQ(OK, trust(server, &client));
2255
2256 server->start();
2257 client.run();
2258}
2259
2260INSTANTIATE_TEST_CASE_P(
2261 BinderRpc, RpcTransportTlsKeyTest,
2262 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2263 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002264 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2265 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002266 RpcTransportTlsKeyTest::PrintParamInfo);
2267
Steven Morelandc1635952021-04-01 16:20:47 +00002268} // namespace android
2269
2270int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002271 ::testing::InitGoogleTest(&argc, argv);
2272 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002273
Steven Moreland5553ac42020-11-11 02:14:45 +00002274 return RUN_ALL_TESTS();
2275}