blob: 8841021b40452e4d1fbb254057069e671fbd53cc [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
David Brazdil21c887c2022-09-23 12:25:18 +0100236static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
237 base::unique_fd sockClient, sockServer;
238 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
239 int savedErrno = errno;
240 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
241 }
242
243 int zero = 0;
244 iovec iov{&zero, sizeof(zero)};
245 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
246 fds.emplace_back(std::move(sockServer));
247
248 if (sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
249 int savedErrno = errno;
250 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
251 }
252 return std::move(sockClient);
253}
254
Andrei Homescu2a298012022-06-15 01:08:54 +0000255using RunServiceFn = void (*)(android::base::borrowed_fd writeEnd,
256 android::base::borrowed_fd readEnd);
257
258class BinderRpc : public ::testing::TestWithParam<
259 std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t, bool, bool>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000260public:
Frederick Mayle69a0c992022-05-26 20:38:39 +0000261 SocketType socketType() const { return std::get<0>(GetParam()); }
262 RpcSecurity rpcSecurity() const { return std::get<1>(GetParam()); }
263 uint32_t clientVersion() const { return std::get<2>(GetParam()); }
264 uint32_t serverVersion() const { return std::get<3>(GetParam()); }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000265 bool serverSingleThreaded() const { return std::get<4>(GetParam()); }
Andrei Homescu2a298012022-06-15 01:08:54 +0000266 bool noKernel() const { return std::get<5>(GetParam()); }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000267
Andrei Homescua858b0e2022-08-01 23:43:09 +0000268 bool clientOrServerSingleThreaded() const {
269 return !kEnableRpcThreads || serverSingleThreaded();
270 }
271
Frederick Mayle69a0c992022-05-26 20:38:39 +0000272 // Whether the test params support sending FDs in parcels.
273 bool supportsFdTransport() const {
274 return clientVersion() >= 1 && serverVersion() >= 1 && rpcSecurity() != RpcSecurity::TLS &&
David Brazdil21c887c2022-09-23 12:25:18 +0100275 (socketType() == SocketType::PRECONNECTED || socketType() == SocketType::UNIX ||
276 socketType() == SocketType::UNIX_BOOTSTRAP);
277 }
278
279 void SetUp() override {
280 if (socketType() == SocketType::UNIX_BOOTSTRAP && rpcSecurity() == RpcSecurity::TLS) {
281 GTEST_SKIP() << "Unix bootstrap not supported over a TLS transport";
282 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000283 }
284
Yifan Hong702115c2021-06-24 15:39:18 -0700285 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000286 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
287 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
Frederick Mayledc07cf82022-05-26 20:30:12 +0000288 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Andrei Homescu2a298012022-06-15 01:08:54 +0000289 if (singleThreaded) {
290 ret += "_single_threaded";
291 }
292 if (noKernel) {
293 ret += "_no_kernel";
294 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700295 return ret;
296 }
297
Steven Morelandc1635952021-04-01 16:20:47 +0000298 // This creates a new process serving an interface on a certain number of
299 // threads.
Andrei Homescu2a298012022-06-15 01:08:54 +0000300 ProcessSession createRpcTestSocketServerProcessEtc(const BinderRpcOptions& options) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000301 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000302
Yifan Hong702115c2021-06-24 15:39:18 -0700303 SocketType socketType = std::get<0>(GetParam());
304 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000305 uint32_t clientVersion = std::get<2>(GetParam());
306 uint32_t serverVersion = std::get<3>(GetParam());
Andrei Homescu2a298012022-06-15 01:08:54 +0000307 bool singleThreaded = std::get<4>(GetParam());
308 bool noKernel = std::get<5>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000309
Andrei Homescu2a298012022-06-15 01:08:54 +0000310 std::string path = android::base::GetExecutableDirectory();
311 auto servicePath =
312 android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
313 singleThreaded ? "_single_threaded" : "",
314 noKernel ? "_no_kernel" : "");
Steven Morelandc1635952021-04-01 16:20:47 +0000315
David Brazdil21c887c2022-09-23 12:25:18 +0100316 base::unique_fd bootstrapClientFd, bootstrapServerFd;
317 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
318 // This is because we cannot pass ParcelFileDescriptor over a pipe.
319 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &bootstrapServerFd)) {
320 int savedErrno = errno;
321 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
322 }
323
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000324 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000325 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700326 android::base::borrowed_fd readEnd) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000327 auto writeFd = std::to_string(writeEnd.get());
328 auto readFd = std::to_string(readEnd.get());
329 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
330 NULL);
Steven Morelandc1635952021-04-01 16:20:47 +0000331 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000332 };
333
Andrei Homescu2a298012022-06-15 01:08:54 +0000334 BinderRpcTestServerConfig serverConfig;
335 serverConfig.numThreads = options.numThreads;
336 serverConfig.socketType = static_cast<int32_t>(socketType);
337 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
338 serverConfig.serverVersion = serverVersion;
339 serverConfig.vsockPort = allocateVsockPort();
340 serverConfig.addr = allocateSocketAddress();
David Brazdil21c887c2022-09-23 12:25:18 +0100341 serverConfig.unixBootstrapFd = bootstrapServerFd.get();
Andrei Homescu2a298012022-06-15 01:08:54 +0000342 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
343 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
344 static_cast<int32_t>(mode));
345 }
346 writeToFd(ret.host.writeEnd(), serverConfig);
347
Yifan Hong1deca4b2021-09-10 16:16:44 -0700348 std::vector<sp<RpcSession>> sessions;
349 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
350 for (size_t i = 0; i < options.numSessions; i++) {
351 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
352 }
353
354 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
355 BinderRpcTestClientInfo clientInfo;
356 for (const auto& session : sessions) {
357 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700358 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700359 }
360 writeToFd(ret.host.writeEnd(), clientInfo);
361
362 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700363 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700364 CHECK_NE(0, serverInfo.port);
365 }
366
367 if (rpcSecurity == RpcSecurity::TLS) {
368 const auto& serverCert = serverInfo.cert.data;
369 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700370 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
371 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700372 }
373
Steven Moreland2372f9d2021-08-05 15:42:01 -0700374 status_t status;
375
Yifan Hong1deca4b2021-09-10 16:16:44 -0700376 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000377 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700378 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700379 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000380 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Moreland659416d2021-05-11 00:47:50 +0000381
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000382 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700383 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700384 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000385 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700386 });
Steven Moreland4198a122021-08-03 17:37:58 -0700387 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000388 case SocketType::UNIX:
Andrei Homescu2a298012022-06-15 01:08:54 +0000389 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000390 break;
David Brazdil21c887c2022-09-23 12:25:18 +0100391 case SocketType::UNIX_BOOTSTRAP:
392 status = session->setupUnixDomainSocketBootstrapClient(
393 base::unique_fd(dup(bootstrapClientFd.get())));
394 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000395 case SocketType::VSOCK:
Andrei Homescu2a298012022-06-15 01:08:54 +0000396 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000397 break;
398 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700399 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000400 break;
401 default:
402 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000403 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000404 if (options.allowConnectFailure && status != OK) {
405 ret.sessions.clear();
406 break;
407 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700408 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000410 }
Steven Morelandc1635952021-04-01 16:20:47 +0000411 return ret;
412 }
413
Andrei Homescu2a298012022-06-15 01:08:54 +0000414 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const BinderRpcOptions& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000415 BinderRpcTestProcessSession ret{
Andrei Homescu2a298012022-06-15 01:08:54 +0000416 .proc = createRpcTestSocketServerProcessEtc(options),
Steven Morelandc1635952021-04-01 16:20:47 +0000417 };
418
Frederick Mayle69a0c992022-05-26 20:38:39 +0000419 ret.rootBinder = ret.proc.sessions.empty() ? nullptr : ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000420 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
421
422 return ret;
423 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700424
425 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
426 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000427};
428
Steven Morelandc1635952021-04-01 16:20:47 +0000429TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000430 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000431 ASSERT_NE(proc.rootBinder, nullptr);
432 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
433}
434
Steven Moreland4cf688f2021-03-31 01:48:58 +0000435TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000436 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000437 ASSERT_NE(proc.rootBinder, nullptr);
438 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
439}
440
Andrei Homescua858b0e2022-08-01 23:43:09 +0000441TEST_P(BinderRpc, MultipleSessions) {
442 if (serverSingleThreaded()) {
443 // Tests with multiple sessions require a multi-threaded service,
444 // but work fine on a single-threaded client
445 GTEST_SKIP() << "This test requires a multi-threaded service";
446 }
447
Steven Moreland4313d7e2021-07-15 23:41:22 +0000448 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000449 for (auto session : proc.proc.sessions) {
450 ASSERT_NE(nullptr, session.root);
451 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000452 }
453}
454
Andrei Homescua858b0e2022-08-01 23:43:09 +0000455TEST_P(BinderRpc, SeparateRootObject) {
456 if (serverSingleThreaded()) {
457 GTEST_SKIP() << "This test requires a multi-threaded service";
458 }
459
Steven Moreland51c44a92021-10-14 16:50:35 -0700460 SocketType type = std::get<0>(GetParam());
David Brazdil21c887c2022-09-23 12:25:18 +0100461 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX ||
462 type == SocketType::UNIX_BOOTSTRAP) {
Steven Moreland51c44a92021-10-14 16:50:35 -0700463 // we can't get port numbers for unix sockets
464 return;
465 }
466
467 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
468
469 int port1 = 0;
470 EXPECT_OK(proc.rootIface->getClientPort(&port1));
471
472 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
473 int port2;
474 EXPECT_OK(rootIface2->getClientPort(&port2));
475
476 // we should have a different IBinderRpcTest object created for each
477 // session, because we use setPerSessionRootObject
478 EXPECT_NE(port1, port2);
479}
480
Steven Morelandc1635952021-04-01 16:20:47 +0000481TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000482 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000483 Parcel data;
484 Parcel reply;
485 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
486}
487
Steven Moreland67753c32021-04-02 18:45:19 +0000488TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700489 auto proc1 = createRpcTestSocketServerProcess({});
490 auto proc2 = createRpcTestSocketServerProcess({});
491
492 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000493
494 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700495 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000496 p1.writeInt32(3);
497
Frederick Maylea4ed5672022-06-17 22:03:38 +0000498 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700499 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
500
Steven Moreland67753c32021-04-02 18:45:19 +0000501 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700502 p2.markForBinder(proc2.rootBinder);
503 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000504
505 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
506 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
507}
508
Steven Morelandc1635952021-04-01 16:20:47 +0000509TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000510 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000511 Parcel data;
512 data.markForBinder(proc.rootBinder);
513 Parcel reply;
514 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
515}
516
Steven Morelandc1635952021-04-01 16:20:47 +0000517TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000518 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000519 EXPECT_OK(proc.rootIface->sendString("asdf"));
520}
521
Steven Morelandc1635952021-04-01 16:20:47 +0000522TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000523 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000524 std::string doubled;
525 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
526 EXPECT_EQ("cool cool ", doubled);
527}
528
Steven Morelandc1635952021-04-01 16:20:47 +0000529TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000530 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000531 std::string single = std::string(1024, 'a');
532 std::string doubled;
533 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
534 EXPECT_EQ(single + single, doubled);
535}
536
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000537TEST_P(BinderRpc, InvalidNullBinderReturn) {
538 auto proc = createRpcTestSocketServerProcess({});
539
540 sp<IBinder> outBinder;
541 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
542}
543
Steven Morelandc1635952021-04-01 16:20:47 +0000544TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000545 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000546
547 int32_t pingResult;
548 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
549 EXPECT_EQ(OK, pingResult);
550
551 EXPECT_EQ(0, MyBinderRpcSession::gNum);
552}
553
Steven Morelandc1635952021-04-01 16:20:47 +0000554TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000555 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000556
557 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
558 sp<IBinder> outBinder;
559 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
560 EXPECT_EQ(inBinder, outBinder);
561
562 wp<IBinder> weak = inBinder;
563 inBinder = nullptr;
564 outBinder = nullptr;
565
566 // Force reading a reply, to process any pending dec refs from the other
567 // process (the other process will process dec refs there before processing
568 // the ping here).
569 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
570
571 EXPECT_EQ(nullptr, weak.promote());
572
573 EXPECT_EQ(0, MyBinderRpcSession::gNum);
574}
575
Steven Morelandc1635952021-04-01 16:20:47 +0000576TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000577 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000578
579 sp<IBinderRpcSession> session;
580 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
581
582 sp<IBinder> inBinder = IInterface::asBinder(session);
583 sp<IBinder> outBinder;
584 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
585 EXPECT_EQ(inBinder, outBinder);
586
587 wp<IBinder> weak = inBinder;
588 session = nullptr;
589 inBinder = nullptr;
590 outBinder = nullptr;
591
592 // Force reading a reply, to process any pending dec refs from the other
593 // process (the other process will process dec refs there before processing
594 // the ping here).
595 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
596
597 EXPECT_EQ(nullptr, weak.promote());
598}
599
Steven Morelandc1635952021-04-01 16:20:47 +0000600TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000601 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000602
603 sp<IBinder> outBinder;
604 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
605 EXPECT_EQ(nullptr, outBinder);
606}
607
Steven Morelandc1635952021-04-01 16:20:47 +0000608TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000609 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000610
611 IBinder* ptr = nullptr;
612 {
613 sp<IBinder> binder = new BBinder();
614 ptr = binder.get();
615 EXPECT_OK(proc.rootIface->holdBinder(binder));
616 }
617
618 sp<IBinder> held;
619 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
620
621 EXPECT_EQ(held.get(), ptr);
622
623 // stop holding binder, because we test to make sure references are cleaned
624 // up
625 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
626 // and flush ref counts
627 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
628}
629
630// START TESTS FOR LIMITATIONS OF SOCKET BINDER
631// These are behavioral differences form regular binder, where certain usecases
632// aren't supported.
633
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000634TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000635 auto proc1 = createRpcTestSocketServerProcess({});
636 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000637
638 sp<IBinder> outBinder;
639 EXPECT_EQ(INVALID_OPERATION,
640 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
641}
642
Andrei Homescua858b0e2022-08-01 23:43:09 +0000643TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
644 if (serverSingleThreaded()) {
645 GTEST_SKIP() << "This test requires a multi-threaded service";
646 }
647
Steven Moreland4313d7e2021-07-15 23:41:22 +0000648 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000649
650 sp<IBinder> outBinder;
651 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000652 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000653 .transactionError());
654}
655
Steven Morelandc1635952021-04-01 16:20:47 +0000656TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000657 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000658 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
659 "at build time.";
660 }
661
Steven Moreland4313d7e2021-07-15 23:41:22 +0000662 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000663
664 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
665 sp<IBinder> outBinder;
666 EXPECT_EQ(INVALID_OPERATION,
667 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
668}
669
Steven Morelandc1635952021-04-01 16:20:47 +0000670TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000671 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000672 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
673 "at build time.";
674 }
675
Steven Moreland4313d7e2021-07-15 23:41:22 +0000676 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000677
678 // for historical reasons, IServiceManager interface only returns the
679 // exception code
680 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
681 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
682}
683
684// END TESTS FOR LIMITATIONS OF SOCKET BINDER
685
Steven Morelandc1635952021-04-01 16:20:47 +0000686TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000687 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000688
689 sp<IBinder> outBinder;
690 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
691 EXPECT_EQ(proc.rootBinder, outBinder);
692}
693
Steven Morelandc1635952021-04-01 16:20:47 +0000694TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000695 auto proc = createRpcTestSocketServerProcess({
696 // Enable FD support because it uses more stack space and so represents
697 // something closer to a worst case scenario.
698 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
699 .serverSupportedFileDescriptorTransportModes =
700 {RpcSession::FileDescriptorTransportMode::UNIX},
701 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000702
703 auto nastyNester = sp<MyBinderRpcTest>::make();
704 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
705
706 wp<IBinder> weak = nastyNester;
707 nastyNester = nullptr;
708 EXPECT_EQ(nullptr, weak.promote());
709}
710
Steven Morelandc1635952021-04-01 16:20:47 +0000711TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000712 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000713
714 sp<IBinder> a;
715 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
716
717 sp<IBinder> b;
718 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
719
720 EXPECT_EQ(a, b);
721}
722
Steven Morelandc1635952021-04-01 16:20:47 +0000723TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000724 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000725
726 sp<IBinder> a;
727 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
728 wp<IBinder> weak = a;
729 a = nullptr;
730
731 sp<IBinder> b;
732 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
733
734 // this is the wrong behavior, since BpBinder
735 // doesn't implement onIncStrongAttempted
736 // but make sure there is no crash
737 EXPECT_EQ(nullptr, weak.promote());
738
739 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
740
741 // In order to fix this:
742 // - need to have incStrongAttempted reflected across IPC boundary (wait for
743 // response to promote - round trip...)
744 // - sendOnLastWeakRef, to delete entries out of RpcState table
745 EXPECT_EQ(b, weak.promote());
746}
747
748#define expectSessions(expected, iface) \
749 do { \
750 int session; \
751 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
752 EXPECT_EQ(expected, session); \
753 } while (false)
754
Steven Morelandc1635952021-04-01 16:20:47 +0000755TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000756 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000757
758 sp<IBinderRpcSession> session;
759 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
760 std::string out;
761 EXPECT_OK(session->getName(&out));
762 EXPECT_EQ("aoeu", out);
763
764 expectSessions(1, proc.rootIface);
765 session = nullptr;
766 expectSessions(0, proc.rootIface);
767}
768
Steven Morelandc1635952021-04-01 16:20:47 +0000769TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000770 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000771
772 std::vector<sp<IBinderRpcSession>> sessions;
773
774 for (size_t i = 0; i < 15; i++) {
775 expectSessions(i, proc.rootIface);
776 sp<IBinderRpcSession> session;
777 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
778 sessions.push_back(session);
779 }
780 expectSessions(sessions.size(), proc.rootIface);
781 for (size_t i = 0; i < sessions.size(); i++) {
782 std::string out;
783 EXPECT_OK(sessions.at(i)->getName(&out));
784 EXPECT_EQ(std::to_string(i), out);
785 }
786 expectSessions(sessions.size(), proc.rootIface);
787
788 while (!sessions.empty()) {
789 sessions.pop_back();
790 expectSessions(sessions.size(), proc.rootIface);
791 }
792 expectSessions(0, proc.rootIface);
793}
794
795size_t epochMillis() {
796 using std::chrono::duration_cast;
797 using std::chrono::milliseconds;
798 using std::chrono::seconds;
799 using std::chrono::system_clock;
800 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
801}
802
Andrei Homescua858b0e2022-08-01 23:43:09 +0000803TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
804 if (clientOrServerSingleThreaded()) {
805 GTEST_SKIP() << "This test requires multiple threads";
806 }
807
Steven Moreland5553ac42020-11-11 02:14:45 +0000808 constexpr size_t kNumThreads = 10;
809
Steven Moreland4313d7e2021-07-15 23:41:22 +0000810 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000811
812 EXPECT_OK(proc.rootIface->lock());
813
814 // block all but one thread taking locks
815 std::vector<std::thread> ts;
816 for (size_t i = 0; i < kNumThreads - 1; i++) {
817 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
818 }
819
820 usleep(100000); // give chance for calls on other threads
821
822 // other calls still work
823 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
824
825 constexpr size_t blockTimeMs = 500;
826 size_t epochMsBefore = epochMillis();
827 // after this, we should never see a response within this time
828 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
829
830 // this call should be blocked for blockTimeMs
831 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
832
833 size_t epochMsAfter = epochMillis();
834 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
835
836 for (auto& t : ts) t.join();
837}
838
Yifan Hong1f44f982021-10-08 17:16:47 -0700839void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
840 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000841 size_t epochMsBefore = epochMillis();
842
843 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700844 for (size_t i = 0; i < numCalls; i++) {
845 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000846 }
847
848 for (auto& t : ts) t.join();
849
850 size_t epochMsAfter = epochMillis();
851
Yifan Hong1f44f982021-10-08 17:16:47 -0700852 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000853
854 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700855 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
856}
857
Andrei Homescua858b0e2022-08-01 23:43:09 +0000858TEST_P(BinderRpc, ThreadPoolOverSaturated) {
859 if (clientOrServerSingleThreaded()) {
860 GTEST_SKIP() << "This test requires multiple threads";
861 }
862
Yifan Hong1f44f982021-10-08 17:16:47 -0700863 constexpr size_t kNumThreads = 10;
864 constexpr size_t kNumCalls = kNumThreads + 3;
865 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
866 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
867}
868
Andrei Homescua858b0e2022-08-01 23:43:09 +0000869TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
870 if (clientOrServerSingleThreaded()) {
871 GTEST_SKIP() << "This test requires multiple threads";
872 }
873
Yifan Hong1f44f982021-10-08 17:16:47 -0700874 constexpr size_t kNumThreads = 20;
875 constexpr size_t kNumOutgoingConnections = 10;
876 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
877 auto proc = createRpcTestSocketServerProcess(
878 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
879 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000880}
881
Andrei Homescua858b0e2022-08-01 23:43:09 +0000882TEST_P(BinderRpc, ThreadingStressTest) {
883 if (clientOrServerSingleThreaded()) {
884 GTEST_SKIP() << "This test requires multiple threads";
885 }
886
Steven Moreland5553ac42020-11-11 02:14:45 +0000887 constexpr size_t kNumClientThreads = 10;
888 constexpr size_t kNumServerThreads = 10;
889 constexpr size_t kNumCalls = 100;
890
Steven Moreland4313d7e2021-07-15 23:41:22 +0000891 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000892
893 std::vector<std::thread> threads;
894 for (size_t i = 0; i < kNumClientThreads; i++) {
895 threads.push_back(std::thread([&] {
896 for (size_t j = 0; j < kNumCalls; j++) {
897 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000898 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000899 EXPECT_EQ(proc.rootBinder, out);
900 }
901 }));
902 }
903
904 for (auto& t : threads) t.join();
905}
906
Steven Moreland925ba0a2021-09-17 18:06:32 -0700907static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
908 std::vector<std::thread> threads;
909 for (size_t i = 0; i < threadCount; i++) {
910 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
911 }
912 for (auto& t : threads) t.join();
913}
914
Andrei Homescua858b0e2022-08-01 23:43:09 +0000915TEST_P(BinderRpc, OnewayStressTest) {
916 if (clientOrServerSingleThreaded()) {
917 GTEST_SKIP() << "This test requires multiple threads";
918 }
919
Steven Morelandc6046982021-04-20 00:49:42 +0000920 constexpr size_t kNumClientThreads = 10;
921 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700922 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000923
Steven Moreland4313d7e2021-07-15 23:41:22 +0000924 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000925
926 std::vector<std::thread> threads;
927 for (size_t i = 0; i < kNumClientThreads; i++) {
928 threads.push_back(std::thread([&] {
929 for (size_t j = 0; j < kNumCalls; j++) {
930 EXPECT_OK(proc.rootIface->sendString("a"));
931 }
Steven Morelandc6046982021-04-20 00:49:42 +0000932 }));
933 }
934
935 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700936
937 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000938}
939
Steven Morelandc1635952021-04-01 16:20:47 +0000940TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000941 constexpr size_t kReallyLongTimeMs = 100;
942 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
943
Steven Moreland4313d7e2021-07-15 23:41:22 +0000944 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000945
946 size_t epochMsBefore = epochMillis();
947
948 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
949
950 size_t epochMsAfter = epochMillis();
951 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
952}
953
Andrei Homescua858b0e2022-08-01 23:43:09 +0000954TEST_P(BinderRpc, OnewayCallQueueing) {
955 if (clientOrServerSingleThreaded()) {
956 GTEST_SKIP() << "This test requires multiple threads";
957 }
958
Steven Moreland5553ac42020-11-11 02:14:45 +0000959 constexpr size_t kNumSleeps = 10;
960 constexpr size_t kNumExtraServerThreads = 4;
961 constexpr size_t kSleepMs = 50;
962
963 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000964 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000965
966 EXPECT_OK(proc.rootIface->lock());
967
Steven Moreland1c678802021-09-17 16:48:47 -0700968 size_t epochMsBefore = epochMillis();
969
970 // all these *Async commands should be queued on the server sequentially,
971 // even though there are multiple threads.
972 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000973 proc.rootIface->sleepMsAsync(kSleepMs);
974 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000975 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
976
Steven Moreland1c678802021-09-17 16:48:47 -0700977 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000978 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700979
Steven Moreland5553ac42020-11-11 02:14:45 +0000980 size_t epochMsAfter = epochMillis();
981
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000982 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000983
Steven Moreland925ba0a2021-09-17 18:06:32 -0700984 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000985}
986
Andrei Homescua858b0e2022-08-01 23:43:09 +0000987TEST_P(BinderRpc, OnewayCallExhaustion) {
988 if (clientOrServerSingleThreaded()) {
989 GTEST_SKIP() << "This test requires multiple threads";
990 }
991
Steven Morelandd45be622021-06-04 02:19:37 +0000992 constexpr size_t kNumClients = 2;
993 constexpr size_t kTooLongMs = 1000;
994
Steven Moreland4313d7e2021-07-15 23:41:22 +0000995 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000996
997 // Build up oneway calls on the second session to make sure it terminates
998 // and shuts down. The first session should be unaffected (proc destructor
999 // checks the first session).
1000 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1001
1002 std::vector<std::thread> threads;
1003 for (size_t i = 0; i < kNumClients; i++) {
1004 // one of these threads will get stuck queueing a transaction once the
1005 // socket fills up, the other will be able to fill up transactions on
1006 // this object
1007 threads.push_back(std::thread([&] {
1008 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1009 }
1010 }));
1011 }
1012 for (auto& t : threads) t.join();
1013
1014 Status status = iface->sleepMsAsync(kTooLongMs);
1015 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1016
Steven Moreland798e0d12021-07-14 23:19:25 +00001017 // now that it has died, wait for the remote session to shutdown
1018 std::vector<int32_t> remoteCounts;
1019 do {
1020 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1021 } while (remoteCounts.size() == kNumClients);
1022
Steven Morelandd45be622021-06-04 02:19:37 +00001023 // the second session should be shutdown in the other process by the time we
1024 // are able to join above (it'll only be hung up once it finishes processing
1025 // any pending commands). We need to erase this session from the record
1026 // here, so that the destructor for our session won't check that this
1027 // session is valid, but we still want it to test the other session.
1028 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1029}
1030
Steven Moreland659416d2021-05-11 00:47:50 +00001031TEST_P(BinderRpc, Callbacks) {
1032 const static std::string kTestString = "good afternoon!";
1033
Steven Morelandc7d40132021-06-10 03:42:11 +00001034 for (bool callIsOneway : {true, false}) {
1035 for (bool callbackIsOneway : {true, false}) {
1036 for (bool delayed : {true, false}) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001037 if (clientOrServerSingleThreaded() &&
1038 (callIsOneway || callbackIsOneway || delayed)) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001039 // we have no incoming connections to receive the callback
1040 continue;
1041 }
1042
Andrei Homescua858b0e2022-08-01 23:43:09 +00001043 size_t numIncomingConnections = clientOrServerSingleThreaded() ? 0 : 1;
Steven Moreland4313d7e2021-07-15 23:41:22 +00001044 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +00001045 {.numThreads = 1,
1046 .numSessions = 1,
Andrei Homescu2a298012022-06-15 01:08:54 +00001047 .numIncomingConnections = numIncomingConnections});
Steven Morelandc7d40132021-06-10 03:42:11 +00001048 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001049
Steven Morelandc7d40132021-06-10 03:42:11 +00001050 if (callIsOneway) {
1051 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1052 kTestString));
1053 } else {
1054 EXPECT_OK(
1055 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1056 }
Steven Moreland659416d2021-05-11 00:47:50 +00001057
Steven Moreland03ecce62022-05-13 23:22:05 +00001058 // if both transactions are synchronous and the response is sent back on the
1059 // same thread, everything should have happened in a nested call. Otherwise,
1060 // the callback will be processed on another thread.
1061 if (callIsOneway || callbackIsOneway || delayed) {
1062 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001063 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001064 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1065 }
Steven Moreland659416d2021-05-11 00:47:50 +00001066
Steven Morelandc7d40132021-06-10 03:42:11 +00001067 EXPECT_EQ(cb->mValues.size(), 1)
1068 << "callIsOneway: " << callIsOneway
1069 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1070 if (cb->mValues.empty()) continue;
1071 EXPECT_EQ(cb->mValues.at(0), kTestString)
1072 << "callIsOneway: " << callIsOneway
1073 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001074
Steven Morelandc7d40132021-06-10 03:42:11 +00001075 // since we are severing the connection, we need to go ahead and
1076 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001077 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1078 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1079 }
Steven Moreland659416d2021-05-11 00:47:50 +00001080
Steven Moreland1b304292021-07-15 22:59:34 +00001081 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001082 // need to manually shut it down
1083 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Morelandc7d40132021-06-10 03:42:11 +00001084 proc.expectAlreadyShutdown = true;
1085 }
Steven Moreland659416d2021-05-11 00:47:50 +00001086 }
1087 }
1088}
1089
Devin Moore66d5b7a2022-07-07 21:42:10 +00001090TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001091 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001092 GTEST_SKIP() << "This test requires multiple threads";
1093 }
1094 class MyDeathRec : public IBinder::DeathRecipient {
1095 public:
1096 void binderDied(const wp<IBinder>& /* who */) override {
1097 dead = true;
1098 mCv.notify_one();
1099 }
1100 std::mutex mMtx;
1101 std::condition_variable mCv;
1102 bool dead = false;
1103 };
1104
1105 // Death recipient needs to have an incoming connection to be called
1106 auto proc = createRpcTestSocketServerProcess(
1107 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1108
1109 auto dr = sp<MyDeathRec>::make();
1110 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1111
1112 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1113 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1114 }
1115
1116 std::unique_lock<std::mutex> lock(dr->mMtx);
Devin Moore47a12012022-08-19 21:16:17 +00001117 ASSERT_TRUE(dr->mCv.wait_for(lock, 1000ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001118
1119 // need to wait for the session to shutdown so we don't "Leak session"
1120 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1121 proc.expectAlreadyShutdown = true;
1122}
1123
1124TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001125 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001126 GTEST_SKIP() << "This test requires multiple threads";
1127 }
1128 class MyDeathRec : public IBinder::DeathRecipient {
1129 public:
1130 void binderDied(const wp<IBinder>& /* who */) override {
1131 dead = true;
1132 mCv.notify_one();
1133 }
1134 std::mutex mMtx;
1135 std::condition_variable mCv;
1136 bool dead = false;
1137 };
1138
1139 // Death recipient needs to have an incoming connection to be called
1140 auto proc = createRpcTestSocketServerProcess(
1141 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1142
1143 auto dr = sp<MyDeathRec>::make();
1144 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1145
1146 // Explicitly calling shutDownAndWait will cause the death recipients
1147 // to be called.
1148 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1149
1150 std::unique_lock<std::mutex> lock(dr->mMtx);
1151 if (!dr->dead) {
1152 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1153 }
1154 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1155
1156 proc.proc.host.terminate();
1157 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1158 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1159 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1160 });
1161 proc.expectAlreadyShutdown = true;
1162}
1163
1164TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1165 class MyDeathRec : public IBinder::DeathRecipient {
1166 public:
1167 void binderDied(const wp<IBinder>& /* who */) override {}
1168 };
1169
1170 auto proc = createRpcTestSocketServerProcess(
1171 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1172
1173 auto dr = sp<MyDeathRec>::make();
1174 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1175 "Cannot register a DeathRecipient without any incoming connections.");
1176}
1177
1178TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001179 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001180 GTEST_SKIP() << "This test requires multiple threads";
1181 }
1182 class MyDeathRec : public IBinder::DeathRecipient {
1183 public:
1184 void binderDied(const wp<IBinder>& /* who */) override {
1185 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1186 }
1187 };
1188
1189 // Death recipient needs to have an incoming connection to be called
1190 auto proc = createRpcTestSocketServerProcess(
1191 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1192
1193 auto dr = sp<MyDeathRec>::make();
1194 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1195 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1196
1197 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1198 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1199 }
1200
1201 // need to wait for the session to shutdown so we don't "Leak session"
1202 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1203 proc.expectAlreadyShutdown = true;
1204}
1205
Steven Moreland195edb82021-06-08 02:44:39 +00001206TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001207 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001208 auto cb = sp<MyBinderRpcCallback>::make();
1209
1210 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1211 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1212}
1213
Steven Morelandc1635952021-04-01 16:20:47 +00001214TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001215 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001216 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001217
1218 // make sure there is some state during crash
1219 // 1. we hold their binder
1220 sp<IBinderRpcSession> session;
1221 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1222 // 2. they hold our binder
1223 sp<IBinder> binder = new BBinder();
1224 EXPECT_OK(proc.rootIface->holdBinder(binder));
1225
1226 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1227 << "Do death cleanup: " << doDeathCleanup;
1228
Frederick Maylea12b0962022-06-25 01:13:22 +00001229 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1230 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1231 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1232 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001233 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001234 }
1235}
1236
Steven Morelandd7302072021-05-15 01:32:04 +00001237TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001238 // This test only works if the current process shared the internal state of
1239 // ProcessState with the service across the call to fork(). Both the static
1240 // libraries and libbinder.so have their own separate copies of all the
1241 // globals, so the test only works when the test client and service both use
1242 // libbinder.so (when using static libraries, even a client and service
1243 // using the same kind of static library should have separate copies of the
1244 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +00001245 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001246 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1247 "at build time.";
1248 }
1249
Steven Moreland4313d7e2021-07-15 23:41:22 +00001250 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001251
Andrei Homescu2a298012022-06-15 01:08:54 +00001252 // we can't allocate IPCThreadState so actually the first time should
1253 // succeed :(
1254 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001255
1256 // second time! we catch the error :)
1257 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1258
Frederick Maylea12b0962022-06-25 01:13:22 +00001259 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1260 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1261 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1262 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001263 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001264}
1265
Frederick Mayle69a0c992022-05-26 20:38:39 +00001266TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1267 auto proc = createRpcTestSocketServerProcess({
1268 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1269 .serverSupportedFileDescriptorTransportModes =
1270 {RpcSession::FileDescriptorTransportMode::UNIX},
1271 .allowConnectFailure = true,
1272 });
1273 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1274 proc.proc.host.terminate();
1275 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1276 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1277 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1278 });
1279 proc.expectAlreadyShutdown = true;
1280}
1281
1282TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1283 auto proc = createRpcTestSocketServerProcess({
1284 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1285 .serverSupportedFileDescriptorTransportModes =
1286 {RpcSession::FileDescriptorTransportMode::NONE},
1287 .allowConnectFailure = true,
1288 });
1289 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1290 proc.proc.host.terminate();
1291 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1292 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1293 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1294 });
1295 proc.expectAlreadyShutdown = true;
1296}
1297
1298TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1299 auto proc = createRpcTestSocketServerProcess({
1300 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1301 .serverSupportedFileDescriptorTransportModes =
1302 {RpcSession::FileDescriptorTransportMode::NONE,
1303 RpcSession::FileDescriptorTransportMode::UNIX},
1304 });
1305
1306 android::os::ParcelFileDescriptor out;
1307 auto status = proc.rootIface->echoAsFile("hello", &out);
1308 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1309}
1310
1311TEST_P(BinderRpc, ReceiveFile) {
1312 auto proc = createRpcTestSocketServerProcess({
1313 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1314 .serverSupportedFileDescriptorTransportModes =
1315 {RpcSession::FileDescriptorTransportMode::UNIX},
1316 });
1317
1318 android::os::ParcelFileDescriptor out;
1319 auto status = proc.rootIface->echoAsFile("hello", &out);
1320 if (!supportsFdTransport()) {
1321 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1322 return;
1323 }
1324 ASSERT_TRUE(status.isOk()) << status;
1325
1326 std::string result;
1327 CHECK(android::base::ReadFdToString(out.get(), &result));
1328 EXPECT_EQ(result, "hello");
1329}
1330
1331TEST_P(BinderRpc, SendFiles) {
1332 auto proc = createRpcTestSocketServerProcess({
1333 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1334 .serverSupportedFileDescriptorTransportModes =
1335 {RpcSession::FileDescriptorTransportMode::UNIX},
1336 });
1337
1338 std::vector<android::os::ParcelFileDescriptor> files;
1339 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1340 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1341 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1342 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1343
1344 android::os::ParcelFileDescriptor out;
1345 auto status = proc.rootIface->concatFiles(files, &out);
1346 if (!supportsFdTransport()) {
1347 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1348 return;
1349 }
1350 ASSERT_TRUE(status.isOk()) << status;
1351
1352 std::string result;
1353 CHECK(android::base::ReadFdToString(out.get(), &result));
1354 EXPECT_EQ(result, "123abcd");
1355}
1356
1357TEST_P(BinderRpc, SendMaxFiles) {
1358 if (!supportsFdTransport()) {
1359 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1360 }
1361
1362 auto proc = createRpcTestSocketServerProcess({
1363 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1364 .serverSupportedFileDescriptorTransportModes =
1365 {RpcSession::FileDescriptorTransportMode::UNIX},
1366 });
1367
1368 std::vector<android::os::ParcelFileDescriptor> files;
1369 for (int i = 0; i < 253; i++) {
1370 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1371 }
1372
1373 android::os::ParcelFileDescriptor out;
1374 auto status = proc.rootIface->concatFiles(files, &out);
1375 ASSERT_TRUE(status.isOk()) << status;
1376
1377 std::string result;
1378 CHECK(android::base::ReadFdToString(out.get(), &result));
1379 EXPECT_EQ(result, std::string(253, 'a'));
1380}
1381
1382TEST_P(BinderRpc, SendTooManyFiles) {
1383 if (!supportsFdTransport()) {
1384 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1385 }
1386
1387 auto proc = createRpcTestSocketServerProcess({
1388 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1389 .serverSupportedFileDescriptorTransportModes =
1390 {RpcSession::FileDescriptorTransportMode::UNIX},
1391 });
1392
1393 std::vector<android::os::ParcelFileDescriptor> files;
1394 for (int i = 0; i < 254; i++) {
1395 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1396 }
1397
1398 android::os::ParcelFileDescriptor out;
1399 auto status = proc.rootIface->concatFiles(files, &out);
1400 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1401}
1402
Steven Moreland37aff182021-03-26 02:04:16 +00001403TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001404 if constexpr (!kEnableSharedLibs) {
1405 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1406 }
1407
Steven Moreland4313d7e2021-07-15 23:41:22 +00001408 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001409
1410 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1411 ASSERT_NE(binder, nullptr);
1412
1413 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1414}
1415
1416TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001417 if constexpr (!kEnableSharedLibs) {
1418 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1419 }
1420
Steven Moreland4313d7e2021-07-15 23:41:22 +00001421 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001422
1423 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1424 ASSERT_NE(binder, nullptr);
1425
1426 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1427 ASSERT_NE(ndkBinder, nullptr);
1428
1429 std::string out;
1430 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1431 ASSERT_TRUE(status.isOk()) << status.getDescription();
1432 ASSERT_EQ("aoeuaoeu", out);
1433}
1434
Steven Moreland5553ac42020-11-11 02:14:45 +00001435ssize_t countFds() {
1436 DIR* dir = opendir("/proc/self/fd/");
1437 if (dir == nullptr) return -1;
1438 ssize_t ret = 0;
1439 dirent* ent;
1440 while ((ent = readdir(dir)) != nullptr) ret++;
1441 closedir(dir);
1442 return ret;
1443}
1444
Andrei Homescua858b0e2022-08-01 23:43:09 +00001445TEST_P(BinderRpc, Fds) {
1446 if (serverSingleThreaded()) {
1447 GTEST_SKIP() << "This test requires multiple threads";
1448 }
1449
Steven Moreland5553ac42020-11-11 02:14:45 +00001450 ssize_t beforeFds = countFds();
1451 ASSERT_GE(beforeFds, 0);
1452 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001453 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001454 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1455 }
1456 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1457}
1458
Devin Moore800b2252021-10-15 16:22:57 +00001459TEST_P(BinderRpc, AidlDelegatorTest) {
1460 auto proc = createRpcTestSocketServerProcess({});
1461 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1462 ASSERT_NE(nullptr, myDelegator);
1463
1464 std::string doubled;
1465 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1466 EXPECT_EQ("cool cool ", doubled);
1467}
1468
Steven Morelandda573042021-06-12 01:13:45 +00001469static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001470 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001471 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001472
Andrei Homescu992a4052022-06-28 21:26:18 +00001473 android::base::unique_fd serverFd(
1474 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1475 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1476
1477 sockaddr_vm serverAddr{
1478 .svm_family = AF_VSOCK,
1479 .svm_port = vsockPort,
1480 .svm_cid = VMADDR_CID_ANY,
1481 };
1482 int ret = TEMP_FAILURE_RETRY(
1483 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1484 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1485 strerror(errno));
1486
1487 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1488 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1489 strerror(errno));
1490
1491 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1492 // to see if the kernel supports it. It's safe to use a blocking
1493 // connect because vsock sockets have a 2 second connection timeout,
1494 // and they return ETIMEDOUT after that.
1495 android::base::unique_fd connectFd(
1496 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1497 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1498 strerror(errno));
1499
1500 bool success = false;
1501 sockaddr_vm connectAddr{
1502 .svm_family = AF_VSOCK,
1503 .svm_port = vsockPort,
1504 .svm_cid = VMADDR_CID_LOCAL,
1505 };
1506 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1507 sizeof(connectAddr)));
1508 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1509 android::base::unique_fd acceptFd;
1510 while (true) {
1511 pollfd pfd[]{
1512 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1513 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1514 };
1515 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1516 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1517
1518 if (pfd[0].revents & POLLIN) {
1519 sockaddr_vm acceptAddr;
1520 socklen_t acceptAddrLen = sizeof(acceptAddr);
1521 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1522 reinterpret_cast<sockaddr*>(&acceptAddr),
1523 &acceptAddrLen, SOCK_CLOEXEC));
1524 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1525 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1526 "Truncated address");
1527
1528 // Store the fd in acceptFd so we keep the connection alive
1529 // while polling connectFd
1530 acceptFd.reset(ret);
1531 }
1532
1533 if (pfd[1].revents & POLLOUT) {
1534 // Connect either succeeded or timed out
1535 int connectErrno;
1536 socklen_t connectErrnoLen = sizeof(connectErrno);
1537 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1538 &connectErrnoLen);
1539 LOG_ALWAYS_FATAL_IF(ret == -1,
1540 "Could not getsockopt() after connect() "
1541 "on non-blocking socket: %s.",
1542 strerror(errno));
1543
1544 // We're done, this is all we wanted
1545 success = connectErrno == 0;
1546 break;
1547 }
1548 }
1549 } else {
1550 success = ret == 0;
1551 }
1552
1553 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1554
1555 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001556}
1557
Yifan Hong1deca4b2021-09-10 16:16:44 -07001558static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
David Brazdil21c887c2022-09-23 12:25:18 +01001559 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001560
1561 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001562
1563 static bool hasVsockLoopback = testSupportVsockLoopback();
1564
1565 if (hasVsockLoopback) {
1566 ret.push_back(SocketType::VSOCK);
1567 }
1568
1569 return ret;
1570}
1571
Frederick Mayledc07cf82022-05-26 20:30:12 +00001572static std::vector<uint32_t> testVersions() {
1573 std::vector<uint32_t> versions;
1574 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1575 versions.push_back(i);
1576 }
1577 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1578 return versions;
1579}
1580
Yifan Hong702115c2021-06-24 15:39:18 -07001581INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1582 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001583 ::testing::ValuesIn(RpcSecurityValues()),
1584 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001585 ::testing::ValuesIn(testVersions()),
1586 ::testing::Values(false, true),
1587 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001588 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001589
Yifan Hong702115c2021-06-24 15:39:18 -07001590class BinderRpcServerRootObject
1591 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001592
1593TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1594 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1595 auto setRootObject = [](bool isStrong) -> SetFn {
1596 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1597 };
1598
Yifan Hong702115c2021-06-24 15:39:18 -07001599 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1600 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001601 auto binder1 = sp<BBinder>::make();
1602 IBinder* binderRaw1 = binder1.get();
1603 setRootObject(isStrong1)(server.get(), binder1);
1604 EXPECT_EQ(binderRaw1, server->getRootObject());
1605 binder1.clear();
1606 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1607
1608 auto binder2 = sp<BBinder>::make();
1609 IBinder* binderRaw2 = binder2.get();
1610 setRootObject(isStrong2)(server.get(), binder2);
1611 EXPECT_EQ(binderRaw2, server->getRootObject());
1612 binder2.clear();
1613 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1614}
1615
1616INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001617 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1618 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001619
Yifan Hong1a235852021-05-13 16:07:47 -07001620class OneOffSignal {
1621public:
1622 // If notify() was previously called, or is called within |duration|, return true; else false.
1623 template <typename R, typename P>
1624 bool wait(std::chrono::duration<R, P> duration) {
1625 std::unique_lock<std::mutex> lock(mMutex);
1626 return mCv.wait_for(lock, duration, [this] { return mValue; });
1627 }
1628 void notify() {
1629 std::unique_lock<std::mutex> lock(mMutex);
1630 mValue = true;
1631 lock.unlock();
1632 mCv.notify_all();
1633 }
1634
1635private:
1636 std::mutex mMutex;
1637 std::condition_variable mCv;
1638 bool mValue = false;
1639};
1640
Yifan Hong194acf22021-06-29 18:44:56 -07001641TEST(BinderRpc, Java) {
1642#if !defined(__ANDROID__)
1643 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1644 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1645 "to binderHostDeviceTest. Hence, just disable this test on host.";
1646#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001647 if constexpr (!kEnableKernelIpc) {
1648 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1649 "at build time.";
1650 }
1651
Yifan Hong194acf22021-06-29 18:44:56 -07001652 sp<IServiceManager> sm = defaultServiceManager();
1653 ASSERT_NE(nullptr, sm);
1654 // Any Java service with non-empty getInterfaceDescriptor() would do.
1655 // Let's pick batteryproperties.
1656 auto binder = sm->checkService(String16("batteryproperties"));
1657 ASSERT_NE(nullptr, binder);
1658 auto descriptor = binder->getInterfaceDescriptor();
1659 ASSERT_GE(descriptor.size(), 0);
1660 ASSERT_EQ(OK, binder->pingBinder());
1661
1662 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001663 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001664 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001665 auto socket = rpcServer->releaseServer();
1666
1667 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001668 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1669
Yifan Honge3caaf22022-01-12 14:46:56 -08001670 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1671 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001672 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001673 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1674 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001675 << statusToString(setRpcClientDebugStatus);
1676 GTEST_SKIP();
1677 }
1678
1679 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001680
1681 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001682 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001683 auto rpcBinder = rpcSession->getRootObject();
1684 ASSERT_NE(nullptr, rpcBinder);
1685
1686 ASSERT_EQ(OK, rpcBinder->pingBinder());
1687
1688 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1689 << "getInterfaceDescriptor should not crash system_server";
1690 ASSERT_EQ(OK, rpcBinder->pingBinder());
1691}
1692
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001693class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1694public:
1695 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1696 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1697 std::to_string(std::get<1>(info.param));
1698 }
1699};
1700
1701TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1702 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1703 int sinkFd = sink.get();
1704 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1705 server->setProtocolVersion(std::get<1>(GetParam()));
1706 ASSERT_FALSE(server->hasServer());
1707 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1708 ASSERT_TRUE(server->hasServer());
1709 base::unique_fd retrieved = server->releaseServer();
1710 ASSERT_FALSE(server->hasServer());
1711 ASSERT_EQ(sinkFd, retrieved.get());
1712}
1713
1714TEST_P(BinderRpcServerOnly, Shutdown) {
1715 if constexpr (!kEnableRpcThreads) {
1716 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1717 }
1718
1719 auto addr = allocateSocketAddress();
1720 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1721 server->setProtocolVersion(std::get<1>(GetParam()));
1722 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1723 auto joinEnds = std::make_shared<OneOffSignal>();
1724
1725 // If things are broken and the thread never stops, don't block other tests. Because the thread
1726 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1727 // shared pointers are passed.
1728 std::thread([server, joinEnds] {
1729 server->join();
1730 joinEnds->notify();
1731 }).detach();
1732
1733 bool shutdown = false;
1734 for (int i = 0; i < 10 && !shutdown; i++) {
1735 usleep(300 * 1000); // 300ms; total 3s
1736 if (server->shutdown()) shutdown = true;
1737 }
1738 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1739
1740 ASSERT_TRUE(joinEnds->wait(2s))
1741 << "After server->shutdown() returns true, join() did not stop after 2s";
1742}
1743
Frederick Mayledc07cf82022-05-26 20:30:12 +00001744INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1745 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1746 ::testing::ValuesIn(testVersions())),
1747 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001748
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001749class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001750public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001751 // Only parameterized only server version because `RpcSession` is bypassed
1752 // in the client half of the tests.
1753 using Param =
1754 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001755 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001756
1757 // A server that handles client socket connections.
1758 class Server {
1759 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001760 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1761
Yifan Hong1deca4b2021-09-10 16:16:44 -07001762 explicit Server() {}
1763 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001764 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001765 [[nodiscard]] AssertionResult setUp(
1766 const Param& param,
1767 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001768 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001769 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001770 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001771 switch (socketType) {
1772 case SocketType::PRECONNECTED: {
1773 return AssertionFailure() << "Not supported by this test";
1774 } break;
1775 case SocketType::UNIX: {
1776 auto addr = allocateSocketAddress();
1777 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1778 if (status != OK) {
1779 return AssertionFailure()
1780 << "setupUnixDomainServer: " << statusToString(status);
1781 }
1782 mConnectToServer = [addr] {
1783 return connectTo(UnixSocketAddress(addr.c_str()));
1784 };
1785 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001786 case SocketType::UNIX_BOOTSTRAP: {
1787 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1788 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1789 return AssertionFailure() << "Socketpair() failed";
1790 }
1791 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1792 std::move(bootstrapFdServer));
1793 if (status != OK) {
1794 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1795 << statusToString(status);
1796 }
1797 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1798 mAcceptConnection = &Server::recvmsgServerConnection;
1799 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1800 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001801 case SocketType::VSOCK: {
1802 auto port = allocateVsockPort();
1803 auto status = rpcServer->setupVsockServer(port);
1804 if (status != OK) {
1805 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1806 }
1807 mConnectToServer = [port] {
1808 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1809 };
1810 } break;
1811 case SocketType::INET: {
1812 unsigned int port;
1813 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1814 if (status != OK) {
1815 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1816 }
1817 mConnectToServer = [port] {
1818 const char* addr = kLocalInetAddress;
1819 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1820 if (aiStart == nullptr) return base::unique_fd{};
1821 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1822 auto fd = connectTo(
1823 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1824 if (fd.ok()) return fd;
1825 }
1826 ALOGE("None of the socket address resolved for %s:%u can be connected",
1827 addr, port);
1828 return base::unique_fd{};
1829 };
1830 }
1831 }
1832 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001833 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001834 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001835 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1836 mSetup = true;
1837 return AssertionSuccess();
1838 }
1839 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1840 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1841 return mCertVerifier;
1842 }
1843 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1844 void start() {
1845 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1846 mThread = std::make_unique<std::thread>(&Server::run, this);
1847 }
David Brazdil21c887c2022-09-23 12:25:18 +01001848
1849 base::unique_fd acceptServerConnection() {
1850 return base::unique_fd(TEMP_FAILURE_RETRY(
1851 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1852 }
1853
1854 base::unique_fd recvmsgServerConnection() {
1855 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1856 int buf;
1857 iovec iov{&buf, sizeof(buf)};
1858
1859 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1860 int savedErrno = errno;
1861 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1862 }
1863 if (fds.size() != 1) {
1864 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1865 }
1866 return std::move(std::get<base::unique_fd>(fds[0]));
1867 }
1868
Yifan Hong1deca4b2021-09-10 16:16:44 -07001869 void run() {
1870 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1871
1872 std::vector<std::thread> threads;
1873 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001874 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001875 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1876 }
1877
1878 for (auto& thread : threads) thread.join();
1879 }
1880 void handleOne(android::base::unique_fd acceptedFd) {
1881 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001882 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001883 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001884 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001885 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001886 }
Yifan Honge07d2732021-09-13 21:59:14 -07001887 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001888 shutdown();
1889 join();
1890 }
1891 void shutdown() { mFdTrigger->trigger(); }
1892
1893 void setPostConnect(
1894 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1895 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001896 }
1897
1898 private:
1899 std::unique_ptr<std::thread> mThread;
1900 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001901 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001902 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001903 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001904 std::unique_ptr<RpcTransportCtx> mCtx;
1905 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1906 std::make_shared<RpcCertificateVerifierSimple>();
1907 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001908 // The function invoked after connection and handshake. By default, it is
1909 // |defaultPostConnect| that sends |kMessage| to the client.
1910 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1911 Server::defaultPostConnect;
1912
1913 void join() {
1914 if (mThread != nullptr) {
1915 mThread->join();
1916 mThread = nullptr;
1917 }
1918 }
1919
1920 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1921 FdTrigger* fdTrigger) {
1922 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001923 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001924 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001925 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001926 if (status != OK) return AssertionFailure() << statusToString(status);
1927 return AssertionSuccess();
1928 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001929 };
1930
1931 class Client {
1932 public:
1933 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1934 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001935 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001936 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1937 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001938 mFdTrigger = FdTrigger::make();
1939 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1940 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1941 return AssertionSuccess();
1942 }
1943 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1944 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1945 return mCertVerifier;
1946 }
Yifan Hong67519322021-09-13 18:51:16 -07001947 // connect() and do handshake
1948 bool setUpTransport() {
1949 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001950 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001951 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1952 return mClientTransport != nullptr;
1953 }
1954 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1955 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1956 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001957 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001958 status_t readStatus =
1959 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001960 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001961 if (readStatus != OK) {
1962 return AssertionFailure() << statusToString(readStatus);
1963 }
1964 if (readMessage != expectedMessage) {
1965 return AssertionFailure()
1966 << "Expected " << expectedMessage << ", actual " << readMessage;
1967 }
1968 return AssertionSuccess();
1969 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001970 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001971 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001972 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1973 return;
1974 }
1975 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001976 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001977 }
1978
Pawan49d74cb2022-08-03 21:19:11 +00001979 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1980
Yifan Hong1deca4b2021-09-10 16:16:44 -07001981 private:
1982 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001983 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001984 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1985 std::unique_ptr<RpcTransportCtx> mCtx;
1986 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1987 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001988 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001989 };
1990
1991 // Make A trust B.
1992 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001993 static status_t trust(RpcSecurity rpcSecurity,
1994 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1995 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001996 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001997 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1998 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1999 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002000 }
2001
2002 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002003};
2004
2005class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
2006public:
2007 using Server = RpcTransportTestUtils::Server;
2008 using Client = RpcTransportTestUtils::Client;
2009 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002010 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002011 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
2012 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00002013 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002014 return ret;
2015 }
2016 static std::vector<ParamType> getRpcTranportTestParams() {
2017 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00002018 for (auto serverVersion : testVersions()) {
2019 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
2020 for (auto rpcSecurity : RpcSecurityValues()) {
2021 switch (rpcSecurity) {
2022 case RpcSecurity::RAW: {
2023 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
2024 } break;
2025 case RpcSecurity::TLS: {
2026 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
2027 serverVersion);
2028 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
2029 serverVersion);
2030 } break;
2031 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002032 }
2033 }
2034 }
2035 return ret;
2036 }
2037 template <typename A, typename B>
2038 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002039 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2040 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002041 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
2042 }
Andrei Homescu12106de2022-04-27 04:42:21 +00002043 void SetUp() override {
2044 if constexpr (!kEnableRpcThreads) {
2045 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2046 }
2047 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002048};
2049
2050TEST_P(RpcTransportTest, GoodCertificate) {
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 ASSERT_EQ(OK, trust(server, &client));
2059
2060 server->start();
2061 client.run();
2062}
2063
2064TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002065 auto server = std::make_unique<Server>();
2066 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002067
2068 std::vector<Client> clients;
2069 for (int i = 0; i < 2; i++) {
2070 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002071 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002072 ASSERT_EQ(OK, trust(&client, server));
2073 ASSERT_EQ(OK, trust(server, &client));
2074 }
2075
2076 server->start();
2077 for (auto& client : clients) client.run();
2078}
2079
2080TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002081 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2082 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002083
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002084 auto untrustedServer = std::make_unique<Server>();
2085 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002086
2087 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002088 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002089
2090 ASSERT_EQ(OK, trust(untrustedServer, &client));
2091
2092 untrustedServer->start();
2093
2094 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2095 // the client can't verify the server's identity.
2096 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2097 client.run(handshakeOk);
2098}
2099TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002100 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2101 (void)serverVersion;
2102
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002103 auto validServer = std::make_unique<Server>();
2104 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002105
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002106 auto maliciousServer = std::make_unique<Server>();
2107 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002108
2109 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002110 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002111
2112 ASSERT_EQ(OK, trust(&client, validServer));
2113 ASSERT_EQ(OK, trust(validServer, &client));
2114 ASSERT_EQ(OK, trust(maliciousServer, &client));
2115
2116 maliciousServer->start();
2117
2118 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2119 // the client can't verify the server's identity.
2120 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2121 client.run(handshakeOk);
2122}
2123
2124TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002125 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2126 (void)serverVersion;
2127
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002128 auto server = std::make_unique<Server>();
2129 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002130
2131 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002132 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002133
2134 ASSERT_EQ(OK, trust(&client, server));
2135
2136 server->start();
2137
2138 // For TLS, Client should be able to verify server's identity, so client should see
2139 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2140 // identity and should drop the connection, so client shouldn't be able to read anything.
2141 bool readOk = rpcSecurity != RpcSecurity::TLS;
2142 client.run(true, readOk);
2143}
2144
2145TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002146 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2147 (void)serverVersion;
2148
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002149 auto server = std::make_unique<Server>();
2150 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002151
2152 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002153 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002154 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002155 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002156
2157 ASSERT_EQ(OK, trust(&validClient, server));
2158 ASSERT_EQ(OK, trust(&maliciousClient, server));
2159
2160 server->start();
2161
2162 // See UntrustedClient.
2163 bool readOk = rpcSecurity != RpcSecurity::TLS;
2164 maliciousClient.run(true, readOk);
2165}
2166
Yifan Hong67519322021-09-13 18:51:16 -07002167TEST_P(RpcTransportTest, Trigger) {
2168 std::string msg2 = ", world!";
2169 std::mutex writeMutex;
2170 std::condition_variable writeCv;
2171 bool shouldContinueWriting = false;
2172 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002173 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002174 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002175 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2176 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002177 if (status != OK) return AssertionFailure() << statusToString(status);
2178
2179 {
2180 std::unique_lock<std::mutex> lock(writeMutex);
2181 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2182 return AssertionFailure() << "write barrier not cleared in time!";
2183 }
2184 }
2185
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002186 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002187 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2188 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002189 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002190 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002191 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002192 << statusToString(status);
2193 return AssertionSuccess();
2194 };
2195
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002196 auto server = std::make_unique<Server>();
2197 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002198
2199 // Set up client
2200 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002201 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002202
2203 // Exchange keys
2204 ASSERT_EQ(OK, trust(&client, server));
2205 ASSERT_EQ(OK, trust(server, &client));
2206
2207 server->setPostConnect(serverPostConnect);
2208
Yifan Hong67519322021-09-13 18:51:16 -07002209 server->start();
2210 // connect() to server and do handshake
2211 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002212 // read the first message. This ensures that server has finished handshake and start handling
2213 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002214 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002215 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2216 // write is on an FdTrigger that has been shut down.
2217 server->shutdown();
2218 // Continues server thread to write the second message.
2219 {
Yifan Hong22211f82021-09-14 12:32:25 -07002220 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002221 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002222 }
Yifan Hong22211f82021-09-14 12:32:25 -07002223 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002224 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002225 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002226 // On the client side, second read fails with DEAD_OBJECT
2227 ASSERT_FALSE(client.readMessage(msg2));
2228}
2229
Pawan49d74cb2022-08-03 21:19:11 +00002230TEST_P(RpcTransportTest, CheckWaitingForRead) {
2231 std::mutex readMutex;
2232 std::condition_variable readCv;
2233 bool shouldContinueReading = false;
2234 // Server will write data on transport once its started
2235 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
2236 std::string message(RpcTransportTestUtils::kMessage);
2237 iovec messageIov{message.data(), message.size()};
2238 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2239 std::nullopt, nullptr);
2240 if (status != OK) return AssertionFailure() << statusToString(status);
2241
2242 {
2243 std::unique_lock<std::mutex> lock(readMutex);
2244 shouldContinueReading = true;
2245 lock.unlock();
2246 readCv.notify_all();
2247 }
2248 return AssertionSuccess();
2249 };
2250
2251 // Setup Server and client
2252 auto server = std::make_unique<Server>();
2253 ASSERT_TRUE(server->setUp(GetParam()));
2254
2255 Client client(server->getConnectToServerFn());
2256 ASSERT_TRUE(client.setUp(GetParam()));
2257
2258 ASSERT_EQ(OK, trust(&client, server));
2259 ASSERT_EQ(OK, trust(server, &client));
2260 server->setPostConnect(serverPostConnect);
2261
2262 server->start();
2263 ASSERT_TRUE(client.setUpTransport());
2264 {
2265 // Wait till server writes data
2266 std::unique_lock<std::mutex> lock(readMutex);
2267 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2268 }
2269
2270 // Since there is no read polling here, we will get polling count 0
2271 ASSERT_FALSE(client.isTransportWaiting());
2272 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2273 // Thread should increment polling count, read and decrement polling count
2274 // Again, polling count should be zero here
2275 ASSERT_FALSE(client.isTransportWaiting());
2276
2277 server->shutdown();
2278}
2279
Yifan Hong1deca4b2021-09-10 16:16:44 -07002280INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002281 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002282 RpcTransportTest::PrintParamInfo);
2283
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002284class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002285 : public testing::TestWithParam<
2286 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002287public:
2288 template <typename A, typename B>
2289 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002290 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2291 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002292 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2293 }
2294 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002295 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2296 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2297 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002298 };
2299};
2300
2301TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002302 if constexpr (!kEnableRpcThreads) {
2303 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2304 }
2305
Frederick Mayledc07cf82022-05-26 20:30:12 +00002306 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002307
2308 std::vector<uint8_t> pkeyData, certData;
2309 {
2310 auto pkey = makeKeyPairForSelfSignedCert();
2311 ASSERT_NE(nullptr, pkey);
2312 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2313 ASSERT_NE(nullptr, cert);
2314 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2315 certData = serializeCertificate(cert.get(), certificateFormat);
2316 }
2317
2318 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2319 auto desCert = deserializeCertificate(certData, certificateFormat);
2320 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002321 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2322 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002323
2324 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2325 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2326
2327 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2328 ASSERT_TRUE(client.setUp(utilsParam));
2329
2330 ASSERT_EQ(OK, trust(&client, server));
2331 ASSERT_EQ(OK, trust(server, &client));
2332
2333 server->start();
2334 client.run();
2335}
2336
2337INSTANTIATE_TEST_CASE_P(
2338 BinderRpc, RpcTransportTlsKeyTest,
2339 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2340 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002341 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2342 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002343 RpcTransportTlsKeyTest::PrintParamInfo);
2344
Steven Morelandc1635952021-04-01 16:20:47 +00002345} // namespace android
2346
2347int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002348 ::testing::InitGoogleTest(&argc, argv);
2349 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002350
Steven Moreland5553ac42020-11-11 02:14:45 +00002351 return RUN_ALL_TESTS();
2352}