blob: 7a550f7e1a207521c97a724e391489a4faffa091 [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 Moreland276d8df2022-09-28 23:56:39 +000088static void debugBacktrace(pid_t pid) {
89 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
90 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
91}
92
Steven Moreland5553ac42020-11-11 02:14:45 +000093class Process {
94public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -070095 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -070096 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
97 android::base::borrowed_fd /* readEnd */)>& f) {
98 android::base::unique_fd childWriteEnd;
99 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +0000100 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
101 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000102 if (0 == (mPid = fork())) {
103 // racey: assume parent doesn't crash before this is set
104 prctl(PR_SET_PDEATHSIG, SIGHUP);
105
Yifan Hong1deca4b2021-09-10 16:16:44 -0700106 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000107
108 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000109 }
110 }
111 ~Process() {
112 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000113 int wstatus;
114 waitpid(mPid, &wstatus, 0);
115 if (mCustomExitStatusCheck) {
116 mCustomExitStatusCheck(wstatus);
117 } else {
118 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
119 << "server process failed: " << WaitStatusToString(wstatus);
120 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000121 }
122 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700123 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700124 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000125
Frederick Maylea12b0962022-06-25 01:13:22 +0000126 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
127 mCustomExitStatusCheck = std::move(f);
128 }
129
Frederick Mayle69a0c992022-05-26 20:38:39 +0000130 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
131 void terminate() { kill(mPid, SIGTERM); }
132
Steven Moreland276d8df2022-09-28 23:56:39 +0000133 pid_t getPid() { return mPid; }
134
Steven Moreland5553ac42020-11-11 02:14:45 +0000135private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000136 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000137 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700138 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700139 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000140};
141
142static std::string allocateSocketAddress() {
143 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000144 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700145 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
146 unlink(ret.c_str());
147 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000148};
149
Steven Morelandda573042021-06-12 01:13:45 +0000150static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000151 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000152 return vsockPort++;
153}
154
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000155struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000156 // reference to process hosting a socket server
157 Process host;
158
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000159 struct SessionInfo {
160 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000161 sp<IBinder> root;
162 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000163
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000164 // client session objects associated with other process
165 // each one represents a separate session
166 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000167
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000168 ProcessSession(ProcessSession&&) = default;
169 ~ProcessSession() {
170 for (auto& session : sessions) {
171 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000172 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000173
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000174 for (auto& info : sessions) {
175 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000176
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000177 EXPECT_NE(nullptr, session);
178 EXPECT_NE(nullptr, session->state());
179 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000180
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000181 wp<RpcSession> weakSession = session;
182 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000183
184 EXPECT_EQ(nullptr, weakSession.promote())
Steven Morelanddb95d572022-10-01 01:02:47 +0000185 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()), "Leaked sess: ")
186 << session->getStrongCount();
Steven Moreland736664b2021-05-01 04:27:25 +0000187 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000188 }
189};
190
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000191// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000192// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000193struct BinderRpcTestProcessSession {
194 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000195
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000196 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000197 sp<IBinder> rootBinder;
198
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000199 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000200 sp<IBinderRpcTest> rootIface;
201
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000202 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000203 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000204
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000205 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
206 ~BinderRpcTestProcessSession() {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000207 if (!expectAlreadyShutdown) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000208 EXPECT_NE(nullptr, rootIface);
209 if (rootIface == nullptr) return;
210
Steven Moreland736664b2021-05-01 04:27:25 +0000211 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000212 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000213 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000214 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000215 for (auto remoteCount : remoteCounts) {
216 EXPECT_EQ(remoteCount, 1);
217 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000218
Steven Moreland798e0d12021-07-14 23:19:25 +0000219 // even though it is on another thread, shutdown races with
220 // the transaction reply being written
221 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
222 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
223 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000224 }
225
226 rootIface = nullptr;
227 rootBinder = nullptr;
228 }
229};
230
Yifan Hong1deca4b2021-09-10 16:16:44 -0700231static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700232 base::unique_fd serverFd(
233 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
234 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700235 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
236 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700237
238 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
239 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700240 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
241 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700242 }
243 return serverFd;
244}
245
Andrei Homescu2a298012022-06-15 01:08:54 +0000246using RunServiceFn = void (*)(android::base::borrowed_fd writeEnd,
247 android::base::borrowed_fd readEnd);
248
249class BinderRpc : public ::testing::TestWithParam<
250 std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t, bool, bool>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000251public:
Frederick Mayle69a0c992022-05-26 20:38:39 +0000252 SocketType socketType() const { return std::get<0>(GetParam()); }
253 RpcSecurity rpcSecurity() const { return std::get<1>(GetParam()); }
254 uint32_t clientVersion() const { return std::get<2>(GetParam()); }
255 uint32_t serverVersion() const { return std::get<3>(GetParam()); }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000256 bool serverSingleThreaded() const { return std::get<4>(GetParam()); }
Andrei Homescu2a298012022-06-15 01:08:54 +0000257 bool noKernel() const { return std::get<5>(GetParam()); }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000258
Andrei Homescua858b0e2022-08-01 23:43:09 +0000259 bool clientOrServerSingleThreaded() const {
260 return !kEnableRpcThreads || serverSingleThreaded();
261 }
262
Frederick Mayle69a0c992022-05-26 20:38:39 +0000263 // Whether the test params support sending FDs in parcels.
264 bool supportsFdTransport() const {
265 return clientVersion() >= 1 && serverVersion() >= 1 && rpcSecurity() != RpcSecurity::TLS &&
266 (socketType() == SocketType::PRECONNECTED || socketType() == SocketType::UNIX);
267 }
268
Yifan Hong702115c2021-06-24 15:39:18 -0700269 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000270 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
271 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
Frederick Mayledc07cf82022-05-26 20:30:12 +0000272 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Andrei Homescu2a298012022-06-15 01:08:54 +0000273 if (singleThreaded) {
274 ret += "_single_threaded";
275 }
276 if (noKernel) {
277 ret += "_no_kernel";
278 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700279 return ret;
280 }
281
Steven Morelandc1635952021-04-01 16:20:47 +0000282 // This creates a new process serving an interface on a certain number of
283 // threads.
Andrei Homescu2a298012022-06-15 01:08:54 +0000284 ProcessSession createRpcTestSocketServerProcessEtc(const BinderRpcOptions& options) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000285 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000286
Yifan Hong702115c2021-06-24 15:39:18 -0700287 SocketType socketType = std::get<0>(GetParam());
288 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000289 uint32_t clientVersion = std::get<2>(GetParam());
290 uint32_t serverVersion = std::get<3>(GetParam());
Andrei Homescu2a298012022-06-15 01:08:54 +0000291 bool singleThreaded = std::get<4>(GetParam());
292 bool noKernel = std::get<5>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000293
Andrei Homescu2a298012022-06-15 01:08:54 +0000294 std::string path = android::base::GetExecutableDirectory();
295 auto servicePath =
296 android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
297 singleThreaded ? "_single_threaded" : "",
298 noKernel ? "_no_kernel" : "");
Steven Morelandc1635952021-04-01 16:20:47 +0000299
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000300 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000301 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700302 android::base::borrowed_fd readEnd) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000303 auto writeFd = std::to_string(writeEnd.get());
304 auto readFd = std::to_string(readEnd.get());
305 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
306 NULL);
Steven Morelandc1635952021-04-01 16:20:47 +0000307 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000308 };
309
Andrei Homescu2a298012022-06-15 01:08:54 +0000310 BinderRpcTestServerConfig serverConfig;
311 serverConfig.numThreads = options.numThreads;
312 serverConfig.socketType = static_cast<int32_t>(socketType);
313 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
314 serverConfig.serverVersion = serverVersion;
315 serverConfig.vsockPort = allocateVsockPort();
316 serverConfig.addr = allocateSocketAddress();
317 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
318 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
319 static_cast<int32_t>(mode));
320 }
321 writeToFd(ret.host.writeEnd(), serverConfig);
322
Yifan Hong1deca4b2021-09-10 16:16:44 -0700323 std::vector<sp<RpcSession>> sessions;
324 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
325 for (size_t i = 0; i < options.numSessions; i++) {
326 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
327 }
328
329 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
330 BinderRpcTestClientInfo clientInfo;
331 for (const auto& session : sessions) {
332 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700333 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700334 }
335 writeToFd(ret.host.writeEnd(), clientInfo);
336
337 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700338 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700339 CHECK_NE(0, serverInfo.port);
340 }
341
342 if (rpcSecurity == RpcSecurity::TLS) {
343 const auto& serverCert = serverInfo.cert.data;
344 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700345 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
346 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700347 }
348
Steven Moreland2372f9d2021-08-05 15:42:01 -0700349 status_t status;
350
Yifan Hong1deca4b2021-09-10 16:16:44 -0700351 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000352 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700353 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700354 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000355 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Moreland659416d2021-05-11 00:47:50 +0000356
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000357 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700358 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700359 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000360 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700361 });
Steven Moreland4198a122021-08-03 17:37:58 -0700362 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000363 case SocketType::UNIX:
Andrei Homescu2a298012022-06-15 01:08:54 +0000364 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000365 break;
366 case SocketType::VSOCK:
Andrei Homescu2a298012022-06-15 01:08:54 +0000367 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000368 break;
369 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700370 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000371 break;
372 default:
373 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000374 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000375 if (options.allowConnectFailure && status != OK) {
376 ret.sessions.clear();
377 break;
378 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700379 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000380 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000381 }
Steven Morelandc1635952021-04-01 16:20:47 +0000382 return ret;
383 }
384
Andrei Homescu2a298012022-06-15 01:08:54 +0000385 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const BinderRpcOptions& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000386 BinderRpcTestProcessSession ret{
Andrei Homescu2a298012022-06-15 01:08:54 +0000387 .proc = createRpcTestSocketServerProcessEtc(options),
Steven Morelandc1635952021-04-01 16:20:47 +0000388 };
389
Frederick Mayle69a0c992022-05-26 20:38:39 +0000390 ret.rootBinder = ret.proc.sessions.empty() ? nullptr : ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000391 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
392
393 return ret;
394 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700395
396 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
397 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000398};
399
Steven Morelandc1635952021-04-01 16:20:47 +0000400TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000401 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000402 ASSERT_NE(proc.rootBinder, nullptr);
403 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
404}
405
Steven Moreland4cf688f2021-03-31 01:48:58 +0000406TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000407 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000408 ASSERT_NE(proc.rootBinder, nullptr);
409 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
410}
411
Andrei Homescua858b0e2022-08-01 23:43:09 +0000412TEST_P(BinderRpc, MultipleSessions) {
413 if (serverSingleThreaded()) {
414 // Tests with multiple sessions require a multi-threaded service,
415 // but work fine on a single-threaded client
416 GTEST_SKIP() << "This test requires a multi-threaded service";
417 }
418
Steven Moreland4313d7e2021-07-15 23:41:22 +0000419 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420 for (auto session : proc.proc.sessions) {
421 ASSERT_NE(nullptr, session.root);
422 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000423 }
424}
425
Andrei Homescua858b0e2022-08-01 23:43:09 +0000426TEST_P(BinderRpc, SeparateRootObject) {
427 if (serverSingleThreaded()) {
428 GTEST_SKIP() << "This test requires a multi-threaded service";
429 }
430
Steven Moreland51c44a92021-10-14 16:50:35 -0700431 SocketType type = std::get<0>(GetParam());
432 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
433 // we can't get port numbers for unix sockets
434 return;
435 }
436
437 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
438
439 int port1 = 0;
440 EXPECT_OK(proc.rootIface->getClientPort(&port1));
441
442 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
443 int port2;
444 EXPECT_OK(rootIface2->getClientPort(&port2));
445
446 // we should have a different IBinderRpcTest object created for each
447 // session, because we use setPerSessionRootObject
448 EXPECT_NE(port1, port2);
449}
450
Steven Morelandc1635952021-04-01 16:20:47 +0000451TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000452 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000453 Parcel data;
454 Parcel reply;
455 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
456}
457
Steven Moreland67753c32021-04-02 18:45:19 +0000458TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700459 auto proc1 = createRpcTestSocketServerProcess({});
460 auto proc2 = createRpcTestSocketServerProcess({});
461
462 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000463
464 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700465 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000466 p1.writeInt32(3);
467
Frederick Maylea4ed5672022-06-17 22:03:38 +0000468 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700469 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
470
Steven Moreland67753c32021-04-02 18:45:19 +0000471 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700472 p2.markForBinder(proc2.rootBinder);
473 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000474
475 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
476 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
477}
478
Steven Morelandc1635952021-04-01 16:20:47 +0000479TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000480 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000481 Parcel data;
482 data.markForBinder(proc.rootBinder);
483 Parcel reply;
484 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
485}
486
Steven Morelandc1635952021-04-01 16:20:47 +0000487TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000488 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000489 EXPECT_OK(proc.rootIface->sendString("asdf"));
490}
491
Steven Morelandc1635952021-04-01 16:20:47 +0000492TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000493 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000494 std::string doubled;
495 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
496 EXPECT_EQ("cool cool ", doubled);
497}
498
Steven Morelandc1635952021-04-01 16:20:47 +0000499TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000500 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000501 std::string single = std::string(1024, 'a');
502 std::string doubled;
503 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
504 EXPECT_EQ(single + single, doubled);
505}
506
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000507TEST_P(BinderRpc, InvalidNullBinderReturn) {
508 auto proc = createRpcTestSocketServerProcess({});
509
510 sp<IBinder> outBinder;
511 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
512}
513
Steven Morelandc1635952021-04-01 16:20:47 +0000514TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000515 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000516
517 int32_t pingResult;
518 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
519 EXPECT_EQ(OK, pingResult);
520
521 EXPECT_EQ(0, MyBinderRpcSession::gNum);
522}
523
Steven Morelandc1635952021-04-01 16:20:47 +0000524TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000525 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000526
527 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
528 sp<IBinder> outBinder;
529 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
530 EXPECT_EQ(inBinder, outBinder);
531
532 wp<IBinder> weak = inBinder;
533 inBinder = nullptr;
534 outBinder = nullptr;
535
536 // Force reading a reply, to process any pending dec refs from the other
537 // process (the other process will process dec refs there before processing
538 // the ping here).
539 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
540
541 EXPECT_EQ(nullptr, weak.promote());
542
543 EXPECT_EQ(0, MyBinderRpcSession::gNum);
544}
545
Steven Morelandc1635952021-04-01 16:20:47 +0000546TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000547 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000548
549 sp<IBinderRpcSession> session;
550 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
551
552 sp<IBinder> inBinder = IInterface::asBinder(session);
553 sp<IBinder> outBinder;
554 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
555 EXPECT_EQ(inBinder, outBinder);
556
557 wp<IBinder> weak = inBinder;
558 session = nullptr;
559 inBinder = nullptr;
560 outBinder = nullptr;
561
562 // Force reading a reply, to process any pending dec refs from the other
563 // process (the other process will process dec refs there before processing
564 // the ping here).
565 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
566
567 EXPECT_EQ(nullptr, weak.promote());
568}
569
Steven Morelandc1635952021-04-01 16:20:47 +0000570TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000571 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000572
573 sp<IBinder> outBinder;
574 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
575 EXPECT_EQ(nullptr, outBinder);
576}
577
Steven Morelandc1635952021-04-01 16:20:47 +0000578TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000579 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000580
581 IBinder* ptr = nullptr;
582 {
583 sp<IBinder> binder = new BBinder();
584 ptr = binder.get();
585 EXPECT_OK(proc.rootIface->holdBinder(binder));
586 }
587
588 sp<IBinder> held;
589 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
590
591 EXPECT_EQ(held.get(), ptr);
592
593 // stop holding binder, because we test to make sure references are cleaned
594 // up
595 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
596 // and flush ref counts
597 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
598}
599
600// START TESTS FOR LIMITATIONS OF SOCKET BINDER
601// These are behavioral differences form regular binder, where certain usecases
602// aren't supported.
603
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000604TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000605 auto proc1 = createRpcTestSocketServerProcess({});
606 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000607
608 sp<IBinder> outBinder;
609 EXPECT_EQ(INVALID_OPERATION,
610 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
611}
612
Andrei Homescua858b0e2022-08-01 23:43:09 +0000613TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
614 if (serverSingleThreaded()) {
615 GTEST_SKIP() << "This test requires a multi-threaded service";
616 }
617
Steven Moreland4313d7e2021-07-15 23:41:22 +0000618 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000619
620 sp<IBinder> outBinder;
621 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000622 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000623 .transactionError());
624}
625
Steven Morelandc1635952021-04-01 16:20:47 +0000626TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000627 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000628 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
629 "at build time.";
630 }
631
Steven Moreland4313d7e2021-07-15 23:41:22 +0000632 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000633
634 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
635 sp<IBinder> outBinder;
636 EXPECT_EQ(INVALID_OPERATION,
637 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
638}
639
Steven Morelandc1635952021-04-01 16:20:47 +0000640TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000641 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000642 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
643 "at build time.";
644 }
645
Steven Moreland4313d7e2021-07-15 23:41:22 +0000646 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000647
648 // for historical reasons, IServiceManager interface only returns the
649 // exception code
650 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
651 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
652}
653
654// END TESTS FOR LIMITATIONS OF SOCKET BINDER
655
Steven Morelandc1635952021-04-01 16:20:47 +0000656TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000657 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000658
659 sp<IBinder> outBinder;
660 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
661 EXPECT_EQ(proc.rootBinder, outBinder);
662}
663
Steven Morelandc1635952021-04-01 16:20:47 +0000664TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000665 auto proc = createRpcTestSocketServerProcess({
666 // Enable FD support because it uses more stack space and so represents
667 // something closer to a worst case scenario.
668 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
669 .serverSupportedFileDescriptorTransportModes =
670 {RpcSession::FileDescriptorTransportMode::UNIX},
671 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000672
673 auto nastyNester = sp<MyBinderRpcTest>::make();
674 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
675
676 wp<IBinder> weak = nastyNester;
677 nastyNester = nullptr;
678 EXPECT_EQ(nullptr, weak.promote());
679}
680
Steven Morelandc1635952021-04-01 16:20:47 +0000681TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000682 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000683
684 sp<IBinder> a;
685 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
686
687 sp<IBinder> b;
688 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
689
690 EXPECT_EQ(a, b);
691}
692
Steven Morelandc1635952021-04-01 16:20:47 +0000693TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000694 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000695
696 sp<IBinder> a;
697 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
698 wp<IBinder> weak = a;
699 a = nullptr;
700
701 sp<IBinder> b;
702 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
703
704 // this is the wrong behavior, since BpBinder
705 // doesn't implement onIncStrongAttempted
706 // but make sure there is no crash
707 EXPECT_EQ(nullptr, weak.promote());
708
709 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
710
711 // In order to fix this:
712 // - need to have incStrongAttempted reflected across IPC boundary (wait for
713 // response to promote - round trip...)
714 // - sendOnLastWeakRef, to delete entries out of RpcState table
715 EXPECT_EQ(b, weak.promote());
716}
717
718#define expectSessions(expected, iface) \
719 do { \
720 int session; \
721 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
722 EXPECT_EQ(expected, session); \
723 } while (false)
724
Steven Morelandc1635952021-04-01 16:20:47 +0000725TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000726 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000727
728 sp<IBinderRpcSession> session;
729 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
730 std::string out;
731 EXPECT_OK(session->getName(&out));
732 EXPECT_EQ("aoeu", out);
733
734 expectSessions(1, proc.rootIface);
735 session = nullptr;
736 expectSessions(0, proc.rootIface);
737}
738
Steven Morelandc1635952021-04-01 16:20:47 +0000739TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000740 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000741
742 std::vector<sp<IBinderRpcSession>> sessions;
743
744 for (size_t i = 0; i < 15; i++) {
745 expectSessions(i, proc.rootIface);
746 sp<IBinderRpcSession> session;
747 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
748 sessions.push_back(session);
749 }
750 expectSessions(sessions.size(), proc.rootIface);
751 for (size_t i = 0; i < sessions.size(); i++) {
752 std::string out;
753 EXPECT_OK(sessions.at(i)->getName(&out));
754 EXPECT_EQ(std::to_string(i), out);
755 }
756 expectSessions(sessions.size(), proc.rootIface);
757
758 while (!sessions.empty()) {
759 sessions.pop_back();
760 expectSessions(sessions.size(), proc.rootIface);
761 }
762 expectSessions(0, proc.rootIface);
763}
764
765size_t epochMillis() {
766 using std::chrono::duration_cast;
767 using std::chrono::milliseconds;
768 using std::chrono::seconds;
769 using std::chrono::system_clock;
770 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
771}
772
Andrei Homescua858b0e2022-08-01 23:43:09 +0000773TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
774 if (clientOrServerSingleThreaded()) {
775 GTEST_SKIP() << "This test requires multiple threads";
776 }
777
Steven Moreland5553ac42020-11-11 02:14:45 +0000778 constexpr size_t kNumThreads = 10;
779
Steven Moreland4313d7e2021-07-15 23:41:22 +0000780 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000781
782 EXPECT_OK(proc.rootIface->lock());
783
784 // block all but one thread taking locks
785 std::vector<std::thread> ts;
786 for (size_t i = 0; i < kNumThreads - 1; i++) {
787 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
788 }
789
790 usleep(100000); // give chance for calls on other threads
791
792 // other calls still work
793 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
794
795 constexpr size_t blockTimeMs = 500;
796 size_t epochMsBefore = epochMillis();
797 // after this, we should never see a response within this time
798 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
799
800 // this call should be blocked for blockTimeMs
801 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
802
803 size_t epochMsAfter = epochMillis();
804 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
805
806 for (auto& t : ts) t.join();
807}
808
Yifan Hong1f44f982021-10-08 17:16:47 -0700809void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
810 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000811 size_t epochMsBefore = epochMillis();
812
813 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700814 for (size_t i = 0; i < numCalls; i++) {
815 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000816 }
817
818 for (auto& t : ts) t.join();
819
820 size_t epochMsAfter = epochMillis();
821
Yifan Hong1f44f982021-10-08 17:16:47 -0700822 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000823
824 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700825 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
826}
827
Andrei Homescua858b0e2022-08-01 23:43:09 +0000828TEST_P(BinderRpc, ThreadPoolOverSaturated) {
829 if (clientOrServerSingleThreaded()) {
830 GTEST_SKIP() << "This test requires multiple threads";
831 }
832
Yifan Hong1f44f982021-10-08 17:16:47 -0700833 constexpr size_t kNumThreads = 10;
834 constexpr size_t kNumCalls = kNumThreads + 3;
835 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
836 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
837}
838
Andrei Homescua858b0e2022-08-01 23:43:09 +0000839TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
840 if (clientOrServerSingleThreaded()) {
841 GTEST_SKIP() << "This test requires multiple threads";
842 }
843
Yifan Hong1f44f982021-10-08 17:16:47 -0700844 constexpr size_t kNumThreads = 20;
845 constexpr size_t kNumOutgoingConnections = 10;
846 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
847 auto proc = createRpcTestSocketServerProcess(
848 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
849 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000850}
851
Andrei Homescua858b0e2022-08-01 23:43:09 +0000852TEST_P(BinderRpc, ThreadingStressTest) {
853 if (clientOrServerSingleThreaded()) {
854 GTEST_SKIP() << "This test requires multiple threads";
855 }
856
Steven Moreland5553ac42020-11-11 02:14:45 +0000857 constexpr size_t kNumClientThreads = 10;
858 constexpr size_t kNumServerThreads = 10;
859 constexpr size_t kNumCalls = 100;
860
Steven Moreland4313d7e2021-07-15 23:41:22 +0000861 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000862
863 std::vector<std::thread> threads;
864 for (size_t i = 0; i < kNumClientThreads; i++) {
865 threads.push_back(std::thread([&] {
866 for (size_t j = 0; j < kNumCalls; j++) {
867 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000868 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000869 EXPECT_EQ(proc.rootBinder, out);
870 }
871 }));
872 }
873
874 for (auto& t : threads) t.join();
875}
876
Steven Moreland925ba0a2021-09-17 18:06:32 -0700877static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
878 std::vector<std::thread> threads;
879 for (size_t i = 0; i < threadCount; i++) {
880 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
881 }
882 for (auto& t : threads) t.join();
883}
884
Andrei Homescua858b0e2022-08-01 23:43:09 +0000885TEST_P(BinderRpc, OnewayStressTest) {
886 if (clientOrServerSingleThreaded()) {
887 GTEST_SKIP() << "This test requires multiple threads";
888 }
889
Steven Morelandc6046982021-04-20 00:49:42 +0000890 constexpr size_t kNumClientThreads = 10;
891 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700892 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000893
Steven Moreland4313d7e2021-07-15 23:41:22 +0000894 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000895
896 std::vector<std::thread> threads;
897 for (size_t i = 0; i < kNumClientThreads; i++) {
898 threads.push_back(std::thread([&] {
899 for (size_t j = 0; j < kNumCalls; j++) {
900 EXPECT_OK(proc.rootIface->sendString("a"));
901 }
Steven Morelandc6046982021-04-20 00:49:42 +0000902 }));
903 }
904
905 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700906
907 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000908}
909
Steven Morelandc1635952021-04-01 16:20:47 +0000910TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000911 constexpr size_t kReallyLongTimeMs = 100;
912 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
913
Steven Moreland4313d7e2021-07-15 23:41:22 +0000914 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000915
916 size_t epochMsBefore = epochMillis();
917
918 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
919
920 size_t epochMsAfter = epochMillis();
921 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
922}
923
Andrei Homescua858b0e2022-08-01 23:43:09 +0000924TEST_P(BinderRpc, OnewayCallQueueing) {
925 if (clientOrServerSingleThreaded()) {
926 GTEST_SKIP() << "This test requires multiple threads";
927 }
928
Steven Moreland5553ac42020-11-11 02:14:45 +0000929 constexpr size_t kNumSleeps = 10;
930 constexpr size_t kNumExtraServerThreads = 4;
931 constexpr size_t kSleepMs = 50;
932
933 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000934 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000935
936 EXPECT_OK(proc.rootIface->lock());
937
Steven Moreland1c678802021-09-17 16:48:47 -0700938 size_t epochMsBefore = epochMillis();
939
940 // all these *Async commands should be queued on the server sequentially,
941 // even though there are multiple threads.
942 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000943 proc.rootIface->sleepMsAsync(kSleepMs);
944 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000945 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
946
Steven Moreland1c678802021-09-17 16:48:47 -0700947 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000948 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700949
Steven Moreland5553ac42020-11-11 02:14:45 +0000950 size_t epochMsAfter = epochMillis();
951
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000952 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000953
Steven Moreland925ba0a2021-09-17 18:06:32 -0700954 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000955}
956
Andrei Homescua858b0e2022-08-01 23:43:09 +0000957TEST_P(BinderRpc, OnewayCallExhaustion) {
958 if (clientOrServerSingleThreaded()) {
959 GTEST_SKIP() << "This test requires multiple threads";
960 }
961
Steven Morelandd45be622021-06-04 02:19:37 +0000962 constexpr size_t kNumClients = 2;
963 constexpr size_t kTooLongMs = 1000;
964
Steven Moreland4313d7e2021-07-15 23:41:22 +0000965 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000966
967 // Build up oneway calls on the second session to make sure it terminates
968 // and shuts down. The first session should be unaffected (proc destructor
969 // checks the first session).
970 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
971
972 std::vector<std::thread> threads;
973 for (size_t i = 0; i < kNumClients; i++) {
974 // one of these threads will get stuck queueing a transaction once the
975 // socket fills up, the other will be able to fill up transactions on
976 // this object
977 threads.push_back(std::thread([&] {
978 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
979 }
980 }));
981 }
982 for (auto& t : threads) t.join();
983
984 Status status = iface->sleepMsAsync(kTooLongMs);
985 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
986
Steven Moreland798e0d12021-07-14 23:19:25 +0000987 // now that it has died, wait for the remote session to shutdown
988 std::vector<int32_t> remoteCounts;
989 do {
990 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
991 } while (remoteCounts.size() == kNumClients);
992
Steven Morelandd45be622021-06-04 02:19:37 +0000993 // the second session should be shutdown in the other process by the time we
994 // are able to join above (it'll only be hung up once it finishes processing
995 // any pending commands). We need to erase this session from the record
996 // here, so that the destructor for our session won't check that this
997 // session is valid, but we still want it to test the other session.
998 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
999}
1000
Steven Moreland659416d2021-05-11 00:47:50 +00001001TEST_P(BinderRpc, Callbacks) {
1002 const static std::string kTestString = "good afternoon!";
1003
Steven Morelandc7d40132021-06-10 03:42:11 +00001004 for (bool callIsOneway : {true, false}) {
1005 for (bool callbackIsOneway : {true, false}) {
1006 for (bool delayed : {true, false}) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001007 if (clientOrServerSingleThreaded() &&
1008 (callIsOneway || callbackIsOneway || delayed)) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001009 // we have no incoming connections to receive the callback
1010 continue;
1011 }
1012
Andrei Homescua858b0e2022-08-01 23:43:09 +00001013 size_t numIncomingConnections = clientOrServerSingleThreaded() ? 0 : 1;
Steven Moreland4313d7e2021-07-15 23:41:22 +00001014 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +00001015 {.numThreads = 1,
1016 .numSessions = 1,
Andrei Homescu2a298012022-06-15 01:08:54 +00001017 .numIncomingConnections = numIncomingConnections});
Steven Morelandc7d40132021-06-10 03:42:11 +00001018 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001019
Steven Morelandc7d40132021-06-10 03:42:11 +00001020 if (callIsOneway) {
1021 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1022 kTestString));
1023 } else {
1024 EXPECT_OK(
1025 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1026 }
Steven Moreland659416d2021-05-11 00:47:50 +00001027
Steven Moreland03ecce62022-05-13 23:22:05 +00001028 // if both transactions are synchronous and the response is sent back on the
1029 // same thread, everything should have happened in a nested call. Otherwise,
1030 // the callback will be processed on another thread.
1031 if (callIsOneway || callbackIsOneway || delayed) {
1032 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001033 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001034 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1035 }
Steven Moreland659416d2021-05-11 00:47:50 +00001036
Steven Morelandc7d40132021-06-10 03:42:11 +00001037 EXPECT_EQ(cb->mValues.size(), 1)
1038 << "callIsOneway: " << callIsOneway
1039 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1040 if (cb->mValues.empty()) continue;
1041 EXPECT_EQ(cb->mValues.at(0), kTestString)
1042 << "callIsOneway: " << callIsOneway
1043 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001044
Steven Morelandc7d40132021-06-10 03:42:11 +00001045 // since we are severing the connection, we need to go ahead and
1046 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001047 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1048 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1049 }
Steven Moreland659416d2021-05-11 00:47:50 +00001050
Steven Moreland1b304292021-07-15 22:59:34 +00001051 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001052 // need to manually shut it down
1053 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Morelandc7d40132021-06-10 03:42:11 +00001054 proc.expectAlreadyShutdown = true;
1055 }
Steven Moreland659416d2021-05-11 00:47:50 +00001056 }
1057 }
1058}
1059
Devin Moore66d5b7a2022-07-07 21:42:10 +00001060TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001061 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001062 GTEST_SKIP() << "This test requires multiple threads";
1063 }
1064 class MyDeathRec : public IBinder::DeathRecipient {
1065 public:
1066 void binderDied(const wp<IBinder>& /* who */) override {
1067 dead = true;
1068 mCv.notify_one();
1069 }
1070 std::mutex mMtx;
1071 std::condition_variable mCv;
1072 bool dead = false;
1073 };
1074
1075 // Death recipient needs to have an incoming connection to be called
1076 auto proc = createRpcTestSocketServerProcess(
1077 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1078
1079 auto dr = sp<MyDeathRec>::make();
1080 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1081
1082 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1083 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1084 }
1085
1086 std::unique_lock<std::mutex> lock(dr->mMtx);
Devin Moore47a12012022-08-19 21:16:17 +00001087 ASSERT_TRUE(dr->mCv.wait_for(lock, 1000ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001088
1089 // need to wait for the session to shutdown so we don't "Leak session"
1090 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1091 proc.expectAlreadyShutdown = true;
1092}
1093
1094TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001095 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001096 GTEST_SKIP() << "This test requires multiple threads";
1097 }
1098 class MyDeathRec : public IBinder::DeathRecipient {
1099 public:
1100 void binderDied(const wp<IBinder>& /* who */) override {
1101 dead = true;
1102 mCv.notify_one();
1103 }
1104 std::mutex mMtx;
1105 std::condition_variable mCv;
1106 bool dead = false;
1107 };
1108
1109 // Death recipient needs to have an incoming connection to be called
1110 auto proc = createRpcTestSocketServerProcess(
1111 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1112
1113 auto dr = sp<MyDeathRec>::make();
1114 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1115
1116 // Explicitly calling shutDownAndWait will cause the death recipients
1117 // to be called.
1118 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1119
1120 std::unique_lock<std::mutex> lock(dr->mMtx);
1121 if (!dr->dead) {
1122 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1123 }
1124 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1125
1126 proc.proc.host.terminate();
1127 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1128 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1129 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1130 });
1131 proc.expectAlreadyShutdown = true;
1132}
1133
1134TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1135 class MyDeathRec : public IBinder::DeathRecipient {
1136 public:
1137 void binderDied(const wp<IBinder>& /* who */) override {}
1138 };
1139
1140 auto proc = createRpcTestSocketServerProcess(
1141 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1142
1143 auto dr = sp<MyDeathRec>::make();
1144 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1145 "Cannot register a DeathRecipient without any incoming connections.");
1146}
1147
1148TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001149 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001150 GTEST_SKIP() << "This test requires multiple threads";
1151 }
1152 class MyDeathRec : public IBinder::DeathRecipient {
1153 public:
1154 void binderDied(const wp<IBinder>& /* who */) override {
1155 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1156 }
1157 };
1158
1159 // Death recipient needs to have an incoming connection to be called
1160 auto proc = createRpcTestSocketServerProcess(
1161 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1162
1163 auto dr = sp<MyDeathRec>::make();
1164 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1165 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1166
1167 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1168 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1169 }
1170
1171 // need to wait for the session to shutdown so we don't "Leak session"
1172 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1173 proc.expectAlreadyShutdown = true;
1174}
1175
Steven Moreland195edb82021-06-08 02:44:39 +00001176TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001177 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001178 auto cb = sp<MyBinderRpcCallback>::make();
1179
1180 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1181 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1182}
1183
Steven Morelandc1635952021-04-01 16:20:47 +00001184TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001185 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001186 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001187
1188 // make sure there is some state during crash
1189 // 1. we hold their binder
1190 sp<IBinderRpcSession> session;
1191 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1192 // 2. they hold our binder
1193 sp<IBinder> binder = new BBinder();
1194 EXPECT_OK(proc.rootIface->holdBinder(binder));
1195
1196 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1197 << "Do death cleanup: " << doDeathCleanup;
1198
Frederick Maylea12b0962022-06-25 01:13:22 +00001199 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1200 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1201 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1202 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001203 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001204 }
1205}
1206
Steven Morelandd7302072021-05-15 01:32:04 +00001207TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001208 // This test only works if the current process shared the internal state of
1209 // ProcessState with the service across the call to fork(). Both the static
1210 // libraries and libbinder.so have their own separate copies of all the
1211 // globals, so the test only works when the test client and service both use
1212 // libbinder.so (when using static libraries, even a client and service
1213 // using the same kind of static library should have separate copies of the
1214 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +00001215 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001216 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1217 "at build time.";
1218 }
1219
Steven Moreland4313d7e2021-07-15 23:41:22 +00001220 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001221
Andrei Homescu2a298012022-06-15 01:08:54 +00001222 // we can't allocate IPCThreadState so actually the first time should
1223 // succeed :(
1224 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001225
1226 // second time! we catch the error :)
1227 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1228
Frederick Maylea12b0962022-06-25 01:13:22 +00001229 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1230 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1231 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1232 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001233 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001234}
1235
Frederick Mayle69a0c992022-05-26 20:38:39 +00001236TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1237 auto proc = createRpcTestSocketServerProcess({
1238 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1239 .serverSupportedFileDescriptorTransportModes =
1240 {RpcSession::FileDescriptorTransportMode::UNIX},
1241 .allowConnectFailure = true,
1242 });
1243 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1244 proc.proc.host.terminate();
1245 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1246 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1247 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1248 });
1249 proc.expectAlreadyShutdown = true;
1250}
1251
1252TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1253 auto proc = createRpcTestSocketServerProcess({
1254 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1255 .serverSupportedFileDescriptorTransportModes =
1256 {RpcSession::FileDescriptorTransportMode::NONE},
1257 .allowConnectFailure = true,
1258 });
1259 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1260 proc.proc.host.terminate();
1261 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1262 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1263 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1264 });
1265 proc.expectAlreadyShutdown = true;
1266}
1267
1268TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1269 auto proc = createRpcTestSocketServerProcess({
1270 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1271 .serverSupportedFileDescriptorTransportModes =
1272 {RpcSession::FileDescriptorTransportMode::NONE,
1273 RpcSession::FileDescriptorTransportMode::UNIX},
1274 });
1275
1276 android::os::ParcelFileDescriptor out;
1277 auto status = proc.rootIface->echoAsFile("hello", &out);
1278 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1279}
1280
1281TEST_P(BinderRpc, ReceiveFile) {
1282 auto proc = createRpcTestSocketServerProcess({
1283 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1284 .serverSupportedFileDescriptorTransportModes =
1285 {RpcSession::FileDescriptorTransportMode::UNIX},
1286 });
1287
1288 android::os::ParcelFileDescriptor out;
1289 auto status = proc.rootIface->echoAsFile("hello", &out);
1290 if (!supportsFdTransport()) {
1291 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1292 return;
1293 }
1294 ASSERT_TRUE(status.isOk()) << status;
1295
1296 std::string result;
1297 CHECK(android::base::ReadFdToString(out.get(), &result));
1298 EXPECT_EQ(result, "hello");
1299}
1300
1301TEST_P(BinderRpc, SendFiles) {
1302 auto proc = createRpcTestSocketServerProcess({
1303 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1304 .serverSupportedFileDescriptorTransportModes =
1305 {RpcSession::FileDescriptorTransportMode::UNIX},
1306 });
1307
1308 std::vector<android::os::ParcelFileDescriptor> files;
1309 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1310 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1311 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1312 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1313
1314 android::os::ParcelFileDescriptor out;
1315 auto status = proc.rootIface->concatFiles(files, &out);
1316 if (!supportsFdTransport()) {
1317 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1318 return;
1319 }
1320 ASSERT_TRUE(status.isOk()) << status;
1321
1322 std::string result;
1323 CHECK(android::base::ReadFdToString(out.get(), &result));
1324 EXPECT_EQ(result, "123abcd");
1325}
1326
1327TEST_P(BinderRpc, SendMaxFiles) {
1328 if (!supportsFdTransport()) {
1329 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1330 }
1331
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 for (int i = 0; i < 253; i++) {
1340 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1341 }
1342
1343 android::os::ParcelFileDescriptor out;
1344 auto status = proc.rootIface->concatFiles(files, &out);
1345 ASSERT_TRUE(status.isOk()) << status;
1346
1347 std::string result;
1348 CHECK(android::base::ReadFdToString(out.get(), &result));
1349 EXPECT_EQ(result, std::string(253, 'a'));
1350}
1351
1352TEST_P(BinderRpc, SendTooManyFiles) {
1353 if (!supportsFdTransport()) {
1354 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1355 }
1356
1357 auto proc = createRpcTestSocketServerProcess({
1358 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1359 .serverSupportedFileDescriptorTransportModes =
1360 {RpcSession::FileDescriptorTransportMode::UNIX},
1361 });
1362
1363 std::vector<android::os::ParcelFileDescriptor> files;
1364 for (int i = 0; i < 254; i++) {
1365 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1366 }
1367
1368 android::os::ParcelFileDescriptor out;
1369 auto status = proc.rootIface->concatFiles(files, &out);
1370 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1371}
1372
Steven Moreland37aff182021-03-26 02:04:16 +00001373TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001374 if constexpr (!kEnableSharedLibs) {
1375 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1376 }
1377
Steven Moreland4313d7e2021-07-15 23:41:22 +00001378 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001379
1380 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1381 ASSERT_NE(binder, nullptr);
1382
1383 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1384}
1385
1386TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001387 if constexpr (!kEnableSharedLibs) {
1388 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1389 }
1390
Steven Moreland4313d7e2021-07-15 23:41:22 +00001391 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001392
1393 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1394 ASSERT_NE(binder, nullptr);
1395
1396 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1397 ASSERT_NE(ndkBinder, nullptr);
1398
1399 std::string out;
1400 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1401 ASSERT_TRUE(status.isOk()) << status.getDescription();
1402 ASSERT_EQ("aoeuaoeu", out);
1403}
1404
Steven Moreland5553ac42020-11-11 02:14:45 +00001405ssize_t countFds() {
1406 DIR* dir = opendir("/proc/self/fd/");
1407 if (dir == nullptr) return -1;
1408 ssize_t ret = 0;
1409 dirent* ent;
1410 while ((ent = readdir(dir)) != nullptr) ret++;
1411 closedir(dir);
1412 return ret;
1413}
1414
Andrei Homescua858b0e2022-08-01 23:43:09 +00001415TEST_P(BinderRpc, Fds) {
1416 if (serverSingleThreaded()) {
1417 GTEST_SKIP() << "This test requires multiple threads";
1418 }
1419
Steven Moreland5553ac42020-11-11 02:14:45 +00001420 ssize_t beforeFds = countFds();
1421 ASSERT_GE(beforeFds, 0);
1422 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001423 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001424 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1425 }
1426 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1427}
1428
Devin Moore800b2252021-10-15 16:22:57 +00001429TEST_P(BinderRpc, AidlDelegatorTest) {
1430 auto proc = createRpcTestSocketServerProcess({});
1431 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1432 ASSERT_NE(nullptr, myDelegator);
1433
1434 std::string doubled;
1435 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1436 EXPECT_EQ("cool cool ", doubled);
1437}
1438
Steven Morelandda573042021-06-12 01:13:45 +00001439static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001440 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001441 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001442
Andrei Homescu992a4052022-06-28 21:26:18 +00001443 android::base::unique_fd serverFd(
1444 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1445 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1446
1447 sockaddr_vm serverAddr{
1448 .svm_family = AF_VSOCK,
1449 .svm_port = vsockPort,
1450 .svm_cid = VMADDR_CID_ANY,
1451 };
1452 int ret = TEMP_FAILURE_RETRY(
1453 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1454 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1455 strerror(errno));
1456
1457 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1458 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1459 strerror(errno));
1460
1461 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1462 // to see if the kernel supports it. It's safe to use a blocking
1463 // connect because vsock sockets have a 2 second connection timeout,
1464 // and they return ETIMEDOUT after that.
1465 android::base::unique_fd connectFd(
1466 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1467 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1468 strerror(errno));
1469
1470 bool success = false;
1471 sockaddr_vm connectAddr{
1472 .svm_family = AF_VSOCK,
1473 .svm_port = vsockPort,
1474 .svm_cid = VMADDR_CID_LOCAL,
1475 };
1476 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1477 sizeof(connectAddr)));
1478 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1479 android::base::unique_fd acceptFd;
1480 while (true) {
1481 pollfd pfd[]{
1482 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1483 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1484 };
1485 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1486 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1487
1488 if (pfd[0].revents & POLLIN) {
1489 sockaddr_vm acceptAddr;
1490 socklen_t acceptAddrLen = sizeof(acceptAddr);
1491 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1492 reinterpret_cast<sockaddr*>(&acceptAddr),
1493 &acceptAddrLen, SOCK_CLOEXEC));
1494 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1495 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1496 "Truncated address");
1497
1498 // Store the fd in acceptFd so we keep the connection alive
1499 // while polling connectFd
1500 acceptFd.reset(ret);
1501 }
1502
1503 if (pfd[1].revents & POLLOUT) {
1504 // Connect either succeeded or timed out
1505 int connectErrno;
1506 socklen_t connectErrnoLen = sizeof(connectErrno);
1507 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1508 &connectErrnoLen);
1509 LOG_ALWAYS_FATAL_IF(ret == -1,
1510 "Could not getsockopt() after connect() "
1511 "on non-blocking socket: %s.",
1512 strerror(errno));
1513
1514 // We're done, this is all we wanted
1515 success = connectErrno == 0;
1516 break;
1517 }
1518 }
1519 } else {
1520 success = ret == 0;
1521 }
1522
1523 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1524
1525 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001526}
1527
Yifan Hong1deca4b2021-09-10 16:16:44 -07001528static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1529 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1530
1531 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001532
1533 static bool hasVsockLoopback = testSupportVsockLoopback();
1534
1535 if (hasVsockLoopback) {
1536 ret.push_back(SocketType::VSOCK);
1537 }
1538
1539 return ret;
1540}
1541
Frederick Mayledc07cf82022-05-26 20:30:12 +00001542static std::vector<uint32_t> testVersions() {
1543 std::vector<uint32_t> versions;
1544 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1545 versions.push_back(i);
1546 }
1547 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1548 return versions;
1549}
1550
Yifan Hong702115c2021-06-24 15:39:18 -07001551INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1552 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001553 ::testing::ValuesIn(RpcSecurityValues()),
1554 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001555 ::testing::ValuesIn(testVersions()),
1556 ::testing::Values(false, true),
1557 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001558 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001559
Yifan Hong702115c2021-06-24 15:39:18 -07001560class BinderRpcServerRootObject
1561 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001562
1563TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1564 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1565 auto setRootObject = [](bool isStrong) -> SetFn {
1566 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1567 };
1568
Yifan Hong702115c2021-06-24 15:39:18 -07001569 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1570 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001571 auto binder1 = sp<BBinder>::make();
1572 IBinder* binderRaw1 = binder1.get();
1573 setRootObject(isStrong1)(server.get(), binder1);
1574 EXPECT_EQ(binderRaw1, server->getRootObject());
1575 binder1.clear();
1576 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1577
1578 auto binder2 = sp<BBinder>::make();
1579 IBinder* binderRaw2 = binder2.get();
1580 setRootObject(isStrong2)(server.get(), binder2);
1581 EXPECT_EQ(binderRaw2, server->getRootObject());
1582 binder2.clear();
1583 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1584}
1585
1586INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001587 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1588 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001589
Yifan Hong1a235852021-05-13 16:07:47 -07001590class OneOffSignal {
1591public:
1592 // If notify() was previously called, or is called within |duration|, return true; else false.
1593 template <typename R, typename P>
1594 bool wait(std::chrono::duration<R, P> duration) {
1595 std::unique_lock<std::mutex> lock(mMutex);
1596 return mCv.wait_for(lock, duration, [this] { return mValue; });
1597 }
1598 void notify() {
1599 std::unique_lock<std::mutex> lock(mMutex);
1600 mValue = true;
1601 lock.unlock();
1602 mCv.notify_all();
1603 }
1604
1605private:
1606 std::mutex mMutex;
1607 std::condition_variable mCv;
1608 bool mValue = false;
1609};
1610
Yifan Hong194acf22021-06-29 18:44:56 -07001611TEST(BinderRpc, Java) {
1612#if !defined(__ANDROID__)
1613 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1614 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1615 "to binderHostDeviceTest. Hence, just disable this test on host.";
1616#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001617 if constexpr (!kEnableKernelIpc) {
1618 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1619 "at build time.";
1620 }
1621
Yifan Hong194acf22021-06-29 18:44:56 -07001622 sp<IServiceManager> sm = defaultServiceManager();
1623 ASSERT_NE(nullptr, sm);
1624 // Any Java service with non-empty getInterfaceDescriptor() would do.
1625 // Let's pick batteryproperties.
1626 auto binder = sm->checkService(String16("batteryproperties"));
1627 ASSERT_NE(nullptr, binder);
1628 auto descriptor = binder->getInterfaceDescriptor();
1629 ASSERT_GE(descriptor.size(), 0);
1630 ASSERT_EQ(OK, binder->pingBinder());
1631
1632 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001633 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001634 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001635 auto socket = rpcServer->releaseServer();
1636
1637 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001638 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1639
Yifan Honge3caaf22022-01-12 14:46:56 -08001640 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1641 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001642 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001643 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1644 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001645 << statusToString(setRpcClientDebugStatus);
1646 GTEST_SKIP();
1647 }
1648
1649 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001650
1651 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001652 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001653 auto rpcBinder = rpcSession->getRootObject();
1654 ASSERT_NE(nullptr, rpcBinder);
1655
1656 ASSERT_EQ(OK, rpcBinder->pingBinder());
1657
1658 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1659 << "getInterfaceDescriptor should not crash system_server";
1660 ASSERT_EQ(OK, rpcBinder->pingBinder());
1661}
1662
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001663class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1664public:
1665 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1666 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1667 std::to_string(std::get<1>(info.param));
1668 }
1669};
1670
1671TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1672 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1673 int sinkFd = sink.get();
1674 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1675 server->setProtocolVersion(std::get<1>(GetParam()));
1676 ASSERT_FALSE(server->hasServer());
1677 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1678 ASSERT_TRUE(server->hasServer());
1679 base::unique_fd retrieved = server->releaseServer();
1680 ASSERT_FALSE(server->hasServer());
1681 ASSERT_EQ(sinkFd, retrieved.get());
1682}
1683
1684TEST_P(BinderRpcServerOnly, Shutdown) {
1685 if constexpr (!kEnableRpcThreads) {
1686 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1687 }
1688
1689 auto addr = allocateSocketAddress();
1690 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1691 server->setProtocolVersion(std::get<1>(GetParam()));
1692 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1693 auto joinEnds = std::make_shared<OneOffSignal>();
1694
1695 // If things are broken and the thread never stops, don't block other tests. Because the thread
1696 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1697 // shared pointers are passed.
1698 std::thread([server, joinEnds] {
1699 server->join();
1700 joinEnds->notify();
1701 }).detach();
1702
1703 bool shutdown = false;
1704 for (int i = 0; i < 10 && !shutdown; i++) {
1705 usleep(300 * 1000); // 300ms; total 3s
1706 if (server->shutdown()) shutdown = true;
1707 }
1708 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1709
1710 ASSERT_TRUE(joinEnds->wait(2s))
1711 << "After server->shutdown() returns true, join() did not stop after 2s";
1712}
1713
Frederick Mayledc07cf82022-05-26 20:30:12 +00001714INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1715 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1716 ::testing::ValuesIn(testVersions())),
1717 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001718
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001719class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001720public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001721 // Only parameterized only server version because `RpcSession` is bypassed
1722 // in the client half of the tests.
1723 using Param =
1724 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001725 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001726
1727 // A server that handles client socket connections.
1728 class Server {
1729 public:
1730 explicit Server() {}
1731 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001732 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001733 [[nodiscard]] AssertionResult setUp(
1734 const Param& param,
1735 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001736 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001737 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001738 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001739 switch (socketType) {
1740 case SocketType::PRECONNECTED: {
1741 return AssertionFailure() << "Not supported by this test";
1742 } break;
1743 case SocketType::UNIX: {
1744 auto addr = allocateSocketAddress();
1745 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1746 if (status != OK) {
1747 return AssertionFailure()
1748 << "setupUnixDomainServer: " << statusToString(status);
1749 }
1750 mConnectToServer = [addr] {
1751 return connectTo(UnixSocketAddress(addr.c_str()));
1752 };
1753 } break;
1754 case SocketType::VSOCK: {
1755 auto port = allocateVsockPort();
1756 auto status = rpcServer->setupVsockServer(port);
1757 if (status != OK) {
1758 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1759 }
1760 mConnectToServer = [port] {
1761 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1762 };
1763 } break;
1764 case SocketType::INET: {
1765 unsigned int port;
1766 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1767 if (status != OK) {
1768 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1769 }
1770 mConnectToServer = [port] {
1771 const char* addr = kLocalInetAddress;
1772 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1773 if (aiStart == nullptr) return base::unique_fd{};
1774 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1775 auto fd = connectTo(
1776 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1777 if (fd.ok()) return fd;
1778 }
1779 ALOGE("None of the socket address resolved for %s:%u can be connected",
1780 addr, port);
1781 return base::unique_fd{};
1782 };
1783 }
1784 }
1785 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001786 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001787 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001788 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1789 mSetup = true;
1790 return AssertionSuccess();
1791 }
1792 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1793 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1794 return mCertVerifier;
1795 }
1796 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1797 void start() {
1798 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1799 mThread = std::make_unique<std::thread>(&Server::run, this);
1800 }
1801 void run() {
1802 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1803
1804 std::vector<std::thread> threads;
1805 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1806 base::unique_fd acceptedFd(
Pawan49d74cb2022-08-03 21:19:11 +00001807 TEMP_FAILURE_RETRY(accept4(mFd.fd.get(), nullptr, nullptr /*length*/,
Yifan Hong1deca4b2021-09-10 16:16:44 -07001808 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1809 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1810 }
1811
1812 for (auto& thread : threads) thread.join();
1813 }
1814 void handleOne(android::base::unique_fd acceptedFd) {
1815 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001816 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001817 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001818 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001819 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001820 }
Yifan Honge07d2732021-09-13 21:59:14 -07001821 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001822 shutdown();
1823 join();
1824 }
1825 void shutdown() { mFdTrigger->trigger(); }
1826
1827 void setPostConnect(
1828 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1829 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001830 }
1831
1832 private:
1833 std::unique_ptr<std::thread> mThread;
1834 ConnectToServer mConnectToServer;
1835 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
Pawan3e0061c2022-08-26 21:08:34 +00001836 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001837 std::unique_ptr<RpcTransportCtx> mCtx;
1838 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1839 std::make_shared<RpcCertificateVerifierSimple>();
1840 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001841 // The function invoked after connection and handshake. By default, it is
1842 // |defaultPostConnect| that sends |kMessage| to the client.
1843 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1844 Server::defaultPostConnect;
1845
1846 void join() {
1847 if (mThread != nullptr) {
1848 mThread->join();
1849 mThread = nullptr;
1850 }
1851 }
1852
1853 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1854 FdTrigger* fdTrigger) {
1855 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001856 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001857 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001858 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001859 if (status != OK) return AssertionFailure() << statusToString(status);
1860 return AssertionSuccess();
1861 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001862 };
1863
1864 class Client {
1865 public:
1866 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1867 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001868 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001869 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1870 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001871 mFdTrigger = FdTrigger::make();
1872 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1873 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1874 return AssertionSuccess();
1875 }
1876 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1877 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1878 return mCertVerifier;
1879 }
Yifan Hong67519322021-09-13 18:51:16 -07001880 // connect() and do handshake
1881 bool setUpTransport() {
1882 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001883 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001884 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1885 return mClientTransport != nullptr;
1886 }
1887 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1888 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1889 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001890 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001891 status_t readStatus =
1892 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001893 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001894 if (readStatus != OK) {
1895 return AssertionFailure() << statusToString(readStatus);
1896 }
1897 if (readMessage != expectedMessage) {
1898 return AssertionFailure()
1899 << "Expected " << expectedMessage << ", actual " << readMessage;
1900 }
1901 return AssertionSuccess();
1902 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001903 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001904 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001905 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1906 return;
1907 }
1908 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001909 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001910 }
1911
Pawan49d74cb2022-08-03 21:19:11 +00001912 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1913
Yifan Hong1deca4b2021-09-10 16:16:44 -07001914 private:
1915 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001916 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001917 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1918 std::unique_ptr<RpcTransportCtx> mCtx;
1919 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1920 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001921 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001922 };
1923
1924 // Make A trust B.
1925 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001926 static status_t trust(RpcSecurity rpcSecurity,
1927 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1928 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001929 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001930 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1931 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1932 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001933 }
1934
1935 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001936};
1937
1938class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1939public:
1940 using Server = RpcTransportTestUtils::Server;
1941 using Client = RpcTransportTestUtils::Client;
1942 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001943 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001944 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1945 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001946 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001947 return ret;
1948 }
1949 static std::vector<ParamType> getRpcTranportTestParams() {
1950 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001951 for (auto serverVersion : testVersions()) {
1952 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1953 for (auto rpcSecurity : RpcSecurityValues()) {
1954 switch (rpcSecurity) {
1955 case RpcSecurity::RAW: {
1956 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1957 } break;
1958 case RpcSecurity::TLS: {
1959 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1960 serverVersion);
1961 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1962 serverVersion);
1963 } break;
1964 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001965 }
1966 }
1967 }
1968 return ret;
1969 }
1970 template <typename A, typename B>
1971 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001972 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1973 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001974 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1975 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001976 void SetUp() override {
1977 if constexpr (!kEnableRpcThreads) {
1978 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1979 }
1980 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001981};
1982
1983TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001984 auto server = std::make_unique<Server>();
1985 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001986
1987 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001988 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001989
1990 ASSERT_EQ(OK, trust(&client, server));
1991 ASSERT_EQ(OK, trust(server, &client));
1992
1993 server->start();
1994 client.run();
1995}
1996
1997TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001998 auto server = std::make_unique<Server>();
1999 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002000
2001 std::vector<Client> clients;
2002 for (int i = 0; i < 2; i++) {
2003 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002004 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002005 ASSERT_EQ(OK, trust(&client, server));
2006 ASSERT_EQ(OK, trust(server, &client));
2007 }
2008
2009 server->start();
2010 for (auto& client : clients) client.run();
2011}
2012
2013TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002014 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2015 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002016
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002017 auto untrustedServer = std::make_unique<Server>();
2018 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002019
2020 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002021 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002022
2023 ASSERT_EQ(OK, trust(untrustedServer, &client));
2024
2025 untrustedServer->start();
2026
2027 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2028 // the client can't verify the server's identity.
2029 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2030 client.run(handshakeOk);
2031}
2032TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002033 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2034 (void)serverVersion;
2035
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002036 auto validServer = std::make_unique<Server>();
2037 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002038
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002039 auto maliciousServer = std::make_unique<Server>();
2040 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002041
2042 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002043 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002044
2045 ASSERT_EQ(OK, trust(&client, validServer));
2046 ASSERT_EQ(OK, trust(validServer, &client));
2047 ASSERT_EQ(OK, trust(maliciousServer, &client));
2048
2049 maliciousServer->start();
2050
2051 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2052 // the client can't verify the server's identity.
2053 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2054 client.run(handshakeOk);
2055}
2056
2057TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002058 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2059 (void)serverVersion;
2060
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002061 auto server = std::make_unique<Server>();
2062 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002063
2064 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002065 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002066
2067 ASSERT_EQ(OK, trust(&client, server));
2068
2069 server->start();
2070
2071 // For TLS, Client should be able to verify server's identity, so client should see
2072 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2073 // identity and should drop the connection, so client shouldn't be able to read anything.
2074 bool readOk = rpcSecurity != RpcSecurity::TLS;
2075 client.run(true, readOk);
2076}
2077
2078TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002079 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2080 (void)serverVersion;
2081
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002082 auto server = std::make_unique<Server>();
2083 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002084
2085 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002086 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002087 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002088 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002089
2090 ASSERT_EQ(OK, trust(&validClient, server));
2091 ASSERT_EQ(OK, trust(&maliciousClient, server));
2092
2093 server->start();
2094
2095 // See UntrustedClient.
2096 bool readOk = rpcSecurity != RpcSecurity::TLS;
2097 maliciousClient.run(true, readOk);
2098}
2099
Yifan Hong67519322021-09-13 18:51:16 -07002100TEST_P(RpcTransportTest, Trigger) {
2101 std::string msg2 = ", world!";
2102 std::mutex writeMutex;
2103 std::condition_variable writeCv;
2104 bool shouldContinueWriting = false;
2105 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002106 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002107 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002108 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2109 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002110 if (status != OK) return AssertionFailure() << statusToString(status);
2111
2112 {
2113 std::unique_lock<std::mutex> lock(writeMutex);
2114 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2115 return AssertionFailure() << "write barrier not cleared in time!";
2116 }
2117 }
2118
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002119 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002120 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2121 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002122 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002123 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002124 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002125 << statusToString(status);
2126 return AssertionSuccess();
2127 };
2128
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002129 auto server = std::make_unique<Server>();
2130 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002131
2132 // Set up client
2133 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002134 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002135
2136 // Exchange keys
2137 ASSERT_EQ(OK, trust(&client, server));
2138 ASSERT_EQ(OK, trust(server, &client));
2139
2140 server->setPostConnect(serverPostConnect);
2141
Yifan Hong67519322021-09-13 18:51:16 -07002142 server->start();
2143 // connect() to server and do handshake
2144 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002145 // read the first message. This ensures that server has finished handshake and start handling
2146 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002147 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002148 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2149 // write is on an FdTrigger that has been shut down.
2150 server->shutdown();
2151 // Continues server thread to write the second message.
2152 {
Yifan Hong22211f82021-09-14 12:32:25 -07002153 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002154 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002155 }
Yifan Hong22211f82021-09-14 12:32:25 -07002156 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002157 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002158 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002159 // On the client side, second read fails with DEAD_OBJECT
2160 ASSERT_FALSE(client.readMessage(msg2));
2161}
2162
Pawan49d74cb2022-08-03 21:19:11 +00002163TEST_P(RpcTransportTest, CheckWaitingForRead) {
2164 std::mutex readMutex;
2165 std::condition_variable readCv;
2166 bool shouldContinueReading = false;
2167 // Server will write data on transport once its started
2168 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
2169 std::string message(RpcTransportTestUtils::kMessage);
2170 iovec messageIov{message.data(), message.size()};
2171 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2172 std::nullopt, nullptr);
2173 if (status != OK) return AssertionFailure() << statusToString(status);
2174
2175 {
2176 std::unique_lock<std::mutex> lock(readMutex);
2177 shouldContinueReading = true;
2178 lock.unlock();
2179 readCv.notify_all();
2180 }
2181 return AssertionSuccess();
2182 };
2183
2184 // Setup Server and client
2185 auto server = std::make_unique<Server>();
2186 ASSERT_TRUE(server->setUp(GetParam()));
2187
2188 Client client(server->getConnectToServerFn());
2189 ASSERT_TRUE(client.setUp(GetParam()));
2190
2191 ASSERT_EQ(OK, trust(&client, server));
2192 ASSERT_EQ(OK, trust(server, &client));
2193 server->setPostConnect(serverPostConnect);
2194
2195 server->start();
2196 ASSERT_TRUE(client.setUpTransport());
2197 {
2198 // Wait till server writes data
2199 std::unique_lock<std::mutex> lock(readMutex);
2200 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2201 }
2202
2203 // Since there is no read polling here, we will get polling count 0
2204 ASSERT_FALSE(client.isTransportWaiting());
2205 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2206 // Thread should increment polling count, read and decrement polling count
2207 // Again, polling count should be zero here
2208 ASSERT_FALSE(client.isTransportWaiting());
2209
2210 server->shutdown();
2211}
2212
Yifan Hong1deca4b2021-09-10 16:16:44 -07002213INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002214 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002215 RpcTransportTest::PrintParamInfo);
2216
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002217class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002218 : public testing::TestWithParam<
2219 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002220public:
2221 template <typename A, typename B>
2222 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002223 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2224 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002225 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2226 }
2227 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002228 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2229 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2230 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002231 };
2232};
2233
2234TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002235 if constexpr (!kEnableRpcThreads) {
2236 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2237 }
2238
Frederick Mayledc07cf82022-05-26 20:30:12 +00002239 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002240
2241 std::vector<uint8_t> pkeyData, certData;
2242 {
2243 auto pkey = makeKeyPairForSelfSignedCert();
2244 ASSERT_NE(nullptr, pkey);
2245 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2246 ASSERT_NE(nullptr, cert);
2247 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2248 certData = serializeCertificate(cert.get(), certificateFormat);
2249 }
2250
2251 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2252 auto desCert = deserializeCertificate(certData, certificateFormat);
2253 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002254 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2255 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002256
2257 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2258 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2259
2260 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2261 ASSERT_TRUE(client.setUp(utilsParam));
2262
2263 ASSERT_EQ(OK, trust(&client, server));
2264 ASSERT_EQ(OK, trust(server, &client));
2265
2266 server->start();
2267 client.run();
2268}
2269
2270INSTANTIATE_TEST_CASE_P(
2271 BinderRpc, RpcTransportTlsKeyTest,
2272 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2273 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002274 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2275 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002276 RpcTransportTlsKeyTest::PrintParamInfo);
2277
Steven Morelandc1635952021-04-01 16:20:47 +00002278} // namespace android
2279
2280int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002281 ::testing::InitGoogleTest(&argc, argv);
2282 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002283
Steven Moreland5553ac42020-11-11 02:14:45 +00002284 return RUN_ALL_TESTS();
2285}