blob: 652da991a436946945ec8ad5a51eb0e393b33a32 [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
Steven Morelandab8aa472022-10-04 00:40:40 +0000184 sp<RpcSession> strongSession = weakSession.promote();
185 EXPECT_EQ(nullptr, strongSession)
Steven Morelanddb95d572022-10-01 01:02:47 +0000186 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()), "Leaked sess: ")
Steven Morelandab8aa472022-10-04 00:40:40 +0000187 << strongSession->getStrongCount();
Steven Moreland736664b2021-05-01 04:27:25 +0000188 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000189 }
190};
191
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000192// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000193// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000194struct BinderRpcTestProcessSession {
195 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000196
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000197 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000198 sp<IBinder> rootBinder;
199
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000200 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000201 sp<IBinderRpcTest> rootIface;
202
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000203 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000204 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000205
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000206 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
207 ~BinderRpcTestProcessSession() {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000208 if (!expectAlreadyShutdown) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000209 EXPECT_NE(nullptr, rootIface);
210 if (rootIface == nullptr) return;
211
Steven Moreland736664b2021-05-01 04:27:25 +0000212 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000213 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000214 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000215 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000216 for (auto remoteCount : remoteCounts) {
217 EXPECT_EQ(remoteCount, 1);
218 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000219
Steven Moreland798e0d12021-07-14 23:19:25 +0000220 // even though it is on another thread, shutdown races with
221 // the transaction reply being written
222 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
223 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
224 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000225 }
226
227 rootIface = nullptr;
228 rootBinder = nullptr;
229 }
230};
231
Yifan Hong1deca4b2021-09-10 16:16:44 -0700232static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700233 base::unique_fd serverFd(
234 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
235 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700236 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
237 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700238
239 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
240 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700241 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
242 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700243 }
244 return serverFd;
245}
246
Andrei Homescu2a298012022-06-15 01:08:54 +0000247using RunServiceFn = void (*)(android::base::borrowed_fd writeEnd,
248 android::base::borrowed_fd readEnd);
249
250class BinderRpc : public ::testing::TestWithParam<
251 std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t, bool, bool>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000252public:
Frederick Mayle69a0c992022-05-26 20:38:39 +0000253 SocketType socketType() const { return std::get<0>(GetParam()); }
254 RpcSecurity rpcSecurity() const { return std::get<1>(GetParam()); }
255 uint32_t clientVersion() const { return std::get<2>(GetParam()); }
256 uint32_t serverVersion() const { return std::get<3>(GetParam()); }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000257 bool serverSingleThreaded() const { return std::get<4>(GetParam()); }
Andrei Homescu2a298012022-06-15 01:08:54 +0000258 bool noKernel() const { return std::get<5>(GetParam()); }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000259
Andrei Homescua858b0e2022-08-01 23:43:09 +0000260 bool clientOrServerSingleThreaded() const {
261 return !kEnableRpcThreads || serverSingleThreaded();
262 }
263
Frederick Mayle69a0c992022-05-26 20:38:39 +0000264 // Whether the test params support sending FDs in parcels.
265 bool supportsFdTransport() const {
266 return clientVersion() >= 1 && serverVersion() >= 1 && rpcSecurity() != RpcSecurity::TLS &&
267 (socketType() == SocketType::PRECONNECTED || socketType() == SocketType::UNIX);
268 }
269
Yifan Hong702115c2021-06-24 15:39:18 -0700270 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000271 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
272 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
Frederick Mayledc07cf82022-05-26 20:30:12 +0000273 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Andrei Homescu2a298012022-06-15 01:08:54 +0000274 if (singleThreaded) {
275 ret += "_single_threaded";
276 }
277 if (noKernel) {
278 ret += "_no_kernel";
279 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700280 return ret;
281 }
282
Steven Morelandc1635952021-04-01 16:20:47 +0000283 // This creates a new process serving an interface on a certain number of
284 // threads.
Andrei Homescu2a298012022-06-15 01:08:54 +0000285 ProcessSession createRpcTestSocketServerProcessEtc(const BinderRpcOptions& options) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000286 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000287
Yifan Hong702115c2021-06-24 15:39:18 -0700288 SocketType socketType = std::get<0>(GetParam());
289 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000290 uint32_t clientVersion = std::get<2>(GetParam());
291 uint32_t serverVersion = std::get<3>(GetParam());
Andrei Homescu2a298012022-06-15 01:08:54 +0000292 bool singleThreaded = std::get<4>(GetParam());
293 bool noKernel = std::get<5>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000294
Andrei Homescu2a298012022-06-15 01:08:54 +0000295 std::string path = android::base::GetExecutableDirectory();
296 auto servicePath =
297 android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
298 singleThreaded ? "_single_threaded" : "",
299 noKernel ? "_no_kernel" : "");
Steven Morelandc1635952021-04-01 16:20:47 +0000300
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000301 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000302 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700303 android::base::borrowed_fd readEnd) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000304 auto writeFd = std::to_string(writeEnd.get());
305 auto readFd = std::to_string(readEnd.get());
306 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
307 NULL);
Steven Morelandc1635952021-04-01 16:20:47 +0000308 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000309 };
310
Andrei Homescu2a298012022-06-15 01:08:54 +0000311 BinderRpcTestServerConfig serverConfig;
312 serverConfig.numThreads = options.numThreads;
313 serverConfig.socketType = static_cast<int32_t>(socketType);
314 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
315 serverConfig.serverVersion = serverVersion;
316 serverConfig.vsockPort = allocateVsockPort();
317 serverConfig.addr = allocateSocketAddress();
318 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
319 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
320 static_cast<int32_t>(mode));
321 }
322 writeToFd(ret.host.writeEnd(), serverConfig);
323
Yifan Hong1deca4b2021-09-10 16:16:44 -0700324 std::vector<sp<RpcSession>> sessions;
325 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
326 for (size_t i = 0; i < options.numSessions; i++) {
327 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
328 }
329
330 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
331 BinderRpcTestClientInfo clientInfo;
332 for (const auto& session : sessions) {
333 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700334 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700335 }
336 writeToFd(ret.host.writeEnd(), clientInfo);
337
338 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700339 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700340 CHECK_NE(0, serverInfo.port);
341 }
342
343 if (rpcSecurity == RpcSecurity::TLS) {
344 const auto& serverCert = serverInfo.cert.data;
345 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700346 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
347 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700348 }
349
Steven Moreland2372f9d2021-08-05 15:42:01 -0700350 status_t status;
351
Yifan Hong1deca4b2021-09-10 16:16:44 -0700352 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000353 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700354 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700355 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000356 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Moreland659416d2021-05-11 00:47:50 +0000357
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000358 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700359 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700360 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000361 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700362 });
Steven Moreland4198a122021-08-03 17:37:58 -0700363 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000364 case SocketType::UNIX:
Andrei Homescu2a298012022-06-15 01:08:54 +0000365 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000366 break;
367 case SocketType::VSOCK:
Andrei Homescu2a298012022-06-15 01:08:54 +0000368 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000369 break;
370 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700371 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000372 break;
373 default:
374 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000375 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000376 if (options.allowConnectFailure && status != OK) {
377 ret.sessions.clear();
378 break;
379 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700380 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000381 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000382 }
Steven Morelandc1635952021-04-01 16:20:47 +0000383 return ret;
384 }
385
Andrei Homescu2a298012022-06-15 01:08:54 +0000386 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const BinderRpcOptions& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000387 BinderRpcTestProcessSession ret{
Andrei Homescu2a298012022-06-15 01:08:54 +0000388 .proc = createRpcTestSocketServerProcessEtc(options),
Steven Morelandc1635952021-04-01 16:20:47 +0000389 };
390
Frederick Mayle69a0c992022-05-26 20:38:39 +0000391 ret.rootBinder = ret.proc.sessions.empty() ? nullptr : ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000392 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
393
394 return ret;
395 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700396
397 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
398 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000399};
400
Steven Morelandc1635952021-04-01 16:20:47 +0000401TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000402 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000403 ASSERT_NE(proc.rootBinder, nullptr);
404 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
405}
406
Steven Moreland4cf688f2021-03-31 01:48:58 +0000407TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000408 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000409 ASSERT_NE(proc.rootBinder, nullptr);
410 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
411}
412
Andrei Homescua858b0e2022-08-01 23:43:09 +0000413TEST_P(BinderRpc, MultipleSessions) {
414 if (serverSingleThreaded()) {
415 // Tests with multiple sessions require a multi-threaded service,
416 // but work fine on a single-threaded client
417 GTEST_SKIP() << "This test requires a multi-threaded service";
418 }
419
Steven Moreland4313d7e2021-07-15 23:41:22 +0000420 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000421 for (auto session : proc.proc.sessions) {
422 ASSERT_NE(nullptr, session.root);
423 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000424 }
425}
426
Andrei Homescua858b0e2022-08-01 23:43:09 +0000427TEST_P(BinderRpc, SeparateRootObject) {
428 if (serverSingleThreaded()) {
429 GTEST_SKIP() << "This test requires a multi-threaded service";
430 }
431
Steven Moreland51c44a92021-10-14 16:50:35 -0700432 SocketType type = std::get<0>(GetParam());
433 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
434 // we can't get port numbers for unix sockets
435 return;
436 }
437
438 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
439
440 int port1 = 0;
441 EXPECT_OK(proc.rootIface->getClientPort(&port1));
442
443 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
444 int port2;
445 EXPECT_OK(rootIface2->getClientPort(&port2));
446
447 // we should have a different IBinderRpcTest object created for each
448 // session, because we use setPerSessionRootObject
449 EXPECT_NE(port1, port2);
450}
451
Steven Morelandc1635952021-04-01 16:20:47 +0000452TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000453 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000454 Parcel data;
455 Parcel reply;
456 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
457}
458
Steven Moreland67753c32021-04-02 18:45:19 +0000459TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700460 auto proc1 = createRpcTestSocketServerProcess({});
461 auto proc2 = createRpcTestSocketServerProcess({});
462
463 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000464
465 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700466 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000467 p1.writeInt32(3);
468
Frederick Maylea4ed5672022-06-17 22:03:38 +0000469 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700470 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
471
Steven Moreland67753c32021-04-02 18:45:19 +0000472 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700473 p2.markForBinder(proc2.rootBinder);
474 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000475
476 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
477 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
478}
479
Steven Morelandc1635952021-04-01 16:20:47 +0000480TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000481 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000482 Parcel data;
483 data.markForBinder(proc.rootBinder);
484 Parcel reply;
485 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
486}
487
Steven Morelandc1635952021-04-01 16:20:47 +0000488TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000489 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000490 EXPECT_OK(proc.rootIface->sendString("asdf"));
491}
492
Steven Morelandc1635952021-04-01 16:20:47 +0000493TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000494 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000495 std::string doubled;
496 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
497 EXPECT_EQ("cool cool ", doubled);
498}
499
Steven Morelandc1635952021-04-01 16:20:47 +0000500TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000501 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000502 std::string single = std::string(1024, 'a');
503 std::string doubled;
504 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
505 EXPECT_EQ(single + single, doubled);
506}
507
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000508TEST_P(BinderRpc, InvalidNullBinderReturn) {
509 auto proc = createRpcTestSocketServerProcess({});
510
511 sp<IBinder> outBinder;
512 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
513}
514
Steven Morelandc1635952021-04-01 16:20:47 +0000515TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000516 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000517
518 int32_t pingResult;
519 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
520 EXPECT_EQ(OK, pingResult);
521
522 EXPECT_EQ(0, MyBinderRpcSession::gNum);
523}
524
Steven Morelandc1635952021-04-01 16:20:47 +0000525TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000526 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000527
528 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
529 sp<IBinder> outBinder;
530 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
531 EXPECT_EQ(inBinder, outBinder);
532
533 wp<IBinder> weak = inBinder;
534 inBinder = nullptr;
535 outBinder = nullptr;
536
537 // Force reading a reply, to process any pending dec refs from the other
538 // process (the other process will process dec refs there before processing
539 // the ping here).
540 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
541
542 EXPECT_EQ(nullptr, weak.promote());
543
544 EXPECT_EQ(0, MyBinderRpcSession::gNum);
545}
546
Steven Morelandc1635952021-04-01 16:20:47 +0000547TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000548 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000549
550 sp<IBinderRpcSession> session;
551 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
552
553 sp<IBinder> inBinder = IInterface::asBinder(session);
554 sp<IBinder> outBinder;
555 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
556 EXPECT_EQ(inBinder, outBinder);
557
558 wp<IBinder> weak = inBinder;
559 session = nullptr;
560 inBinder = nullptr;
561 outBinder = nullptr;
562
563 // Force reading a reply, to process any pending dec refs from the other
564 // process (the other process will process dec refs there before processing
565 // the ping here).
566 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
567
568 EXPECT_EQ(nullptr, weak.promote());
569}
570
Steven Morelandc1635952021-04-01 16:20:47 +0000571TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000572 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000573
574 sp<IBinder> outBinder;
575 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
576 EXPECT_EQ(nullptr, outBinder);
577}
578
Steven Morelandc1635952021-04-01 16:20:47 +0000579TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000580 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000581
582 IBinder* ptr = nullptr;
583 {
584 sp<IBinder> binder = new BBinder();
585 ptr = binder.get();
586 EXPECT_OK(proc.rootIface->holdBinder(binder));
587 }
588
589 sp<IBinder> held;
590 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
591
592 EXPECT_EQ(held.get(), ptr);
593
594 // stop holding binder, because we test to make sure references are cleaned
595 // up
596 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
597 // and flush ref counts
598 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
599}
600
601// START TESTS FOR LIMITATIONS OF SOCKET BINDER
602// These are behavioral differences form regular binder, where certain usecases
603// aren't supported.
604
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000605TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000606 auto proc1 = createRpcTestSocketServerProcess({});
607 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000608
609 sp<IBinder> outBinder;
610 EXPECT_EQ(INVALID_OPERATION,
611 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
612}
613
Andrei Homescua858b0e2022-08-01 23:43:09 +0000614TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
615 if (serverSingleThreaded()) {
616 GTEST_SKIP() << "This test requires a multi-threaded service";
617 }
618
Steven Moreland4313d7e2021-07-15 23:41:22 +0000619 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000620
621 sp<IBinder> outBinder;
622 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000623 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000624 .transactionError());
625}
626
Steven Morelandc1635952021-04-01 16:20:47 +0000627TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000628 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000629 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
630 "at build time.";
631 }
632
Steven Moreland4313d7e2021-07-15 23:41:22 +0000633 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000634
635 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
636 sp<IBinder> outBinder;
637 EXPECT_EQ(INVALID_OPERATION,
638 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
639}
640
Steven Morelandc1635952021-04-01 16:20:47 +0000641TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000642 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000643 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
644 "at build time.";
645 }
646
Steven Moreland4313d7e2021-07-15 23:41:22 +0000647 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000648
649 // for historical reasons, IServiceManager interface only returns the
650 // exception code
651 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
652 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
653}
654
655// END TESTS FOR LIMITATIONS OF SOCKET BINDER
656
Steven Morelandc1635952021-04-01 16:20:47 +0000657TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000658 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000659
660 sp<IBinder> outBinder;
661 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
662 EXPECT_EQ(proc.rootBinder, outBinder);
663}
664
Steven Morelandc1635952021-04-01 16:20:47 +0000665TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000666 auto proc = createRpcTestSocketServerProcess({
667 // Enable FD support because it uses more stack space and so represents
668 // something closer to a worst case scenario.
669 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
670 .serverSupportedFileDescriptorTransportModes =
671 {RpcSession::FileDescriptorTransportMode::UNIX},
672 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000673
674 auto nastyNester = sp<MyBinderRpcTest>::make();
675 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
676
677 wp<IBinder> weak = nastyNester;
678 nastyNester = nullptr;
679 EXPECT_EQ(nullptr, weak.promote());
680}
681
Steven Morelandc1635952021-04-01 16:20:47 +0000682TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000683 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000684
685 sp<IBinder> a;
686 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
687
688 sp<IBinder> b;
689 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
690
691 EXPECT_EQ(a, b);
692}
693
Steven Morelandc1635952021-04-01 16:20:47 +0000694TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000695 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000696
697 sp<IBinder> a;
698 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
699 wp<IBinder> weak = a;
700 a = nullptr;
701
702 sp<IBinder> b;
703 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
704
705 // this is the wrong behavior, since BpBinder
706 // doesn't implement onIncStrongAttempted
707 // but make sure there is no crash
708 EXPECT_EQ(nullptr, weak.promote());
709
710 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
711
712 // In order to fix this:
713 // - need to have incStrongAttempted reflected across IPC boundary (wait for
714 // response to promote - round trip...)
715 // - sendOnLastWeakRef, to delete entries out of RpcState table
716 EXPECT_EQ(b, weak.promote());
717}
718
719#define expectSessions(expected, iface) \
720 do { \
721 int session; \
722 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
723 EXPECT_EQ(expected, session); \
724 } while (false)
725
Steven Morelandc1635952021-04-01 16:20:47 +0000726TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000727 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000728
729 sp<IBinderRpcSession> session;
730 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
731 std::string out;
732 EXPECT_OK(session->getName(&out));
733 EXPECT_EQ("aoeu", out);
734
735 expectSessions(1, proc.rootIface);
736 session = nullptr;
737 expectSessions(0, proc.rootIface);
738}
739
Steven Morelandc1635952021-04-01 16:20:47 +0000740TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000741 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000742
743 std::vector<sp<IBinderRpcSession>> sessions;
744
745 for (size_t i = 0; i < 15; i++) {
746 expectSessions(i, proc.rootIface);
747 sp<IBinderRpcSession> session;
748 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
749 sessions.push_back(session);
750 }
751 expectSessions(sessions.size(), proc.rootIface);
752 for (size_t i = 0; i < sessions.size(); i++) {
753 std::string out;
754 EXPECT_OK(sessions.at(i)->getName(&out));
755 EXPECT_EQ(std::to_string(i), out);
756 }
757 expectSessions(sessions.size(), proc.rootIface);
758
759 while (!sessions.empty()) {
760 sessions.pop_back();
761 expectSessions(sessions.size(), proc.rootIface);
762 }
763 expectSessions(0, proc.rootIface);
764}
765
766size_t epochMillis() {
767 using std::chrono::duration_cast;
768 using std::chrono::milliseconds;
769 using std::chrono::seconds;
770 using std::chrono::system_clock;
771 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
772}
773
Andrei Homescua858b0e2022-08-01 23:43:09 +0000774TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
775 if (clientOrServerSingleThreaded()) {
776 GTEST_SKIP() << "This test requires multiple threads";
777 }
778
Steven Moreland5553ac42020-11-11 02:14:45 +0000779 constexpr size_t kNumThreads = 10;
780
Steven Moreland4313d7e2021-07-15 23:41:22 +0000781 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000782
783 EXPECT_OK(proc.rootIface->lock());
784
785 // block all but one thread taking locks
786 std::vector<std::thread> ts;
787 for (size_t i = 0; i < kNumThreads - 1; i++) {
788 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
789 }
790
791 usleep(100000); // give chance for calls on other threads
792
793 // other calls still work
794 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
795
796 constexpr size_t blockTimeMs = 500;
797 size_t epochMsBefore = epochMillis();
798 // after this, we should never see a response within this time
799 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
800
801 // this call should be blocked for blockTimeMs
802 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
803
804 size_t epochMsAfter = epochMillis();
805 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
806
807 for (auto& t : ts) t.join();
808}
809
Yifan Hong1f44f982021-10-08 17:16:47 -0700810void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
811 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000812 size_t epochMsBefore = epochMillis();
813
814 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700815 for (size_t i = 0; i < numCalls; i++) {
816 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000817 }
818
819 for (auto& t : ts) t.join();
820
821 size_t epochMsAfter = epochMillis();
822
Yifan Hong1f44f982021-10-08 17:16:47 -0700823 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000824
825 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700826 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
827}
828
Andrei Homescua858b0e2022-08-01 23:43:09 +0000829TEST_P(BinderRpc, ThreadPoolOverSaturated) {
830 if (clientOrServerSingleThreaded()) {
831 GTEST_SKIP() << "This test requires multiple threads";
832 }
833
Yifan Hong1f44f982021-10-08 17:16:47 -0700834 constexpr size_t kNumThreads = 10;
835 constexpr size_t kNumCalls = kNumThreads + 3;
836 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
837 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
838}
839
Andrei Homescua858b0e2022-08-01 23:43:09 +0000840TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
841 if (clientOrServerSingleThreaded()) {
842 GTEST_SKIP() << "This test requires multiple threads";
843 }
844
Yifan Hong1f44f982021-10-08 17:16:47 -0700845 constexpr size_t kNumThreads = 20;
846 constexpr size_t kNumOutgoingConnections = 10;
847 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
848 auto proc = createRpcTestSocketServerProcess(
849 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
850 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000851}
852
Andrei Homescua858b0e2022-08-01 23:43:09 +0000853TEST_P(BinderRpc, ThreadingStressTest) {
854 if (clientOrServerSingleThreaded()) {
855 GTEST_SKIP() << "This test requires multiple threads";
856 }
857
Steven Moreland5553ac42020-11-11 02:14:45 +0000858 constexpr size_t kNumClientThreads = 10;
859 constexpr size_t kNumServerThreads = 10;
860 constexpr size_t kNumCalls = 100;
861
Steven Moreland4313d7e2021-07-15 23:41:22 +0000862 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000863
864 std::vector<std::thread> threads;
865 for (size_t i = 0; i < kNumClientThreads; i++) {
866 threads.push_back(std::thread([&] {
867 for (size_t j = 0; j < kNumCalls; j++) {
868 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000869 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000870 EXPECT_EQ(proc.rootBinder, out);
871 }
872 }));
873 }
874
875 for (auto& t : threads) t.join();
876}
877
Steven Moreland925ba0a2021-09-17 18:06:32 -0700878static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
879 std::vector<std::thread> threads;
880 for (size_t i = 0; i < threadCount; i++) {
881 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
882 }
883 for (auto& t : threads) t.join();
884}
885
Andrei Homescua858b0e2022-08-01 23:43:09 +0000886TEST_P(BinderRpc, OnewayStressTest) {
887 if (clientOrServerSingleThreaded()) {
888 GTEST_SKIP() << "This test requires multiple threads";
889 }
890
Steven Morelandc6046982021-04-20 00:49:42 +0000891 constexpr size_t kNumClientThreads = 10;
892 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700893 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000894
Steven Moreland4313d7e2021-07-15 23:41:22 +0000895 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000896
897 std::vector<std::thread> threads;
898 for (size_t i = 0; i < kNumClientThreads; i++) {
899 threads.push_back(std::thread([&] {
900 for (size_t j = 0; j < kNumCalls; j++) {
901 EXPECT_OK(proc.rootIface->sendString("a"));
902 }
Steven Morelandc6046982021-04-20 00:49:42 +0000903 }));
904 }
905
906 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700907
908 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000909}
910
Steven Morelandc1635952021-04-01 16:20:47 +0000911TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000912 constexpr size_t kReallyLongTimeMs = 100;
913 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
914
Steven Moreland4313d7e2021-07-15 23:41:22 +0000915 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000916
917 size_t epochMsBefore = epochMillis();
918
919 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
920
921 size_t epochMsAfter = epochMillis();
922 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
923}
924
Andrei Homescua858b0e2022-08-01 23:43:09 +0000925TEST_P(BinderRpc, OnewayCallQueueing) {
926 if (clientOrServerSingleThreaded()) {
927 GTEST_SKIP() << "This test requires multiple threads";
928 }
929
Steven Moreland5553ac42020-11-11 02:14:45 +0000930 constexpr size_t kNumSleeps = 10;
931 constexpr size_t kNumExtraServerThreads = 4;
932 constexpr size_t kSleepMs = 50;
933
934 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000935 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000936
937 EXPECT_OK(proc.rootIface->lock());
938
Steven Moreland1c678802021-09-17 16:48:47 -0700939 size_t epochMsBefore = epochMillis();
940
941 // all these *Async commands should be queued on the server sequentially,
942 // even though there are multiple threads.
943 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000944 proc.rootIface->sleepMsAsync(kSleepMs);
945 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000946 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
947
Steven Moreland1c678802021-09-17 16:48:47 -0700948 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000949 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700950
Steven Moreland5553ac42020-11-11 02:14:45 +0000951 size_t epochMsAfter = epochMillis();
952
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000953 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000954
Steven Moreland925ba0a2021-09-17 18:06:32 -0700955 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000956}
957
Andrei Homescua858b0e2022-08-01 23:43:09 +0000958TEST_P(BinderRpc, OnewayCallExhaustion) {
959 if (clientOrServerSingleThreaded()) {
960 GTEST_SKIP() << "This test requires multiple threads";
961 }
962
Steven Morelandd45be622021-06-04 02:19:37 +0000963 constexpr size_t kNumClients = 2;
964 constexpr size_t kTooLongMs = 1000;
965
Steven Moreland4313d7e2021-07-15 23:41:22 +0000966 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000967
968 // Build up oneway calls on the second session to make sure it terminates
969 // and shuts down. The first session should be unaffected (proc destructor
970 // checks the first session).
971 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
972
973 std::vector<std::thread> threads;
974 for (size_t i = 0; i < kNumClients; i++) {
975 // one of these threads will get stuck queueing a transaction once the
976 // socket fills up, the other will be able to fill up transactions on
977 // this object
978 threads.push_back(std::thread([&] {
979 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
980 }
981 }));
982 }
983 for (auto& t : threads) t.join();
984
985 Status status = iface->sleepMsAsync(kTooLongMs);
986 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
987
Steven Moreland798e0d12021-07-14 23:19:25 +0000988 // now that it has died, wait for the remote session to shutdown
989 std::vector<int32_t> remoteCounts;
990 do {
991 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
992 } while (remoteCounts.size() == kNumClients);
993
Steven Morelandd45be622021-06-04 02:19:37 +0000994 // the second session should be shutdown in the other process by the time we
995 // are able to join above (it'll only be hung up once it finishes processing
996 // any pending commands). We need to erase this session from the record
997 // here, so that the destructor for our session won't check that this
998 // session is valid, but we still want it to test the other session.
999 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1000}
1001
Steven Moreland659416d2021-05-11 00:47:50 +00001002TEST_P(BinderRpc, Callbacks) {
1003 const static std::string kTestString = "good afternoon!";
1004
Steven Morelandc7d40132021-06-10 03:42:11 +00001005 for (bool callIsOneway : {true, false}) {
1006 for (bool callbackIsOneway : {true, false}) {
1007 for (bool delayed : {true, false}) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001008 if (clientOrServerSingleThreaded() &&
1009 (callIsOneway || callbackIsOneway || delayed)) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001010 // we have no incoming connections to receive the callback
1011 continue;
1012 }
1013
Andrei Homescua858b0e2022-08-01 23:43:09 +00001014 size_t numIncomingConnections = clientOrServerSingleThreaded() ? 0 : 1;
Steven Moreland4313d7e2021-07-15 23:41:22 +00001015 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +00001016 {.numThreads = 1,
1017 .numSessions = 1,
Andrei Homescu2a298012022-06-15 01:08:54 +00001018 .numIncomingConnections = numIncomingConnections});
Steven Morelandc7d40132021-06-10 03:42:11 +00001019 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001020
Steven Morelandc7d40132021-06-10 03:42:11 +00001021 if (callIsOneway) {
1022 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1023 kTestString));
1024 } else {
1025 EXPECT_OK(
1026 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1027 }
Steven Moreland659416d2021-05-11 00:47:50 +00001028
Steven Moreland03ecce62022-05-13 23:22:05 +00001029 // if both transactions are synchronous and the response is sent back on the
1030 // same thread, everything should have happened in a nested call. Otherwise,
1031 // the callback will be processed on another thread.
1032 if (callIsOneway || callbackIsOneway || delayed) {
1033 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001034 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001035 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1036 }
Steven Moreland659416d2021-05-11 00:47:50 +00001037
Steven Morelandc7d40132021-06-10 03:42:11 +00001038 EXPECT_EQ(cb->mValues.size(), 1)
1039 << "callIsOneway: " << callIsOneway
1040 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1041 if (cb->mValues.empty()) continue;
1042 EXPECT_EQ(cb->mValues.at(0), kTestString)
1043 << "callIsOneway: " << callIsOneway
1044 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001045
Steven Morelandc7d40132021-06-10 03:42:11 +00001046 // since we are severing the connection, we need to go ahead and
1047 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001048 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1049 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1050 }
Steven Moreland659416d2021-05-11 00:47:50 +00001051
Steven Moreland1b304292021-07-15 22:59:34 +00001052 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001053 // need to manually shut it down
1054 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Morelandc7d40132021-06-10 03:42:11 +00001055 proc.expectAlreadyShutdown = true;
1056 }
Steven Moreland659416d2021-05-11 00:47:50 +00001057 }
1058 }
1059}
1060
Devin Moore66d5b7a2022-07-07 21:42:10 +00001061TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001062 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001063 GTEST_SKIP() << "This test requires multiple threads";
1064 }
1065 class MyDeathRec : public IBinder::DeathRecipient {
1066 public:
1067 void binderDied(const wp<IBinder>& /* who */) override {
1068 dead = true;
1069 mCv.notify_one();
1070 }
1071 std::mutex mMtx;
1072 std::condition_variable mCv;
1073 bool dead = false;
1074 };
1075
1076 // Death recipient needs to have an incoming connection to be called
1077 auto proc = createRpcTestSocketServerProcess(
1078 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1079
1080 auto dr = sp<MyDeathRec>::make();
1081 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1082
1083 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1084 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1085 }
1086
1087 std::unique_lock<std::mutex> lock(dr->mMtx);
Devin Moore47a12012022-08-19 21:16:17 +00001088 ASSERT_TRUE(dr->mCv.wait_for(lock, 1000ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001089
1090 // need to wait for the session to shutdown so we don't "Leak session"
1091 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1092 proc.expectAlreadyShutdown = true;
1093}
1094
1095TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001096 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001097 GTEST_SKIP() << "This test requires multiple threads";
1098 }
1099 class MyDeathRec : public IBinder::DeathRecipient {
1100 public:
1101 void binderDied(const wp<IBinder>& /* who */) override {
1102 dead = true;
1103 mCv.notify_one();
1104 }
1105 std::mutex mMtx;
1106 std::condition_variable mCv;
1107 bool dead = false;
1108 };
1109
1110 // Death recipient needs to have an incoming connection to be called
1111 auto proc = createRpcTestSocketServerProcess(
1112 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1113
1114 auto dr = sp<MyDeathRec>::make();
1115 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1116
1117 // Explicitly calling shutDownAndWait will cause the death recipients
1118 // to be called.
1119 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1120
1121 std::unique_lock<std::mutex> lock(dr->mMtx);
1122 if (!dr->dead) {
1123 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1124 }
1125 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1126
1127 proc.proc.host.terminate();
1128 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1129 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1130 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1131 });
1132 proc.expectAlreadyShutdown = true;
1133}
1134
1135TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1136 class MyDeathRec : public IBinder::DeathRecipient {
1137 public:
1138 void binderDied(const wp<IBinder>& /* who */) override {}
1139 };
1140
1141 auto proc = createRpcTestSocketServerProcess(
1142 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1143
1144 auto dr = sp<MyDeathRec>::make();
1145 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1146 "Cannot register a DeathRecipient without any incoming connections.");
1147}
1148
1149TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001150 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001151 GTEST_SKIP() << "This test requires multiple threads";
1152 }
1153 class MyDeathRec : public IBinder::DeathRecipient {
1154 public:
1155 void binderDied(const wp<IBinder>& /* who */) override {
1156 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1157 }
1158 };
1159
1160 // Death recipient needs to have an incoming connection to be called
1161 auto proc = createRpcTestSocketServerProcess(
1162 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1163
1164 auto dr = sp<MyDeathRec>::make();
1165 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1166 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1167
1168 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1169 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1170 }
1171
1172 // need to wait for the session to shutdown so we don't "Leak session"
1173 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1174 proc.expectAlreadyShutdown = true;
1175}
1176
Steven Moreland195edb82021-06-08 02:44:39 +00001177TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001178 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001179 auto cb = sp<MyBinderRpcCallback>::make();
1180
1181 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1182 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1183}
1184
Steven Morelandc1635952021-04-01 16:20:47 +00001185TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001186 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001187 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001188
1189 // make sure there is some state during crash
1190 // 1. we hold their binder
1191 sp<IBinderRpcSession> session;
1192 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1193 // 2. they hold our binder
1194 sp<IBinder> binder = new BBinder();
1195 EXPECT_OK(proc.rootIface->holdBinder(binder));
1196
1197 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1198 << "Do death cleanup: " << doDeathCleanup;
1199
Frederick Maylea12b0962022-06-25 01:13:22 +00001200 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1201 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1202 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1203 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001204 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001205 }
1206}
1207
Steven Morelandd7302072021-05-15 01:32:04 +00001208TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001209 // This test only works if the current process shared the internal state of
1210 // ProcessState with the service across the call to fork(). Both the static
1211 // libraries and libbinder.so have their own separate copies of all the
1212 // globals, so the test only works when the test client and service both use
1213 // libbinder.so (when using static libraries, even a client and service
1214 // using the same kind of static library should have separate copies of the
1215 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +00001216 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001217 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1218 "at build time.";
1219 }
1220
Steven Moreland4313d7e2021-07-15 23:41:22 +00001221 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001222
Andrei Homescu2a298012022-06-15 01:08:54 +00001223 // we can't allocate IPCThreadState so actually the first time should
1224 // succeed :(
1225 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001226
1227 // second time! we catch the error :)
1228 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1229
Frederick Maylea12b0962022-06-25 01:13:22 +00001230 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1231 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1232 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1233 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001234 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001235}
1236
Frederick Mayle69a0c992022-05-26 20:38:39 +00001237TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1238 auto proc = createRpcTestSocketServerProcess({
1239 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1240 .serverSupportedFileDescriptorTransportModes =
1241 {RpcSession::FileDescriptorTransportMode::UNIX},
1242 .allowConnectFailure = true,
1243 });
1244 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1245 proc.proc.host.terminate();
1246 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1247 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1248 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1249 });
1250 proc.expectAlreadyShutdown = true;
1251}
1252
1253TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1254 auto proc = createRpcTestSocketServerProcess({
1255 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1256 .serverSupportedFileDescriptorTransportModes =
1257 {RpcSession::FileDescriptorTransportMode::NONE},
1258 .allowConnectFailure = true,
1259 });
1260 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1261 proc.proc.host.terminate();
1262 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1263 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1264 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1265 });
1266 proc.expectAlreadyShutdown = true;
1267}
1268
1269TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1270 auto proc = createRpcTestSocketServerProcess({
1271 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1272 .serverSupportedFileDescriptorTransportModes =
1273 {RpcSession::FileDescriptorTransportMode::NONE,
1274 RpcSession::FileDescriptorTransportMode::UNIX},
1275 });
1276
1277 android::os::ParcelFileDescriptor out;
1278 auto status = proc.rootIface->echoAsFile("hello", &out);
1279 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1280}
1281
1282TEST_P(BinderRpc, ReceiveFile) {
1283 auto proc = createRpcTestSocketServerProcess({
1284 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1285 .serverSupportedFileDescriptorTransportModes =
1286 {RpcSession::FileDescriptorTransportMode::UNIX},
1287 });
1288
1289 android::os::ParcelFileDescriptor out;
1290 auto status = proc.rootIface->echoAsFile("hello", &out);
1291 if (!supportsFdTransport()) {
1292 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1293 return;
1294 }
1295 ASSERT_TRUE(status.isOk()) << status;
1296
1297 std::string result;
1298 CHECK(android::base::ReadFdToString(out.get(), &result));
1299 EXPECT_EQ(result, "hello");
1300}
1301
1302TEST_P(BinderRpc, SendFiles) {
1303 auto proc = createRpcTestSocketServerProcess({
1304 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1305 .serverSupportedFileDescriptorTransportModes =
1306 {RpcSession::FileDescriptorTransportMode::UNIX},
1307 });
1308
1309 std::vector<android::os::ParcelFileDescriptor> files;
1310 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1311 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1312 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1313 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1314
1315 android::os::ParcelFileDescriptor out;
1316 auto status = proc.rootIface->concatFiles(files, &out);
1317 if (!supportsFdTransport()) {
1318 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1319 return;
1320 }
1321 ASSERT_TRUE(status.isOk()) << status;
1322
1323 std::string result;
1324 CHECK(android::base::ReadFdToString(out.get(), &result));
1325 EXPECT_EQ(result, "123abcd");
1326}
1327
1328TEST_P(BinderRpc, SendMaxFiles) {
1329 if (!supportsFdTransport()) {
1330 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1331 }
1332
1333 auto proc = createRpcTestSocketServerProcess({
1334 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1335 .serverSupportedFileDescriptorTransportModes =
1336 {RpcSession::FileDescriptorTransportMode::UNIX},
1337 });
1338
1339 std::vector<android::os::ParcelFileDescriptor> files;
1340 for (int i = 0; i < 253; i++) {
1341 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1342 }
1343
1344 android::os::ParcelFileDescriptor out;
1345 auto status = proc.rootIface->concatFiles(files, &out);
1346 ASSERT_TRUE(status.isOk()) << status;
1347
1348 std::string result;
1349 CHECK(android::base::ReadFdToString(out.get(), &result));
1350 EXPECT_EQ(result, std::string(253, 'a'));
1351}
1352
1353TEST_P(BinderRpc, SendTooManyFiles) {
1354 if (!supportsFdTransport()) {
1355 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1356 }
1357
1358 auto proc = createRpcTestSocketServerProcess({
1359 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1360 .serverSupportedFileDescriptorTransportModes =
1361 {RpcSession::FileDescriptorTransportMode::UNIX},
1362 });
1363
1364 std::vector<android::os::ParcelFileDescriptor> files;
1365 for (int i = 0; i < 254; i++) {
1366 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1367 }
1368
1369 android::os::ParcelFileDescriptor out;
1370 auto status = proc.rootIface->concatFiles(files, &out);
1371 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1372}
1373
Steven Moreland37aff182021-03-26 02:04:16 +00001374TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001375 if constexpr (!kEnableSharedLibs) {
1376 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1377 }
1378
Steven Moreland4313d7e2021-07-15 23:41:22 +00001379 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001380
1381 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1382 ASSERT_NE(binder, nullptr);
1383
1384 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1385}
1386
1387TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001388 if constexpr (!kEnableSharedLibs) {
1389 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1390 }
1391
Steven Moreland4313d7e2021-07-15 23:41:22 +00001392 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001393
1394 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1395 ASSERT_NE(binder, nullptr);
1396
1397 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1398 ASSERT_NE(ndkBinder, nullptr);
1399
1400 std::string out;
1401 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1402 ASSERT_TRUE(status.isOk()) << status.getDescription();
1403 ASSERT_EQ("aoeuaoeu", out);
1404}
1405
Steven Moreland5553ac42020-11-11 02:14:45 +00001406ssize_t countFds() {
1407 DIR* dir = opendir("/proc/self/fd/");
1408 if (dir == nullptr) return -1;
1409 ssize_t ret = 0;
1410 dirent* ent;
1411 while ((ent = readdir(dir)) != nullptr) ret++;
1412 closedir(dir);
1413 return ret;
1414}
1415
Andrei Homescua858b0e2022-08-01 23:43:09 +00001416TEST_P(BinderRpc, Fds) {
1417 if (serverSingleThreaded()) {
1418 GTEST_SKIP() << "This test requires multiple threads";
1419 }
1420
Steven Moreland5553ac42020-11-11 02:14:45 +00001421 ssize_t beforeFds = countFds();
1422 ASSERT_GE(beforeFds, 0);
1423 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001424 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001425 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1426 }
1427 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1428}
1429
Devin Moore800b2252021-10-15 16:22:57 +00001430TEST_P(BinderRpc, AidlDelegatorTest) {
1431 auto proc = createRpcTestSocketServerProcess({});
1432 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1433 ASSERT_NE(nullptr, myDelegator);
1434
1435 std::string doubled;
1436 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1437 EXPECT_EQ("cool cool ", doubled);
1438}
1439
Steven Morelandda573042021-06-12 01:13:45 +00001440static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001441 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001442 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001443
Andrei Homescu992a4052022-06-28 21:26:18 +00001444 android::base::unique_fd serverFd(
1445 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1446 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1447
1448 sockaddr_vm serverAddr{
1449 .svm_family = AF_VSOCK,
1450 .svm_port = vsockPort,
1451 .svm_cid = VMADDR_CID_ANY,
1452 };
1453 int ret = TEMP_FAILURE_RETRY(
1454 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1455 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1456 strerror(errno));
1457
1458 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1459 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1460 strerror(errno));
1461
1462 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1463 // to see if the kernel supports it. It's safe to use a blocking
1464 // connect because vsock sockets have a 2 second connection timeout,
1465 // and they return ETIMEDOUT after that.
1466 android::base::unique_fd connectFd(
1467 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1468 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1469 strerror(errno));
1470
1471 bool success = false;
1472 sockaddr_vm connectAddr{
1473 .svm_family = AF_VSOCK,
1474 .svm_port = vsockPort,
1475 .svm_cid = VMADDR_CID_LOCAL,
1476 };
1477 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1478 sizeof(connectAddr)));
1479 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1480 android::base::unique_fd acceptFd;
1481 while (true) {
1482 pollfd pfd[]{
1483 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1484 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1485 };
1486 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1487 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1488
1489 if (pfd[0].revents & POLLIN) {
1490 sockaddr_vm acceptAddr;
1491 socklen_t acceptAddrLen = sizeof(acceptAddr);
1492 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1493 reinterpret_cast<sockaddr*>(&acceptAddr),
1494 &acceptAddrLen, SOCK_CLOEXEC));
1495 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1496 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1497 "Truncated address");
1498
1499 // Store the fd in acceptFd so we keep the connection alive
1500 // while polling connectFd
1501 acceptFd.reset(ret);
1502 }
1503
1504 if (pfd[1].revents & POLLOUT) {
1505 // Connect either succeeded or timed out
1506 int connectErrno;
1507 socklen_t connectErrnoLen = sizeof(connectErrno);
1508 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1509 &connectErrnoLen);
1510 LOG_ALWAYS_FATAL_IF(ret == -1,
1511 "Could not getsockopt() after connect() "
1512 "on non-blocking socket: %s.",
1513 strerror(errno));
1514
1515 // We're done, this is all we wanted
1516 success = connectErrno == 0;
1517 break;
1518 }
1519 }
1520 } else {
1521 success = ret == 0;
1522 }
1523
1524 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1525
1526 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001527}
1528
Yifan Hong1deca4b2021-09-10 16:16:44 -07001529static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1530 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1531
1532 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001533
1534 static bool hasVsockLoopback = testSupportVsockLoopback();
1535
1536 if (hasVsockLoopback) {
1537 ret.push_back(SocketType::VSOCK);
1538 }
1539
1540 return ret;
1541}
1542
Frederick Mayledc07cf82022-05-26 20:30:12 +00001543static std::vector<uint32_t> testVersions() {
1544 std::vector<uint32_t> versions;
1545 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1546 versions.push_back(i);
1547 }
1548 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1549 return versions;
1550}
1551
Yifan Hong702115c2021-06-24 15:39:18 -07001552INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1553 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001554 ::testing::ValuesIn(RpcSecurityValues()),
1555 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001556 ::testing::ValuesIn(testVersions()),
1557 ::testing::Values(false, true),
1558 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001559 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001560
Yifan Hong702115c2021-06-24 15:39:18 -07001561class BinderRpcServerRootObject
1562 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001563
1564TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1565 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1566 auto setRootObject = [](bool isStrong) -> SetFn {
1567 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1568 };
1569
Yifan Hong702115c2021-06-24 15:39:18 -07001570 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1571 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001572 auto binder1 = sp<BBinder>::make();
1573 IBinder* binderRaw1 = binder1.get();
1574 setRootObject(isStrong1)(server.get(), binder1);
1575 EXPECT_EQ(binderRaw1, server->getRootObject());
1576 binder1.clear();
1577 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1578
1579 auto binder2 = sp<BBinder>::make();
1580 IBinder* binderRaw2 = binder2.get();
1581 setRootObject(isStrong2)(server.get(), binder2);
1582 EXPECT_EQ(binderRaw2, server->getRootObject());
1583 binder2.clear();
1584 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1585}
1586
1587INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001588 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1589 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001590
Yifan Hong1a235852021-05-13 16:07:47 -07001591class OneOffSignal {
1592public:
1593 // If notify() was previously called, or is called within |duration|, return true; else false.
1594 template <typename R, typename P>
1595 bool wait(std::chrono::duration<R, P> duration) {
1596 std::unique_lock<std::mutex> lock(mMutex);
1597 return mCv.wait_for(lock, duration, [this] { return mValue; });
1598 }
1599 void notify() {
1600 std::unique_lock<std::mutex> lock(mMutex);
1601 mValue = true;
1602 lock.unlock();
1603 mCv.notify_all();
1604 }
1605
1606private:
1607 std::mutex mMutex;
1608 std::condition_variable mCv;
1609 bool mValue = false;
1610};
1611
Yifan Hong194acf22021-06-29 18:44:56 -07001612TEST(BinderRpc, Java) {
1613#if !defined(__ANDROID__)
1614 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1615 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1616 "to binderHostDeviceTest. Hence, just disable this test on host.";
1617#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001618 if constexpr (!kEnableKernelIpc) {
1619 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1620 "at build time.";
1621 }
1622
Yifan Hong194acf22021-06-29 18:44:56 -07001623 sp<IServiceManager> sm = defaultServiceManager();
1624 ASSERT_NE(nullptr, sm);
1625 // Any Java service with non-empty getInterfaceDescriptor() would do.
1626 // Let's pick batteryproperties.
1627 auto binder = sm->checkService(String16("batteryproperties"));
1628 ASSERT_NE(nullptr, binder);
1629 auto descriptor = binder->getInterfaceDescriptor();
1630 ASSERT_GE(descriptor.size(), 0);
1631 ASSERT_EQ(OK, binder->pingBinder());
1632
1633 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001634 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001635 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001636 auto socket = rpcServer->releaseServer();
1637
1638 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001639 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1640
Yifan Honge3caaf22022-01-12 14:46:56 -08001641 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1642 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001643 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001644 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1645 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001646 << statusToString(setRpcClientDebugStatus);
1647 GTEST_SKIP();
1648 }
1649
1650 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001651
1652 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001653 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001654 auto rpcBinder = rpcSession->getRootObject();
1655 ASSERT_NE(nullptr, rpcBinder);
1656
1657 ASSERT_EQ(OK, rpcBinder->pingBinder());
1658
1659 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1660 << "getInterfaceDescriptor should not crash system_server";
1661 ASSERT_EQ(OK, rpcBinder->pingBinder());
1662}
1663
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001664class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1665public:
1666 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1667 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1668 std::to_string(std::get<1>(info.param));
1669 }
1670};
1671
1672TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1673 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1674 int sinkFd = sink.get();
1675 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1676 server->setProtocolVersion(std::get<1>(GetParam()));
1677 ASSERT_FALSE(server->hasServer());
1678 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1679 ASSERT_TRUE(server->hasServer());
1680 base::unique_fd retrieved = server->releaseServer();
1681 ASSERT_FALSE(server->hasServer());
1682 ASSERT_EQ(sinkFd, retrieved.get());
1683}
1684
1685TEST_P(BinderRpcServerOnly, Shutdown) {
1686 if constexpr (!kEnableRpcThreads) {
1687 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1688 }
1689
1690 auto addr = allocateSocketAddress();
1691 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1692 server->setProtocolVersion(std::get<1>(GetParam()));
1693 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1694 auto joinEnds = std::make_shared<OneOffSignal>();
1695
1696 // If things are broken and the thread never stops, don't block other tests. Because the thread
1697 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1698 // shared pointers are passed.
1699 std::thread([server, joinEnds] {
1700 server->join();
1701 joinEnds->notify();
1702 }).detach();
1703
1704 bool shutdown = false;
1705 for (int i = 0; i < 10 && !shutdown; i++) {
1706 usleep(300 * 1000); // 300ms; total 3s
1707 if (server->shutdown()) shutdown = true;
1708 }
1709 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1710
1711 ASSERT_TRUE(joinEnds->wait(2s))
1712 << "After server->shutdown() returns true, join() did not stop after 2s";
1713}
1714
Frederick Mayledc07cf82022-05-26 20:30:12 +00001715INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1716 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1717 ::testing::ValuesIn(testVersions())),
1718 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001719
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001720class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001721public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001722 // Only parameterized only server version because `RpcSession` is bypassed
1723 // in the client half of the tests.
1724 using Param =
1725 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001726 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001727
1728 // A server that handles client socket connections.
1729 class Server {
1730 public:
1731 explicit Server() {}
1732 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001733 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001734 [[nodiscard]] AssertionResult setUp(
1735 const Param& param,
1736 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001737 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001738 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001739 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001740 switch (socketType) {
1741 case SocketType::PRECONNECTED: {
1742 return AssertionFailure() << "Not supported by this test";
1743 } break;
1744 case SocketType::UNIX: {
1745 auto addr = allocateSocketAddress();
1746 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1747 if (status != OK) {
1748 return AssertionFailure()
1749 << "setupUnixDomainServer: " << statusToString(status);
1750 }
1751 mConnectToServer = [addr] {
1752 return connectTo(UnixSocketAddress(addr.c_str()));
1753 };
1754 } break;
1755 case SocketType::VSOCK: {
1756 auto port = allocateVsockPort();
1757 auto status = rpcServer->setupVsockServer(port);
1758 if (status != OK) {
1759 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1760 }
1761 mConnectToServer = [port] {
1762 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1763 };
1764 } break;
1765 case SocketType::INET: {
1766 unsigned int port;
1767 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1768 if (status != OK) {
1769 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1770 }
1771 mConnectToServer = [port] {
1772 const char* addr = kLocalInetAddress;
1773 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1774 if (aiStart == nullptr) return base::unique_fd{};
1775 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1776 auto fd = connectTo(
1777 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1778 if (fd.ok()) return fd;
1779 }
1780 ALOGE("None of the socket address resolved for %s:%u can be connected",
1781 addr, port);
1782 return base::unique_fd{};
1783 };
1784 }
1785 }
1786 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001787 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001788 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001789 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1790 mSetup = true;
1791 return AssertionSuccess();
1792 }
1793 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1794 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1795 return mCertVerifier;
1796 }
1797 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1798 void start() {
1799 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1800 mThread = std::make_unique<std::thread>(&Server::run, this);
1801 }
1802 void run() {
1803 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1804
1805 std::vector<std::thread> threads;
1806 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1807 base::unique_fd acceptedFd(
Pawan49d74cb2022-08-03 21:19:11 +00001808 TEMP_FAILURE_RETRY(accept4(mFd.fd.get(), nullptr, nullptr /*length*/,
Yifan Hong1deca4b2021-09-10 16:16:44 -07001809 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1810 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1811 }
1812
1813 for (auto& thread : threads) thread.join();
1814 }
1815 void handleOne(android::base::unique_fd acceptedFd) {
1816 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001817 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001818 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001819 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001820 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001821 }
Yifan Honge07d2732021-09-13 21:59:14 -07001822 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001823 shutdown();
1824 join();
1825 }
1826 void shutdown() { mFdTrigger->trigger(); }
1827
1828 void setPostConnect(
1829 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1830 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001831 }
1832
1833 private:
1834 std::unique_ptr<std::thread> mThread;
1835 ConnectToServer mConnectToServer;
1836 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
Pawan3e0061c2022-08-26 21:08:34 +00001837 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001838 std::unique_ptr<RpcTransportCtx> mCtx;
1839 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1840 std::make_shared<RpcCertificateVerifierSimple>();
1841 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001842 // The function invoked after connection and handshake. By default, it is
1843 // |defaultPostConnect| that sends |kMessage| to the client.
1844 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1845 Server::defaultPostConnect;
1846
1847 void join() {
1848 if (mThread != nullptr) {
1849 mThread->join();
1850 mThread = nullptr;
1851 }
1852 }
1853
1854 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1855 FdTrigger* fdTrigger) {
1856 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001857 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001858 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001859 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001860 if (status != OK) return AssertionFailure() << statusToString(status);
1861 return AssertionSuccess();
1862 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001863 };
1864
1865 class Client {
1866 public:
1867 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1868 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001869 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001870 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1871 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001872 mFdTrigger = FdTrigger::make();
1873 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1874 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1875 return AssertionSuccess();
1876 }
1877 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1878 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1879 return mCertVerifier;
1880 }
Yifan Hong67519322021-09-13 18:51:16 -07001881 // connect() and do handshake
1882 bool setUpTransport() {
1883 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001884 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001885 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1886 return mClientTransport != nullptr;
1887 }
1888 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1889 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1890 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001891 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001892 status_t readStatus =
1893 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001894 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001895 if (readStatus != OK) {
1896 return AssertionFailure() << statusToString(readStatus);
1897 }
1898 if (readMessage != expectedMessage) {
1899 return AssertionFailure()
1900 << "Expected " << expectedMessage << ", actual " << readMessage;
1901 }
1902 return AssertionSuccess();
1903 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001904 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001905 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001906 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1907 return;
1908 }
1909 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001910 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001911 }
1912
Pawan49d74cb2022-08-03 21:19:11 +00001913 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1914
Yifan Hong1deca4b2021-09-10 16:16:44 -07001915 private:
1916 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001917 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001918 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1919 std::unique_ptr<RpcTransportCtx> mCtx;
1920 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1921 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001922 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001923 };
1924
1925 // Make A trust B.
1926 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001927 static status_t trust(RpcSecurity rpcSecurity,
1928 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1929 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001930 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001931 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1932 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1933 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001934 }
1935
1936 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001937};
1938
1939class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1940public:
1941 using Server = RpcTransportTestUtils::Server;
1942 using Client = RpcTransportTestUtils::Client;
1943 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001944 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001945 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1946 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001947 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001948 return ret;
1949 }
1950 static std::vector<ParamType> getRpcTranportTestParams() {
1951 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001952 for (auto serverVersion : testVersions()) {
1953 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1954 for (auto rpcSecurity : RpcSecurityValues()) {
1955 switch (rpcSecurity) {
1956 case RpcSecurity::RAW: {
1957 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1958 } break;
1959 case RpcSecurity::TLS: {
1960 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1961 serverVersion);
1962 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1963 serverVersion);
1964 } break;
1965 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001966 }
1967 }
1968 }
1969 return ret;
1970 }
1971 template <typename A, typename B>
1972 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001973 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1974 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001975 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1976 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001977 void SetUp() override {
1978 if constexpr (!kEnableRpcThreads) {
1979 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1980 }
1981 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001982};
1983
1984TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001985 auto server = std::make_unique<Server>();
1986 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001987
1988 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001989 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001990
1991 ASSERT_EQ(OK, trust(&client, server));
1992 ASSERT_EQ(OK, trust(server, &client));
1993
1994 server->start();
1995 client.run();
1996}
1997
1998TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001999 auto server = std::make_unique<Server>();
2000 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002001
2002 std::vector<Client> clients;
2003 for (int i = 0; i < 2; i++) {
2004 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002005 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002006 ASSERT_EQ(OK, trust(&client, server));
2007 ASSERT_EQ(OK, trust(server, &client));
2008 }
2009
2010 server->start();
2011 for (auto& client : clients) client.run();
2012}
2013
2014TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002015 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2016 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002017
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002018 auto untrustedServer = std::make_unique<Server>();
2019 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002020
2021 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002022 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002023
2024 ASSERT_EQ(OK, trust(untrustedServer, &client));
2025
2026 untrustedServer->start();
2027
2028 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2029 // the client can't verify the server's identity.
2030 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2031 client.run(handshakeOk);
2032}
2033TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002034 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2035 (void)serverVersion;
2036
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002037 auto validServer = std::make_unique<Server>();
2038 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002039
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002040 auto maliciousServer = std::make_unique<Server>();
2041 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002042
2043 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002044 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002045
2046 ASSERT_EQ(OK, trust(&client, validServer));
2047 ASSERT_EQ(OK, trust(validServer, &client));
2048 ASSERT_EQ(OK, trust(maliciousServer, &client));
2049
2050 maliciousServer->start();
2051
2052 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2053 // the client can't verify the server's identity.
2054 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2055 client.run(handshakeOk);
2056}
2057
2058TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002059 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2060 (void)serverVersion;
2061
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002062 auto server = std::make_unique<Server>();
2063 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002064
2065 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002066 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002067
2068 ASSERT_EQ(OK, trust(&client, server));
2069
2070 server->start();
2071
2072 // For TLS, Client should be able to verify server's identity, so client should see
2073 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2074 // identity and should drop the connection, so client shouldn't be able to read anything.
2075 bool readOk = rpcSecurity != RpcSecurity::TLS;
2076 client.run(true, readOk);
2077}
2078
2079TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002080 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2081 (void)serverVersion;
2082
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002083 auto server = std::make_unique<Server>();
2084 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002085
2086 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002087 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002088 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002089 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002090
2091 ASSERT_EQ(OK, trust(&validClient, server));
2092 ASSERT_EQ(OK, trust(&maliciousClient, server));
2093
2094 server->start();
2095
2096 // See UntrustedClient.
2097 bool readOk = rpcSecurity != RpcSecurity::TLS;
2098 maliciousClient.run(true, readOk);
2099}
2100
Yifan Hong67519322021-09-13 18:51:16 -07002101TEST_P(RpcTransportTest, Trigger) {
2102 std::string msg2 = ", world!";
2103 std::mutex writeMutex;
2104 std::condition_variable writeCv;
2105 bool shouldContinueWriting = false;
2106 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002107 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002108 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002109 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2110 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002111 if (status != OK) return AssertionFailure() << statusToString(status);
2112
2113 {
2114 std::unique_lock<std::mutex> lock(writeMutex);
2115 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2116 return AssertionFailure() << "write barrier not cleared in time!";
2117 }
2118 }
2119
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002120 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002121 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2122 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002123 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002124 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002125 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002126 << statusToString(status);
2127 return AssertionSuccess();
2128 };
2129
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002130 auto server = std::make_unique<Server>();
2131 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002132
2133 // Set up client
2134 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002135 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002136
2137 // Exchange keys
2138 ASSERT_EQ(OK, trust(&client, server));
2139 ASSERT_EQ(OK, trust(server, &client));
2140
2141 server->setPostConnect(serverPostConnect);
2142
Yifan Hong67519322021-09-13 18:51:16 -07002143 server->start();
2144 // connect() to server and do handshake
2145 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002146 // read the first message. This ensures that server has finished handshake and start handling
2147 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002148 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002149 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2150 // write is on an FdTrigger that has been shut down.
2151 server->shutdown();
2152 // Continues server thread to write the second message.
2153 {
Yifan Hong22211f82021-09-14 12:32:25 -07002154 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002155 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002156 }
Yifan Hong22211f82021-09-14 12:32:25 -07002157 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002158 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002159 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002160 // On the client side, second read fails with DEAD_OBJECT
2161 ASSERT_FALSE(client.readMessage(msg2));
2162}
2163
Pawan49d74cb2022-08-03 21:19:11 +00002164TEST_P(RpcTransportTest, CheckWaitingForRead) {
2165 std::mutex readMutex;
2166 std::condition_variable readCv;
2167 bool shouldContinueReading = false;
2168 // Server will write data on transport once its started
2169 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
2170 std::string message(RpcTransportTestUtils::kMessage);
2171 iovec messageIov{message.data(), message.size()};
2172 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2173 std::nullopt, nullptr);
2174 if (status != OK) return AssertionFailure() << statusToString(status);
2175
2176 {
2177 std::unique_lock<std::mutex> lock(readMutex);
2178 shouldContinueReading = true;
2179 lock.unlock();
2180 readCv.notify_all();
2181 }
2182 return AssertionSuccess();
2183 };
2184
2185 // Setup Server and client
2186 auto server = std::make_unique<Server>();
2187 ASSERT_TRUE(server->setUp(GetParam()));
2188
2189 Client client(server->getConnectToServerFn());
2190 ASSERT_TRUE(client.setUp(GetParam()));
2191
2192 ASSERT_EQ(OK, trust(&client, server));
2193 ASSERT_EQ(OK, trust(server, &client));
2194 server->setPostConnect(serverPostConnect);
2195
2196 server->start();
2197 ASSERT_TRUE(client.setUpTransport());
2198 {
2199 // Wait till server writes data
2200 std::unique_lock<std::mutex> lock(readMutex);
2201 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2202 }
2203
2204 // Since there is no read polling here, we will get polling count 0
2205 ASSERT_FALSE(client.isTransportWaiting());
2206 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2207 // Thread should increment polling count, read and decrement polling count
2208 // Again, polling count should be zero here
2209 ASSERT_FALSE(client.isTransportWaiting());
2210
2211 server->shutdown();
2212}
2213
Yifan Hong1deca4b2021-09-10 16:16:44 -07002214INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002215 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002216 RpcTransportTest::PrintParamInfo);
2217
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002218class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002219 : public testing::TestWithParam<
2220 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002221public:
2222 template <typename A, typename B>
2223 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002224 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2225 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002226 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2227 }
2228 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002229 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2230 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2231 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002232 };
2233};
2234
2235TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002236 if constexpr (!kEnableRpcThreads) {
2237 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2238 }
2239
Frederick Mayledc07cf82022-05-26 20:30:12 +00002240 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002241
2242 std::vector<uint8_t> pkeyData, certData;
2243 {
2244 auto pkey = makeKeyPairForSelfSignedCert();
2245 ASSERT_NE(nullptr, pkey);
2246 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2247 ASSERT_NE(nullptr, cert);
2248 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2249 certData = serializeCertificate(cert.get(), certificateFormat);
2250 }
2251
2252 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2253 auto desCert = deserializeCertificate(certData, certificateFormat);
2254 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002255 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2256 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002257
2258 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2259 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2260
2261 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2262 ASSERT_TRUE(client.setUp(utilsParam));
2263
2264 ASSERT_EQ(OK, trust(&client, server));
2265 ASSERT_EQ(OK, trust(server, &client));
2266
2267 server->start();
2268 client.run();
2269}
2270
2271INSTANTIATE_TEST_CASE_P(
2272 BinderRpc, RpcTransportTlsKeyTest,
2273 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2274 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002275 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2276 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002277 RpcTransportTlsKeyTest::PrintParamInfo);
2278
Steven Morelandc1635952021-04-01 16:20:47 +00002279} // namespace android
2280
2281int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002282 ::testing::InitGoogleTest(&argc, argv);
2283 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002284
Steven Moreland5553ac42020-11-11 02:14:45 +00002285 return RUN_ALL_TESTS();
2286}