blob: 9a6d4dfa534cf9181b0c5814e26c5f71d416a42b [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Frederick Maylea12b0962022-06-25 01:13:22 +000017#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000018#include <gtest/gtest.h>
19
Steven Morelandc1635952021-04-01 16:20:47 +000020#include <chrono>
21#include <cstdlib>
22#include <iostream>
23#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000024#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000025
Andrei Homescu2a298012022-06-15 01:08:54 +000026#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070027#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000029#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000030
Andrei Homescu2a298012022-06-15 01:08:54 +000031#include "binderRpcTestCommon.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000032
Yifan Hong1a235852021-05-13 16:07:47 -070033using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070034using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070035using testing::AssertionFailure;
36using testing::AssertionResult;
37using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070038
Steven Moreland5553ac42020-11-11 02:14:45 +000039namespace android {
40
Andrei Homescu12106de2022-04-27 04:42:21 +000041#ifdef BINDER_TEST_NO_SHARED_LIBS
42constexpr bool kEnableSharedLibs = false;
43#else
44constexpr bool kEnableSharedLibs = true;
45#endif
46
Steven Morelandbf57bce2021-07-26 15:26:12 -070047static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
48 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Frederick Mayle69a0c992022-05-26 20:38:39 +000049
Steven Moreland1fda67b2021-04-02 18:35:50 +000050TEST(BinderRpcParcel, EntireParcelFormatted) {
51 Parcel p;
52 p.writeInt32(3);
53
Devin Moore66d5b7a2022-07-07 21:42:10 +000054 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "format must be set before data is written");
Steven Moreland1fda67b2021-04-02 18:35:50 +000055}
56
Steven Morelandbf57bce2021-07-26 15:26:12 -070057TEST(BinderRpc, CannotUseNextWireVersion) {
58 auto session = RpcSession::make();
59 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
60 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
61 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
62 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
63}
64
65TEST(BinderRpc, CanUseExperimentalWireVersion) {
66 auto session = RpcSession::make();
67 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
68}
69
Steven Moreland5553ac42020-11-11 02:14:45 +000070using android::binder::Status;
71
72#define EXPECT_OK(status) \
73 do { \
74 Status stat = (status); \
75 EXPECT_TRUE(stat.isOk()) << stat; \
76 } while (false)
77
Frederick Maylea12b0962022-06-25 01:13:22 +000078static std::string WaitStatusToString(int wstatus) {
79 if (WIFEXITED(wstatus)) {
80 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
81 }
82 if (WIFSIGNALED(wstatus)) {
83 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
84 }
85 return base::StringPrintf("unexpected state %d", wstatus);
86}
87
Steven Moreland276d8df2022-09-28 23:56:39 +000088static void debugBacktrace(pid_t pid) {
89 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
90 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
91}
92
Steven Moreland5553ac42020-11-11 02:14:45 +000093class Process {
94public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -070095 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -070096 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
97 android::base::borrowed_fd /* readEnd */)>& f) {
98 android::base::unique_fd childWriteEnd;
99 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +0000100 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
101 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000102 if (0 == (mPid = fork())) {
103 // racey: assume parent doesn't crash before this is set
104 prctl(PR_SET_PDEATHSIG, SIGHUP);
105
Yifan Hong1deca4b2021-09-10 16:16:44 -0700106 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000107
108 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000109 }
110 }
111 ~Process() {
112 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000113 int wstatus;
114 waitpid(mPid, &wstatus, 0);
115 if (mCustomExitStatusCheck) {
116 mCustomExitStatusCheck(wstatus);
117 } else {
118 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
119 << "server process failed: " << WaitStatusToString(wstatus);
120 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000121 }
122 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700123 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700124 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000125
Frederick Maylea12b0962022-06-25 01:13:22 +0000126 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
127 mCustomExitStatusCheck = std::move(f);
128 }
129
Frederick Mayle69a0c992022-05-26 20:38:39 +0000130 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
131 void terminate() { kill(mPid, SIGTERM); }
132
Steven Moreland276d8df2022-09-28 23:56:39 +0000133 pid_t getPid() { return mPid; }
134
Steven Moreland5553ac42020-11-11 02:14:45 +0000135private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000136 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000137 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700138 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700139 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000140};
141
142static std::string allocateSocketAddress() {
143 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000144 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700145 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
146 unlink(ret.c_str());
147 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000148};
149
Steven Morelandda573042021-06-12 01:13:45 +0000150static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000151 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000152 return vsockPort++;
153}
154
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000155struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000156 // reference to process hosting a socket server
157 Process host;
158
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000159 struct SessionInfo {
160 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000161 sp<IBinder> root;
162 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000163
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000164 // client session objects associated with other process
165 // each one represents a separate session
166 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000167
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000168 ProcessSession(ProcessSession&&) = default;
169 ~ProcessSession() {
170 for (auto& session : sessions) {
171 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000172 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000173
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000174 for (auto& info : sessions) {
175 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000176
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000177 EXPECT_NE(nullptr, session);
178 EXPECT_NE(nullptr, session->state());
179 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000180
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000181 wp<RpcSession> weakSession = session;
182 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000183
184 EXPECT_EQ(nullptr, weakSession.promote())
185 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()), "Leaked session");
Steven Moreland736664b2021-05-01 04:27:25 +0000186 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000187 }
188};
189
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000190// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000191// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000192struct BinderRpcTestProcessSession {
193 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000194
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000195 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000196 sp<IBinder> rootBinder;
197
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000198 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000199 sp<IBinderRpcTest> rootIface;
200
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000201 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000202 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000203
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000204 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
205 ~BinderRpcTestProcessSession() {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000206 if (!expectAlreadyShutdown) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000207 EXPECT_NE(nullptr, rootIface);
208 if (rootIface == nullptr) return;
209
Steven Moreland736664b2021-05-01 04:27:25 +0000210 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000211 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000212 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000213 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000214 for (auto remoteCount : remoteCounts) {
215 EXPECT_EQ(remoteCount, 1);
216 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000217
Steven Moreland798e0d12021-07-14 23:19:25 +0000218 // even though it is on another thread, shutdown races with
219 // the transaction reply being written
220 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
221 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
222 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000223 }
224
225 rootIface = nullptr;
226 rootBinder = nullptr;
227 }
228};
229
Yifan Hong1deca4b2021-09-10 16:16:44 -0700230static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700231 base::unique_fd serverFd(
232 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
233 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700234 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
235 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700236
237 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
238 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700239 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
240 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700241 }
242 return serverFd;
243}
244
Andrei Homescu2a298012022-06-15 01:08:54 +0000245using RunServiceFn = void (*)(android::base::borrowed_fd writeEnd,
246 android::base::borrowed_fd readEnd);
247
248class BinderRpc : public ::testing::TestWithParam<
249 std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t, bool, bool>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000250public:
Frederick Mayle69a0c992022-05-26 20:38:39 +0000251 SocketType socketType() const { return std::get<0>(GetParam()); }
252 RpcSecurity rpcSecurity() const { return std::get<1>(GetParam()); }
253 uint32_t clientVersion() const { return std::get<2>(GetParam()); }
254 uint32_t serverVersion() const { return std::get<3>(GetParam()); }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000255 bool serverSingleThreaded() const { return std::get<4>(GetParam()); }
Andrei Homescu2a298012022-06-15 01:08:54 +0000256 bool noKernel() const { return std::get<5>(GetParam()); }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000257
Andrei Homescua858b0e2022-08-01 23:43:09 +0000258 bool clientOrServerSingleThreaded() const {
259 return !kEnableRpcThreads || serverSingleThreaded();
260 }
261
Frederick Mayle69a0c992022-05-26 20:38:39 +0000262 // Whether the test params support sending FDs in parcels.
263 bool supportsFdTransport() const {
264 return clientVersion() >= 1 && serverVersion() >= 1 && rpcSecurity() != RpcSecurity::TLS &&
265 (socketType() == SocketType::PRECONNECTED || socketType() == SocketType::UNIX);
266 }
267
Yifan Hong702115c2021-06-24 15:39:18 -0700268 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000269 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
270 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
Frederick Mayledc07cf82022-05-26 20:30:12 +0000271 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Andrei Homescu2a298012022-06-15 01:08:54 +0000272 if (singleThreaded) {
273 ret += "_single_threaded";
274 }
275 if (noKernel) {
276 ret += "_no_kernel";
277 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700278 return ret;
279 }
280
Steven Morelandc1635952021-04-01 16:20:47 +0000281 // This creates a new process serving an interface on a certain number of
282 // threads.
Andrei Homescu2a298012022-06-15 01:08:54 +0000283 ProcessSession createRpcTestSocketServerProcessEtc(const BinderRpcOptions& options) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000284 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000285
Yifan Hong702115c2021-06-24 15:39:18 -0700286 SocketType socketType = std::get<0>(GetParam());
287 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000288 uint32_t clientVersion = std::get<2>(GetParam());
289 uint32_t serverVersion = std::get<3>(GetParam());
Andrei Homescu2a298012022-06-15 01:08:54 +0000290 bool singleThreaded = std::get<4>(GetParam());
291 bool noKernel = std::get<5>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000292
Andrei Homescu2a298012022-06-15 01:08:54 +0000293 std::string path = android::base::GetExecutableDirectory();
294 auto servicePath =
295 android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
296 singleThreaded ? "_single_threaded" : "",
297 noKernel ? "_no_kernel" : "");
Steven Morelandc1635952021-04-01 16:20:47 +0000298
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000299 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000300 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700301 android::base::borrowed_fd readEnd) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000302 auto writeFd = std::to_string(writeEnd.get());
303 auto readFd = std::to_string(readEnd.get());
304 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
305 NULL);
Steven Morelandc1635952021-04-01 16:20:47 +0000306 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000307 };
308
Andrei Homescu2a298012022-06-15 01:08:54 +0000309 BinderRpcTestServerConfig serverConfig;
310 serverConfig.numThreads = options.numThreads;
311 serverConfig.socketType = static_cast<int32_t>(socketType);
312 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
313 serverConfig.serverVersion = serverVersion;
314 serverConfig.vsockPort = allocateVsockPort();
315 serverConfig.addr = allocateSocketAddress();
316 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
317 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
318 static_cast<int32_t>(mode));
319 }
320 writeToFd(ret.host.writeEnd(), serverConfig);
321
Yifan Hong1deca4b2021-09-10 16:16:44 -0700322 std::vector<sp<RpcSession>> sessions;
323 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
324 for (size_t i = 0; i < options.numSessions; i++) {
325 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
326 }
327
328 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
329 BinderRpcTestClientInfo clientInfo;
330 for (const auto& session : sessions) {
331 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700332 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700333 }
334 writeToFd(ret.host.writeEnd(), clientInfo);
335
336 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700337 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700338 CHECK_NE(0, serverInfo.port);
339 }
340
341 if (rpcSecurity == RpcSecurity::TLS) {
342 const auto& serverCert = serverInfo.cert.data;
343 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700344 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
345 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700346 }
347
Steven Moreland2372f9d2021-08-05 15:42:01 -0700348 status_t status;
349
Yifan Hong1deca4b2021-09-10 16:16:44 -0700350 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000351 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700352 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700353 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000354 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Moreland659416d2021-05-11 00:47:50 +0000355
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000356 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700357 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700358 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000359 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700360 });
Steven Moreland4198a122021-08-03 17:37:58 -0700361 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000362 case SocketType::UNIX:
Andrei Homescu2a298012022-06-15 01:08:54 +0000363 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000364 break;
365 case SocketType::VSOCK:
Andrei Homescu2a298012022-06-15 01:08:54 +0000366 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000367 break;
368 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700369 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000370 break;
371 default:
372 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000373 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000374 if (options.allowConnectFailure && status != OK) {
375 ret.sessions.clear();
376 break;
377 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700378 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000379 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000380 }
Steven Morelandc1635952021-04-01 16:20:47 +0000381 return ret;
382 }
383
Andrei Homescu2a298012022-06-15 01:08:54 +0000384 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const BinderRpcOptions& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000385 BinderRpcTestProcessSession ret{
Andrei Homescu2a298012022-06-15 01:08:54 +0000386 .proc = createRpcTestSocketServerProcessEtc(options),
Steven Morelandc1635952021-04-01 16:20:47 +0000387 };
388
Frederick Mayle69a0c992022-05-26 20:38:39 +0000389 ret.rootBinder = ret.proc.sessions.empty() ? nullptr : ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000390 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
391
392 return ret;
393 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700394
395 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
396 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000397};
398
Steven Morelandc1635952021-04-01 16:20:47 +0000399TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000400 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000401 ASSERT_NE(proc.rootBinder, nullptr);
402 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
403}
404
Steven Moreland4cf688f2021-03-31 01:48:58 +0000405TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000406 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000407 ASSERT_NE(proc.rootBinder, nullptr);
408 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
409}
410
Andrei Homescua858b0e2022-08-01 23:43:09 +0000411TEST_P(BinderRpc, MultipleSessions) {
412 if (serverSingleThreaded()) {
413 // Tests with multiple sessions require a multi-threaded service,
414 // but work fine on a single-threaded client
415 GTEST_SKIP() << "This test requires a multi-threaded service";
416 }
417
Steven Moreland4313d7e2021-07-15 23:41:22 +0000418 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000419 for (auto session : proc.proc.sessions) {
420 ASSERT_NE(nullptr, session.root);
421 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000422 }
423}
424
Andrei Homescua858b0e2022-08-01 23:43:09 +0000425TEST_P(BinderRpc, SeparateRootObject) {
426 if (serverSingleThreaded()) {
427 GTEST_SKIP() << "This test requires a multi-threaded service";
428 }
429
Steven Moreland51c44a92021-10-14 16:50:35 -0700430 SocketType type = std::get<0>(GetParam());
431 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
432 // we can't get port numbers for unix sockets
433 return;
434 }
435
436 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
437
438 int port1 = 0;
439 EXPECT_OK(proc.rootIface->getClientPort(&port1));
440
441 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
442 int port2;
443 EXPECT_OK(rootIface2->getClientPort(&port2));
444
445 // we should have a different IBinderRpcTest object created for each
446 // session, because we use setPerSessionRootObject
447 EXPECT_NE(port1, port2);
448}
449
Steven Morelandc1635952021-04-01 16:20:47 +0000450TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000451 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000452 Parcel data;
453 Parcel reply;
454 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
455}
456
Steven Moreland67753c32021-04-02 18:45:19 +0000457TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700458 auto proc1 = createRpcTestSocketServerProcess({});
459 auto proc2 = createRpcTestSocketServerProcess({});
460
461 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000462
463 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700464 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000465 p1.writeInt32(3);
466
Frederick Maylea4ed5672022-06-17 22:03:38 +0000467 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700468 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
469
Steven Moreland67753c32021-04-02 18:45:19 +0000470 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700471 p2.markForBinder(proc2.rootBinder);
472 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000473
474 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
475 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
476}
477
Steven Morelandc1635952021-04-01 16:20:47 +0000478TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000479 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000480 Parcel data;
481 data.markForBinder(proc.rootBinder);
482 Parcel reply;
483 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
484}
485
Steven Morelandc1635952021-04-01 16:20:47 +0000486TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000487 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000488 EXPECT_OK(proc.rootIface->sendString("asdf"));
489}
490
Steven Morelandc1635952021-04-01 16:20:47 +0000491TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000492 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000493 std::string doubled;
494 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
495 EXPECT_EQ("cool cool ", doubled);
496}
497
Steven Morelandc1635952021-04-01 16:20:47 +0000498TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000499 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000500 std::string single = std::string(1024, 'a');
501 std::string doubled;
502 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
503 EXPECT_EQ(single + single, doubled);
504}
505
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000506TEST_P(BinderRpc, InvalidNullBinderReturn) {
507 auto proc = createRpcTestSocketServerProcess({});
508
509 sp<IBinder> outBinder;
510 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
511}
512
Steven Morelandc1635952021-04-01 16:20:47 +0000513TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000514 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000515
516 int32_t pingResult;
517 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
518 EXPECT_EQ(OK, pingResult);
519
520 EXPECT_EQ(0, MyBinderRpcSession::gNum);
521}
522
Steven Morelandc1635952021-04-01 16:20:47 +0000523TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000524 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000525
526 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
527 sp<IBinder> outBinder;
528 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
529 EXPECT_EQ(inBinder, outBinder);
530
531 wp<IBinder> weak = inBinder;
532 inBinder = nullptr;
533 outBinder = nullptr;
534
535 // Force reading a reply, to process any pending dec refs from the other
536 // process (the other process will process dec refs there before processing
537 // the ping here).
538 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
539
540 EXPECT_EQ(nullptr, weak.promote());
541
542 EXPECT_EQ(0, MyBinderRpcSession::gNum);
543}
544
Steven Morelandc1635952021-04-01 16:20:47 +0000545TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000546 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000547
548 sp<IBinderRpcSession> session;
549 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
550
551 sp<IBinder> inBinder = IInterface::asBinder(session);
552 sp<IBinder> outBinder;
553 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
554 EXPECT_EQ(inBinder, outBinder);
555
556 wp<IBinder> weak = inBinder;
557 session = nullptr;
558 inBinder = nullptr;
559 outBinder = nullptr;
560
561 // Force reading a reply, to process any pending dec refs from the other
562 // process (the other process will process dec refs there before processing
563 // the ping here).
564 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
565
566 EXPECT_EQ(nullptr, weak.promote());
567}
568
Steven Morelandc1635952021-04-01 16:20:47 +0000569TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000570 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000571
572 sp<IBinder> outBinder;
573 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
574 EXPECT_EQ(nullptr, outBinder);
575}
576
Steven Morelandc1635952021-04-01 16:20:47 +0000577TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000578 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000579
580 IBinder* ptr = nullptr;
581 {
582 sp<IBinder> binder = new BBinder();
583 ptr = binder.get();
584 EXPECT_OK(proc.rootIface->holdBinder(binder));
585 }
586
587 sp<IBinder> held;
588 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
589
590 EXPECT_EQ(held.get(), ptr);
591
592 // stop holding binder, because we test to make sure references are cleaned
593 // up
594 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
595 // and flush ref counts
596 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
597}
598
599// START TESTS FOR LIMITATIONS OF SOCKET BINDER
600// These are behavioral differences form regular binder, where certain usecases
601// aren't supported.
602
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000603TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000604 auto proc1 = createRpcTestSocketServerProcess({});
605 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000606
607 sp<IBinder> outBinder;
608 EXPECT_EQ(INVALID_OPERATION,
609 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
610}
611
Andrei Homescua858b0e2022-08-01 23:43:09 +0000612TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
613 if (serverSingleThreaded()) {
614 GTEST_SKIP() << "This test requires a multi-threaded service";
615 }
616
Steven Moreland4313d7e2021-07-15 23:41:22 +0000617 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000618
619 sp<IBinder> outBinder;
620 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000621 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000622 .transactionError());
623}
624
Steven Morelandc1635952021-04-01 16:20:47 +0000625TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000626 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000627 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
628 "at build time.";
629 }
630
Steven Moreland4313d7e2021-07-15 23:41:22 +0000631 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000632
633 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
634 sp<IBinder> outBinder;
635 EXPECT_EQ(INVALID_OPERATION,
636 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
637}
638
Steven Morelandc1635952021-04-01 16:20:47 +0000639TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000640 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000641 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
642 "at build time.";
643 }
644
Steven Moreland4313d7e2021-07-15 23:41:22 +0000645 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000646
647 // for historical reasons, IServiceManager interface only returns the
648 // exception code
649 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
650 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
651}
652
653// END TESTS FOR LIMITATIONS OF SOCKET BINDER
654
Steven Morelandc1635952021-04-01 16:20:47 +0000655TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000656 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000657
658 sp<IBinder> outBinder;
659 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
660 EXPECT_EQ(proc.rootBinder, outBinder);
661}
662
Steven Morelandc1635952021-04-01 16:20:47 +0000663TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000664 auto proc = createRpcTestSocketServerProcess({
665 // Enable FD support because it uses more stack space and so represents
666 // something closer to a worst case scenario.
667 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
668 .serverSupportedFileDescriptorTransportModes =
669 {RpcSession::FileDescriptorTransportMode::UNIX},
670 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000671
672 auto nastyNester = sp<MyBinderRpcTest>::make();
673 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
674
675 wp<IBinder> weak = nastyNester;
676 nastyNester = nullptr;
677 EXPECT_EQ(nullptr, weak.promote());
678}
679
Steven Morelandc1635952021-04-01 16:20:47 +0000680TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000681 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000682
683 sp<IBinder> a;
684 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
685
686 sp<IBinder> b;
687 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
688
689 EXPECT_EQ(a, b);
690}
691
Steven Morelandc1635952021-04-01 16:20:47 +0000692TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000693 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000694
695 sp<IBinder> a;
696 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
697 wp<IBinder> weak = a;
698 a = nullptr;
699
700 sp<IBinder> b;
701 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
702
703 // this is the wrong behavior, since BpBinder
704 // doesn't implement onIncStrongAttempted
705 // but make sure there is no crash
706 EXPECT_EQ(nullptr, weak.promote());
707
708 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
709
710 // In order to fix this:
711 // - need to have incStrongAttempted reflected across IPC boundary (wait for
712 // response to promote - round trip...)
713 // - sendOnLastWeakRef, to delete entries out of RpcState table
714 EXPECT_EQ(b, weak.promote());
715}
716
717#define expectSessions(expected, iface) \
718 do { \
719 int session; \
720 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
721 EXPECT_EQ(expected, session); \
722 } while (false)
723
Steven Morelandc1635952021-04-01 16:20:47 +0000724TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000725 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000726
727 sp<IBinderRpcSession> session;
728 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
729 std::string out;
730 EXPECT_OK(session->getName(&out));
731 EXPECT_EQ("aoeu", out);
732
733 expectSessions(1, proc.rootIface);
734 session = nullptr;
735 expectSessions(0, proc.rootIface);
736}
737
Steven Morelandc1635952021-04-01 16:20:47 +0000738TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000739 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000740
741 std::vector<sp<IBinderRpcSession>> sessions;
742
743 for (size_t i = 0; i < 15; i++) {
744 expectSessions(i, proc.rootIface);
745 sp<IBinderRpcSession> session;
746 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
747 sessions.push_back(session);
748 }
749 expectSessions(sessions.size(), proc.rootIface);
750 for (size_t i = 0; i < sessions.size(); i++) {
751 std::string out;
752 EXPECT_OK(sessions.at(i)->getName(&out));
753 EXPECT_EQ(std::to_string(i), out);
754 }
755 expectSessions(sessions.size(), proc.rootIface);
756
757 while (!sessions.empty()) {
758 sessions.pop_back();
759 expectSessions(sessions.size(), proc.rootIface);
760 }
761 expectSessions(0, proc.rootIface);
762}
763
764size_t epochMillis() {
765 using std::chrono::duration_cast;
766 using std::chrono::milliseconds;
767 using std::chrono::seconds;
768 using std::chrono::system_clock;
769 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
770}
771
Andrei Homescua858b0e2022-08-01 23:43:09 +0000772TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
773 if (clientOrServerSingleThreaded()) {
774 GTEST_SKIP() << "This test requires multiple threads";
775 }
776
Steven Moreland5553ac42020-11-11 02:14:45 +0000777 constexpr size_t kNumThreads = 10;
778
Steven Moreland4313d7e2021-07-15 23:41:22 +0000779 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000780
781 EXPECT_OK(proc.rootIface->lock());
782
783 // block all but one thread taking locks
784 std::vector<std::thread> ts;
785 for (size_t i = 0; i < kNumThreads - 1; i++) {
786 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
787 }
788
789 usleep(100000); // give chance for calls on other threads
790
791 // other calls still work
792 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
793
794 constexpr size_t blockTimeMs = 500;
795 size_t epochMsBefore = epochMillis();
796 // after this, we should never see a response within this time
797 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
798
799 // this call should be blocked for blockTimeMs
800 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
801
802 size_t epochMsAfter = epochMillis();
803 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
804
805 for (auto& t : ts) t.join();
806}
807
Yifan Hong1f44f982021-10-08 17:16:47 -0700808void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
809 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000810 size_t epochMsBefore = epochMillis();
811
812 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700813 for (size_t i = 0; i < numCalls; i++) {
814 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000815 }
816
817 for (auto& t : ts) t.join();
818
819 size_t epochMsAfter = epochMillis();
820
Yifan Hong1f44f982021-10-08 17:16:47 -0700821 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000822
823 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700824 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
825}
826
Andrei Homescua858b0e2022-08-01 23:43:09 +0000827TEST_P(BinderRpc, ThreadPoolOverSaturated) {
828 if (clientOrServerSingleThreaded()) {
829 GTEST_SKIP() << "This test requires multiple threads";
830 }
831
Yifan Hong1f44f982021-10-08 17:16:47 -0700832 constexpr size_t kNumThreads = 10;
833 constexpr size_t kNumCalls = kNumThreads + 3;
834 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
835 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
836}
837
Andrei Homescua858b0e2022-08-01 23:43:09 +0000838TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
839 if (clientOrServerSingleThreaded()) {
840 GTEST_SKIP() << "This test requires multiple threads";
841 }
842
Yifan Hong1f44f982021-10-08 17:16:47 -0700843 constexpr size_t kNumThreads = 20;
844 constexpr size_t kNumOutgoingConnections = 10;
845 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
846 auto proc = createRpcTestSocketServerProcess(
847 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
848 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000849}
850
Andrei Homescua858b0e2022-08-01 23:43:09 +0000851TEST_P(BinderRpc, ThreadingStressTest) {
852 if (clientOrServerSingleThreaded()) {
853 GTEST_SKIP() << "This test requires multiple threads";
854 }
855
Steven Moreland5553ac42020-11-11 02:14:45 +0000856 constexpr size_t kNumClientThreads = 10;
857 constexpr size_t kNumServerThreads = 10;
858 constexpr size_t kNumCalls = 100;
859
Steven Moreland4313d7e2021-07-15 23:41:22 +0000860 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000861
862 std::vector<std::thread> threads;
863 for (size_t i = 0; i < kNumClientThreads; i++) {
864 threads.push_back(std::thread([&] {
865 for (size_t j = 0; j < kNumCalls; j++) {
866 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000867 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000868 EXPECT_EQ(proc.rootBinder, out);
869 }
870 }));
871 }
872
873 for (auto& t : threads) t.join();
874}
875
Steven Moreland925ba0a2021-09-17 18:06:32 -0700876static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
877 std::vector<std::thread> threads;
878 for (size_t i = 0; i < threadCount; i++) {
879 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
880 }
881 for (auto& t : threads) t.join();
882}
883
Andrei Homescua858b0e2022-08-01 23:43:09 +0000884TEST_P(BinderRpc, OnewayStressTest) {
885 if (clientOrServerSingleThreaded()) {
886 GTEST_SKIP() << "This test requires multiple threads";
887 }
888
Steven Morelandc6046982021-04-20 00:49:42 +0000889 constexpr size_t kNumClientThreads = 10;
890 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700891 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000892
Steven Moreland4313d7e2021-07-15 23:41:22 +0000893 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000894
895 std::vector<std::thread> threads;
896 for (size_t i = 0; i < kNumClientThreads; i++) {
897 threads.push_back(std::thread([&] {
898 for (size_t j = 0; j < kNumCalls; j++) {
899 EXPECT_OK(proc.rootIface->sendString("a"));
900 }
Steven Morelandc6046982021-04-20 00:49:42 +0000901 }));
902 }
903
904 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700905
906 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000907}
908
Steven Morelandc1635952021-04-01 16:20:47 +0000909TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000910 constexpr size_t kReallyLongTimeMs = 100;
911 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
912
Steven Moreland4313d7e2021-07-15 23:41:22 +0000913 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000914
915 size_t epochMsBefore = epochMillis();
916
917 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
918
919 size_t epochMsAfter = epochMillis();
920 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
921}
922
Andrei Homescua858b0e2022-08-01 23:43:09 +0000923TEST_P(BinderRpc, OnewayCallQueueing) {
924 if (clientOrServerSingleThreaded()) {
925 GTEST_SKIP() << "This test requires multiple threads";
926 }
927
Steven Moreland5553ac42020-11-11 02:14:45 +0000928 constexpr size_t kNumSleeps = 10;
929 constexpr size_t kNumExtraServerThreads = 4;
930 constexpr size_t kSleepMs = 50;
931
932 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000933 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000934
935 EXPECT_OK(proc.rootIface->lock());
936
Steven Moreland1c678802021-09-17 16:48:47 -0700937 size_t epochMsBefore = epochMillis();
938
939 // all these *Async commands should be queued on the server sequentially,
940 // even though there are multiple threads.
941 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000942 proc.rootIface->sleepMsAsync(kSleepMs);
943 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000944 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
945
Steven Moreland1c678802021-09-17 16:48:47 -0700946 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000947 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700948
Steven Moreland5553ac42020-11-11 02:14:45 +0000949 size_t epochMsAfter = epochMillis();
950
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000951 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000952
Steven Moreland925ba0a2021-09-17 18:06:32 -0700953 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000954}
955
Andrei Homescua858b0e2022-08-01 23:43:09 +0000956TEST_P(BinderRpc, OnewayCallExhaustion) {
957 if (clientOrServerSingleThreaded()) {
958 GTEST_SKIP() << "This test requires multiple threads";
959 }
960
Steven Morelandd45be622021-06-04 02:19:37 +0000961 constexpr size_t kNumClients = 2;
962 constexpr size_t kTooLongMs = 1000;
963
Steven Moreland4313d7e2021-07-15 23:41:22 +0000964 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000965
966 // Build up oneway calls on the second session to make sure it terminates
967 // and shuts down. The first session should be unaffected (proc destructor
968 // checks the first session).
969 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
970
971 std::vector<std::thread> threads;
972 for (size_t i = 0; i < kNumClients; i++) {
973 // one of these threads will get stuck queueing a transaction once the
974 // socket fills up, the other will be able to fill up transactions on
975 // this object
976 threads.push_back(std::thread([&] {
977 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
978 }
979 }));
980 }
981 for (auto& t : threads) t.join();
982
983 Status status = iface->sleepMsAsync(kTooLongMs);
984 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
985
Steven Moreland798e0d12021-07-14 23:19:25 +0000986 // now that it has died, wait for the remote session to shutdown
987 std::vector<int32_t> remoteCounts;
988 do {
989 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
990 } while (remoteCounts.size() == kNumClients);
991
Steven Morelandd45be622021-06-04 02:19:37 +0000992 // the second session should be shutdown in the other process by the time we
993 // are able to join above (it'll only be hung up once it finishes processing
994 // any pending commands). We need to erase this session from the record
995 // here, so that the destructor for our session won't check that this
996 // session is valid, but we still want it to test the other session.
997 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
998}
999
Steven Moreland659416d2021-05-11 00:47:50 +00001000TEST_P(BinderRpc, Callbacks) {
1001 const static std::string kTestString = "good afternoon!";
1002
Steven Morelandc7d40132021-06-10 03:42:11 +00001003 for (bool callIsOneway : {true, false}) {
1004 for (bool callbackIsOneway : {true, false}) {
1005 for (bool delayed : {true, false}) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001006 if (clientOrServerSingleThreaded() &&
1007 (callIsOneway || callbackIsOneway || delayed)) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001008 // we have no incoming connections to receive the callback
1009 continue;
1010 }
1011
Andrei Homescua858b0e2022-08-01 23:43:09 +00001012 size_t numIncomingConnections = clientOrServerSingleThreaded() ? 0 : 1;
Steven Moreland4313d7e2021-07-15 23:41:22 +00001013 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +00001014 {.numThreads = 1,
1015 .numSessions = 1,
Andrei Homescu2a298012022-06-15 01:08:54 +00001016 .numIncomingConnections = numIncomingConnections});
Steven Morelandc7d40132021-06-10 03:42:11 +00001017 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001018
Steven Morelandc7d40132021-06-10 03:42:11 +00001019 if (callIsOneway) {
1020 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1021 kTestString));
1022 } else {
1023 EXPECT_OK(
1024 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1025 }
Steven Moreland659416d2021-05-11 00:47:50 +00001026
Steven Moreland03ecce62022-05-13 23:22:05 +00001027 // if both transactions are synchronous and the response is sent back on the
1028 // same thread, everything should have happened in a nested call. Otherwise,
1029 // the callback will be processed on another thread.
1030 if (callIsOneway || callbackIsOneway || delayed) {
1031 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001032 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001033 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1034 }
Steven Moreland659416d2021-05-11 00:47:50 +00001035
Steven Morelandc7d40132021-06-10 03:42:11 +00001036 EXPECT_EQ(cb->mValues.size(), 1)
1037 << "callIsOneway: " << callIsOneway
1038 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1039 if (cb->mValues.empty()) continue;
1040 EXPECT_EQ(cb->mValues.at(0), kTestString)
1041 << "callIsOneway: " << callIsOneway
1042 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001043
Steven Morelandc7d40132021-06-10 03:42:11 +00001044 // since we are severing the connection, we need to go ahead and
1045 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001046 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1047 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1048 }
Steven Moreland659416d2021-05-11 00:47:50 +00001049
Steven Moreland1b304292021-07-15 22:59:34 +00001050 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001051 // need to manually shut it down
1052 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Morelandc7d40132021-06-10 03:42:11 +00001053 proc.expectAlreadyShutdown = true;
1054 }
Steven Moreland659416d2021-05-11 00:47:50 +00001055 }
1056 }
1057}
1058
Devin Moore66d5b7a2022-07-07 21:42:10 +00001059TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001060 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001061 GTEST_SKIP() << "This test requires multiple threads";
1062 }
1063 class MyDeathRec : public IBinder::DeathRecipient {
1064 public:
1065 void binderDied(const wp<IBinder>& /* who */) override {
1066 dead = true;
1067 mCv.notify_one();
1068 }
1069 std::mutex mMtx;
1070 std::condition_variable mCv;
1071 bool dead = false;
1072 };
1073
1074 // Death recipient needs to have an incoming connection to be called
1075 auto proc = createRpcTestSocketServerProcess(
1076 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1077
1078 auto dr = sp<MyDeathRec>::make();
1079 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1080
1081 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1082 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1083 }
1084
1085 std::unique_lock<std::mutex> lock(dr->mMtx);
Devin Moore47a12012022-08-19 21:16:17 +00001086 ASSERT_TRUE(dr->mCv.wait_for(lock, 1000ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001087
1088 // need to wait for the session to shutdown so we don't "Leak session"
1089 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1090 proc.expectAlreadyShutdown = true;
1091}
1092
1093TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001094 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001095 GTEST_SKIP() << "This test requires multiple threads";
1096 }
1097 class MyDeathRec : public IBinder::DeathRecipient {
1098 public:
1099 void binderDied(const wp<IBinder>& /* who */) override {
1100 dead = true;
1101 mCv.notify_one();
1102 }
1103 std::mutex mMtx;
1104 std::condition_variable mCv;
1105 bool dead = false;
1106 };
1107
1108 // Death recipient needs to have an incoming connection to be called
1109 auto proc = createRpcTestSocketServerProcess(
1110 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1111
1112 auto dr = sp<MyDeathRec>::make();
1113 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1114
1115 // Explicitly calling shutDownAndWait will cause the death recipients
1116 // to be called.
1117 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1118
1119 std::unique_lock<std::mutex> lock(dr->mMtx);
1120 if (!dr->dead) {
1121 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1122 }
1123 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1124
1125 proc.proc.host.terminate();
1126 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1127 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1128 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1129 });
1130 proc.expectAlreadyShutdown = true;
1131}
1132
1133TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1134 class MyDeathRec : public IBinder::DeathRecipient {
1135 public:
1136 void binderDied(const wp<IBinder>& /* who */) override {}
1137 };
1138
1139 auto proc = createRpcTestSocketServerProcess(
1140 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1141
1142 auto dr = sp<MyDeathRec>::make();
1143 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1144 "Cannot register a DeathRecipient without any incoming connections.");
1145}
1146
1147TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001148 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001149 GTEST_SKIP() << "This test requires multiple threads";
1150 }
1151 class MyDeathRec : public IBinder::DeathRecipient {
1152 public:
1153 void binderDied(const wp<IBinder>& /* who */) override {
1154 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1155 }
1156 };
1157
1158 // Death recipient needs to have an incoming connection to be called
1159 auto proc = createRpcTestSocketServerProcess(
1160 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1161
1162 auto dr = sp<MyDeathRec>::make();
1163 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1164 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1165
1166 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1167 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1168 }
1169
1170 // need to wait for the session to shutdown so we don't "Leak session"
1171 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1172 proc.expectAlreadyShutdown = true;
1173}
1174
Steven Moreland195edb82021-06-08 02:44:39 +00001175TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001176 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001177 auto cb = sp<MyBinderRpcCallback>::make();
1178
1179 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1180 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1181}
1182
Steven Morelandc1635952021-04-01 16:20:47 +00001183TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001184 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001185 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001186
1187 // make sure there is some state during crash
1188 // 1. we hold their binder
1189 sp<IBinderRpcSession> session;
1190 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1191 // 2. they hold our binder
1192 sp<IBinder> binder = new BBinder();
1193 EXPECT_OK(proc.rootIface->holdBinder(binder));
1194
1195 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1196 << "Do death cleanup: " << doDeathCleanup;
1197
Frederick Maylea12b0962022-06-25 01:13:22 +00001198 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1199 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1200 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1201 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001202 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001203 }
1204}
1205
Steven Morelandd7302072021-05-15 01:32:04 +00001206TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001207 // This test only works if the current process shared the internal state of
1208 // ProcessState with the service across the call to fork(). Both the static
1209 // libraries and libbinder.so have their own separate copies of all the
1210 // globals, so the test only works when the test client and service both use
1211 // libbinder.so (when using static libraries, even a client and service
1212 // using the same kind of static library should have separate copies of the
1213 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +00001214 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001215 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1216 "at build time.";
1217 }
1218
Steven Moreland4313d7e2021-07-15 23:41:22 +00001219 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001220
Andrei Homescu2a298012022-06-15 01:08:54 +00001221 // we can't allocate IPCThreadState so actually the first time should
1222 // succeed :(
1223 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001224
1225 // second time! we catch the error :)
1226 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1227
Frederick Maylea12b0962022-06-25 01:13:22 +00001228 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1229 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1230 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1231 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001232 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001233}
1234
Frederick Mayle69a0c992022-05-26 20:38:39 +00001235TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1236 auto proc = createRpcTestSocketServerProcess({
1237 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1238 .serverSupportedFileDescriptorTransportModes =
1239 {RpcSession::FileDescriptorTransportMode::UNIX},
1240 .allowConnectFailure = true,
1241 });
1242 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1243 proc.proc.host.terminate();
1244 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1245 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1246 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1247 });
1248 proc.expectAlreadyShutdown = true;
1249}
1250
1251TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1252 auto proc = createRpcTestSocketServerProcess({
1253 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1254 .serverSupportedFileDescriptorTransportModes =
1255 {RpcSession::FileDescriptorTransportMode::NONE},
1256 .allowConnectFailure = true,
1257 });
1258 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1259 proc.proc.host.terminate();
1260 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1261 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1262 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1263 });
1264 proc.expectAlreadyShutdown = true;
1265}
1266
1267TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1268 auto proc = createRpcTestSocketServerProcess({
1269 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1270 .serverSupportedFileDescriptorTransportModes =
1271 {RpcSession::FileDescriptorTransportMode::NONE,
1272 RpcSession::FileDescriptorTransportMode::UNIX},
1273 });
1274
1275 android::os::ParcelFileDescriptor out;
1276 auto status = proc.rootIface->echoAsFile("hello", &out);
1277 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1278}
1279
1280TEST_P(BinderRpc, ReceiveFile) {
1281 auto proc = createRpcTestSocketServerProcess({
1282 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1283 .serverSupportedFileDescriptorTransportModes =
1284 {RpcSession::FileDescriptorTransportMode::UNIX},
1285 });
1286
1287 android::os::ParcelFileDescriptor out;
1288 auto status = proc.rootIface->echoAsFile("hello", &out);
1289 if (!supportsFdTransport()) {
1290 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1291 return;
1292 }
1293 ASSERT_TRUE(status.isOk()) << status;
1294
1295 std::string result;
1296 CHECK(android::base::ReadFdToString(out.get(), &result));
1297 EXPECT_EQ(result, "hello");
1298}
1299
1300TEST_P(BinderRpc, SendFiles) {
1301 auto proc = createRpcTestSocketServerProcess({
1302 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1303 .serverSupportedFileDescriptorTransportModes =
1304 {RpcSession::FileDescriptorTransportMode::UNIX},
1305 });
1306
1307 std::vector<android::os::ParcelFileDescriptor> files;
1308 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1309 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1310 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1311 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1312
1313 android::os::ParcelFileDescriptor out;
1314 auto status = proc.rootIface->concatFiles(files, &out);
1315 if (!supportsFdTransport()) {
1316 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1317 return;
1318 }
1319 ASSERT_TRUE(status.isOk()) << status;
1320
1321 std::string result;
1322 CHECK(android::base::ReadFdToString(out.get(), &result));
1323 EXPECT_EQ(result, "123abcd");
1324}
1325
1326TEST_P(BinderRpc, SendMaxFiles) {
1327 if (!supportsFdTransport()) {
1328 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1329 }
1330
1331 auto proc = createRpcTestSocketServerProcess({
1332 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1333 .serverSupportedFileDescriptorTransportModes =
1334 {RpcSession::FileDescriptorTransportMode::UNIX},
1335 });
1336
1337 std::vector<android::os::ParcelFileDescriptor> files;
1338 for (int i = 0; i < 253; i++) {
1339 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1340 }
1341
1342 android::os::ParcelFileDescriptor out;
1343 auto status = proc.rootIface->concatFiles(files, &out);
1344 ASSERT_TRUE(status.isOk()) << status;
1345
1346 std::string result;
1347 CHECK(android::base::ReadFdToString(out.get(), &result));
1348 EXPECT_EQ(result, std::string(253, 'a'));
1349}
1350
1351TEST_P(BinderRpc, SendTooManyFiles) {
1352 if (!supportsFdTransport()) {
1353 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1354 }
1355
1356 auto proc = createRpcTestSocketServerProcess({
1357 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1358 .serverSupportedFileDescriptorTransportModes =
1359 {RpcSession::FileDescriptorTransportMode::UNIX},
1360 });
1361
1362 std::vector<android::os::ParcelFileDescriptor> files;
1363 for (int i = 0; i < 254; i++) {
1364 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1365 }
1366
1367 android::os::ParcelFileDescriptor out;
1368 auto status = proc.rootIface->concatFiles(files, &out);
1369 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1370}
1371
Steven Moreland37aff182021-03-26 02:04:16 +00001372TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001373 if constexpr (!kEnableSharedLibs) {
1374 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1375 }
1376
Steven Moreland4313d7e2021-07-15 23:41:22 +00001377 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001378
1379 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1380 ASSERT_NE(binder, nullptr);
1381
1382 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1383}
1384
1385TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001386 if constexpr (!kEnableSharedLibs) {
1387 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1388 }
1389
Steven Moreland4313d7e2021-07-15 23:41:22 +00001390 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001391
1392 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1393 ASSERT_NE(binder, nullptr);
1394
1395 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1396 ASSERT_NE(ndkBinder, nullptr);
1397
1398 std::string out;
1399 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1400 ASSERT_TRUE(status.isOk()) << status.getDescription();
1401 ASSERT_EQ("aoeuaoeu", out);
1402}
1403
Steven Moreland5553ac42020-11-11 02:14:45 +00001404ssize_t countFds() {
1405 DIR* dir = opendir("/proc/self/fd/");
1406 if (dir == nullptr) return -1;
1407 ssize_t ret = 0;
1408 dirent* ent;
1409 while ((ent = readdir(dir)) != nullptr) ret++;
1410 closedir(dir);
1411 return ret;
1412}
1413
Andrei Homescua858b0e2022-08-01 23:43:09 +00001414TEST_P(BinderRpc, Fds) {
1415 if (serverSingleThreaded()) {
1416 GTEST_SKIP() << "This test requires multiple threads";
1417 }
1418
Steven Moreland5553ac42020-11-11 02:14:45 +00001419 ssize_t beforeFds = countFds();
1420 ASSERT_GE(beforeFds, 0);
1421 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001422 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001423 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1424 }
1425 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1426}
1427
Devin Moore800b2252021-10-15 16:22:57 +00001428TEST_P(BinderRpc, AidlDelegatorTest) {
1429 auto proc = createRpcTestSocketServerProcess({});
1430 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1431 ASSERT_NE(nullptr, myDelegator);
1432
1433 std::string doubled;
1434 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1435 EXPECT_EQ("cool cool ", doubled);
1436}
1437
Steven Morelandda573042021-06-12 01:13:45 +00001438static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001439 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001440 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001441
Andrei Homescu992a4052022-06-28 21:26:18 +00001442 android::base::unique_fd serverFd(
1443 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1444 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1445
1446 sockaddr_vm serverAddr{
1447 .svm_family = AF_VSOCK,
1448 .svm_port = vsockPort,
1449 .svm_cid = VMADDR_CID_ANY,
1450 };
1451 int ret = TEMP_FAILURE_RETRY(
1452 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1453 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1454 strerror(errno));
1455
1456 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1457 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1458 strerror(errno));
1459
1460 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1461 // to see if the kernel supports it. It's safe to use a blocking
1462 // connect because vsock sockets have a 2 second connection timeout,
1463 // and they return ETIMEDOUT after that.
1464 android::base::unique_fd connectFd(
1465 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1466 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1467 strerror(errno));
1468
1469 bool success = false;
1470 sockaddr_vm connectAddr{
1471 .svm_family = AF_VSOCK,
1472 .svm_port = vsockPort,
1473 .svm_cid = VMADDR_CID_LOCAL,
1474 };
1475 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1476 sizeof(connectAddr)));
1477 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1478 android::base::unique_fd acceptFd;
1479 while (true) {
1480 pollfd pfd[]{
1481 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1482 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1483 };
1484 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1485 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1486
1487 if (pfd[0].revents & POLLIN) {
1488 sockaddr_vm acceptAddr;
1489 socklen_t acceptAddrLen = sizeof(acceptAddr);
1490 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1491 reinterpret_cast<sockaddr*>(&acceptAddr),
1492 &acceptAddrLen, SOCK_CLOEXEC));
1493 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1494 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1495 "Truncated address");
1496
1497 // Store the fd in acceptFd so we keep the connection alive
1498 // while polling connectFd
1499 acceptFd.reset(ret);
1500 }
1501
1502 if (pfd[1].revents & POLLOUT) {
1503 // Connect either succeeded or timed out
1504 int connectErrno;
1505 socklen_t connectErrnoLen = sizeof(connectErrno);
1506 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1507 &connectErrnoLen);
1508 LOG_ALWAYS_FATAL_IF(ret == -1,
1509 "Could not getsockopt() after connect() "
1510 "on non-blocking socket: %s.",
1511 strerror(errno));
1512
1513 // We're done, this is all we wanted
1514 success = connectErrno == 0;
1515 break;
1516 }
1517 }
1518 } else {
1519 success = ret == 0;
1520 }
1521
1522 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1523
1524 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001525}
1526
Yifan Hong1deca4b2021-09-10 16:16:44 -07001527static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1528 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1529
1530 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001531
1532 static bool hasVsockLoopback = testSupportVsockLoopback();
1533
1534 if (hasVsockLoopback) {
1535 ret.push_back(SocketType::VSOCK);
1536 }
1537
1538 return ret;
1539}
1540
Frederick Mayledc07cf82022-05-26 20:30:12 +00001541static std::vector<uint32_t> testVersions() {
1542 std::vector<uint32_t> versions;
1543 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1544 versions.push_back(i);
1545 }
1546 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1547 return versions;
1548}
1549
Yifan Hong702115c2021-06-24 15:39:18 -07001550INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1551 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001552 ::testing::ValuesIn(RpcSecurityValues()),
1553 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001554 ::testing::ValuesIn(testVersions()),
1555 ::testing::Values(false, true),
1556 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001557 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001558
Yifan Hong702115c2021-06-24 15:39:18 -07001559class BinderRpcServerRootObject
1560 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001561
1562TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1563 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1564 auto setRootObject = [](bool isStrong) -> SetFn {
1565 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1566 };
1567
Yifan Hong702115c2021-06-24 15:39:18 -07001568 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1569 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001570 auto binder1 = sp<BBinder>::make();
1571 IBinder* binderRaw1 = binder1.get();
1572 setRootObject(isStrong1)(server.get(), binder1);
1573 EXPECT_EQ(binderRaw1, server->getRootObject());
1574 binder1.clear();
1575 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1576
1577 auto binder2 = sp<BBinder>::make();
1578 IBinder* binderRaw2 = binder2.get();
1579 setRootObject(isStrong2)(server.get(), binder2);
1580 EXPECT_EQ(binderRaw2, server->getRootObject());
1581 binder2.clear();
1582 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1583}
1584
1585INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001586 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1587 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001588
Yifan Hong1a235852021-05-13 16:07:47 -07001589class OneOffSignal {
1590public:
1591 // If notify() was previously called, or is called within |duration|, return true; else false.
1592 template <typename R, typename P>
1593 bool wait(std::chrono::duration<R, P> duration) {
1594 std::unique_lock<std::mutex> lock(mMutex);
1595 return mCv.wait_for(lock, duration, [this] { return mValue; });
1596 }
1597 void notify() {
1598 std::unique_lock<std::mutex> lock(mMutex);
1599 mValue = true;
1600 lock.unlock();
1601 mCv.notify_all();
1602 }
1603
1604private:
1605 std::mutex mMutex;
1606 std::condition_variable mCv;
1607 bool mValue = false;
1608};
1609
Yifan Hong194acf22021-06-29 18:44:56 -07001610TEST(BinderRpc, Java) {
1611#if !defined(__ANDROID__)
1612 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1613 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1614 "to binderHostDeviceTest. Hence, just disable this test on host.";
1615#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001616 if constexpr (!kEnableKernelIpc) {
1617 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1618 "at build time.";
1619 }
1620
Yifan Hong194acf22021-06-29 18:44:56 -07001621 sp<IServiceManager> sm = defaultServiceManager();
1622 ASSERT_NE(nullptr, sm);
1623 // Any Java service with non-empty getInterfaceDescriptor() would do.
1624 // Let's pick batteryproperties.
1625 auto binder = sm->checkService(String16("batteryproperties"));
1626 ASSERT_NE(nullptr, binder);
1627 auto descriptor = binder->getInterfaceDescriptor();
1628 ASSERT_GE(descriptor.size(), 0);
1629 ASSERT_EQ(OK, binder->pingBinder());
1630
1631 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001632 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001633 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001634 auto socket = rpcServer->releaseServer();
1635
1636 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001637 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1638
Yifan Honge3caaf22022-01-12 14:46:56 -08001639 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1640 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001641 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001642 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1643 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001644 << statusToString(setRpcClientDebugStatus);
1645 GTEST_SKIP();
1646 }
1647
1648 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001649
1650 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001651 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001652 auto rpcBinder = rpcSession->getRootObject();
1653 ASSERT_NE(nullptr, rpcBinder);
1654
1655 ASSERT_EQ(OK, rpcBinder->pingBinder());
1656
1657 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1658 << "getInterfaceDescriptor should not crash system_server";
1659 ASSERT_EQ(OK, rpcBinder->pingBinder());
1660}
1661
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001662class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1663public:
1664 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1665 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1666 std::to_string(std::get<1>(info.param));
1667 }
1668};
1669
1670TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1671 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1672 int sinkFd = sink.get();
1673 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1674 server->setProtocolVersion(std::get<1>(GetParam()));
1675 ASSERT_FALSE(server->hasServer());
1676 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1677 ASSERT_TRUE(server->hasServer());
1678 base::unique_fd retrieved = server->releaseServer();
1679 ASSERT_FALSE(server->hasServer());
1680 ASSERT_EQ(sinkFd, retrieved.get());
1681}
1682
1683TEST_P(BinderRpcServerOnly, Shutdown) {
1684 if constexpr (!kEnableRpcThreads) {
1685 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1686 }
1687
1688 auto addr = allocateSocketAddress();
1689 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1690 server->setProtocolVersion(std::get<1>(GetParam()));
1691 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1692 auto joinEnds = std::make_shared<OneOffSignal>();
1693
1694 // If things are broken and the thread never stops, don't block other tests. Because the thread
1695 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1696 // shared pointers are passed.
1697 std::thread([server, joinEnds] {
1698 server->join();
1699 joinEnds->notify();
1700 }).detach();
1701
1702 bool shutdown = false;
1703 for (int i = 0; i < 10 && !shutdown; i++) {
1704 usleep(300 * 1000); // 300ms; total 3s
1705 if (server->shutdown()) shutdown = true;
1706 }
1707 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1708
1709 ASSERT_TRUE(joinEnds->wait(2s))
1710 << "After server->shutdown() returns true, join() did not stop after 2s";
1711}
1712
Frederick Mayledc07cf82022-05-26 20:30:12 +00001713INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1714 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1715 ::testing::ValuesIn(testVersions())),
1716 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001717
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001718class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001719public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001720 // Only parameterized only server version because `RpcSession` is bypassed
1721 // in the client half of the tests.
1722 using Param =
1723 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001724 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001725
1726 // A server that handles client socket connections.
1727 class Server {
1728 public:
1729 explicit Server() {}
1730 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001731 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001732 [[nodiscard]] AssertionResult setUp(
1733 const Param& param,
1734 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001735 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001736 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001737 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001738 switch (socketType) {
1739 case SocketType::PRECONNECTED: {
1740 return AssertionFailure() << "Not supported by this test";
1741 } break;
1742 case SocketType::UNIX: {
1743 auto addr = allocateSocketAddress();
1744 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1745 if (status != OK) {
1746 return AssertionFailure()
1747 << "setupUnixDomainServer: " << statusToString(status);
1748 }
1749 mConnectToServer = [addr] {
1750 return connectTo(UnixSocketAddress(addr.c_str()));
1751 };
1752 } break;
1753 case SocketType::VSOCK: {
1754 auto port = allocateVsockPort();
1755 auto status = rpcServer->setupVsockServer(port);
1756 if (status != OK) {
1757 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1758 }
1759 mConnectToServer = [port] {
1760 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1761 };
1762 } break;
1763 case SocketType::INET: {
1764 unsigned int port;
1765 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1766 if (status != OK) {
1767 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1768 }
1769 mConnectToServer = [port] {
1770 const char* addr = kLocalInetAddress;
1771 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1772 if (aiStart == nullptr) return base::unique_fd{};
1773 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1774 auto fd = connectTo(
1775 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1776 if (fd.ok()) return fd;
1777 }
1778 ALOGE("None of the socket address resolved for %s:%u can be connected",
1779 addr, port);
1780 return base::unique_fd{};
1781 };
1782 }
1783 }
1784 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001785 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001786 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001787 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1788 mSetup = true;
1789 return AssertionSuccess();
1790 }
1791 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1792 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1793 return mCertVerifier;
1794 }
1795 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1796 void start() {
1797 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1798 mThread = std::make_unique<std::thread>(&Server::run, this);
1799 }
1800 void run() {
1801 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1802
1803 std::vector<std::thread> threads;
1804 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1805 base::unique_fd acceptedFd(
Pawan49d74cb2022-08-03 21:19:11 +00001806 TEMP_FAILURE_RETRY(accept4(mFd.fd.get(), nullptr, nullptr /*length*/,
Yifan Hong1deca4b2021-09-10 16:16:44 -07001807 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1808 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1809 }
1810
1811 for (auto& thread : threads) thread.join();
1812 }
1813 void handleOne(android::base::unique_fd acceptedFd) {
1814 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001815 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001816 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001817 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001818 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001819 }
Yifan Honge07d2732021-09-13 21:59:14 -07001820 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001821 shutdown();
1822 join();
1823 }
1824 void shutdown() { mFdTrigger->trigger(); }
1825
1826 void setPostConnect(
1827 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1828 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001829 }
1830
1831 private:
1832 std::unique_ptr<std::thread> mThread;
1833 ConnectToServer mConnectToServer;
1834 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
Pawan3e0061c2022-08-26 21:08:34 +00001835 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001836 std::unique_ptr<RpcTransportCtx> mCtx;
1837 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1838 std::make_shared<RpcCertificateVerifierSimple>();
1839 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001840 // The function invoked after connection and handshake. By default, it is
1841 // |defaultPostConnect| that sends |kMessage| to the client.
1842 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1843 Server::defaultPostConnect;
1844
1845 void join() {
1846 if (mThread != nullptr) {
1847 mThread->join();
1848 mThread = nullptr;
1849 }
1850 }
1851
1852 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1853 FdTrigger* fdTrigger) {
1854 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001855 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001856 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001857 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001858 if (status != OK) return AssertionFailure() << statusToString(status);
1859 return AssertionSuccess();
1860 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001861 };
1862
1863 class Client {
1864 public:
1865 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1866 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001867 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001868 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1869 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001870 mFdTrigger = FdTrigger::make();
1871 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1872 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1873 return AssertionSuccess();
1874 }
1875 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1876 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1877 return mCertVerifier;
1878 }
Yifan Hong67519322021-09-13 18:51:16 -07001879 // connect() and do handshake
1880 bool setUpTransport() {
1881 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001882 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001883 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1884 return mClientTransport != nullptr;
1885 }
1886 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1887 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1888 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001889 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001890 status_t readStatus =
1891 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001892 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001893 if (readStatus != OK) {
1894 return AssertionFailure() << statusToString(readStatus);
1895 }
1896 if (readMessage != expectedMessage) {
1897 return AssertionFailure()
1898 << "Expected " << expectedMessage << ", actual " << readMessage;
1899 }
1900 return AssertionSuccess();
1901 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001902 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001903 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001904 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1905 return;
1906 }
1907 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001908 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001909 }
1910
Pawan49d74cb2022-08-03 21:19:11 +00001911 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1912
Yifan Hong1deca4b2021-09-10 16:16:44 -07001913 private:
1914 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001915 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001916 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1917 std::unique_ptr<RpcTransportCtx> mCtx;
1918 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1919 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001920 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001921 };
1922
1923 // Make A trust B.
1924 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001925 static status_t trust(RpcSecurity rpcSecurity,
1926 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1927 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001928 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001929 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1930 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1931 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001932 }
1933
1934 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001935};
1936
1937class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1938public:
1939 using Server = RpcTransportTestUtils::Server;
1940 using Client = RpcTransportTestUtils::Client;
1941 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001942 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001943 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1944 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001945 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001946 return ret;
1947 }
1948 static std::vector<ParamType> getRpcTranportTestParams() {
1949 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001950 for (auto serverVersion : testVersions()) {
1951 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1952 for (auto rpcSecurity : RpcSecurityValues()) {
1953 switch (rpcSecurity) {
1954 case RpcSecurity::RAW: {
1955 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1956 } break;
1957 case RpcSecurity::TLS: {
1958 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1959 serverVersion);
1960 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1961 serverVersion);
1962 } break;
1963 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001964 }
1965 }
1966 }
1967 return ret;
1968 }
1969 template <typename A, typename B>
1970 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001971 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1972 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001973 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1974 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001975 void SetUp() override {
1976 if constexpr (!kEnableRpcThreads) {
1977 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1978 }
1979 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001980};
1981
1982TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001983 auto server = std::make_unique<Server>();
1984 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001985
1986 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001987 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001988
1989 ASSERT_EQ(OK, trust(&client, server));
1990 ASSERT_EQ(OK, trust(server, &client));
1991
1992 server->start();
1993 client.run();
1994}
1995
1996TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001997 auto server = std::make_unique<Server>();
1998 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001999
2000 std::vector<Client> clients;
2001 for (int i = 0; i < 2; i++) {
2002 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002003 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002004 ASSERT_EQ(OK, trust(&client, server));
2005 ASSERT_EQ(OK, trust(server, &client));
2006 }
2007
2008 server->start();
2009 for (auto& client : clients) client.run();
2010}
2011
2012TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002013 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2014 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002015
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002016 auto untrustedServer = std::make_unique<Server>();
2017 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002018
2019 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002020 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002021
2022 ASSERT_EQ(OK, trust(untrustedServer, &client));
2023
2024 untrustedServer->start();
2025
2026 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2027 // the client can't verify the server's identity.
2028 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2029 client.run(handshakeOk);
2030}
2031TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002032 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2033 (void)serverVersion;
2034
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002035 auto validServer = std::make_unique<Server>();
2036 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002037
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002038 auto maliciousServer = std::make_unique<Server>();
2039 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002040
2041 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002042 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002043
2044 ASSERT_EQ(OK, trust(&client, validServer));
2045 ASSERT_EQ(OK, trust(validServer, &client));
2046 ASSERT_EQ(OK, trust(maliciousServer, &client));
2047
2048 maliciousServer->start();
2049
2050 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2051 // the client can't verify the server's identity.
2052 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2053 client.run(handshakeOk);
2054}
2055
2056TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002057 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2058 (void)serverVersion;
2059
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002060 auto server = std::make_unique<Server>();
2061 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002062
2063 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002064 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002065
2066 ASSERT_EQ(OK, trust(&client, server));
2067
2068 server->start();
2069
2070 // For TLS, Client should be able to verify server's identity, so client should see
2071 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2072 // identity and should drop the connection, so client shouldn't be able to read anything.
2073 bool readOk = rpcSecurity != RpcSecurity::TLS;
2074 client.run(true, readOk);
2075}
2076
2077TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002078 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2079 (void)serverVersion;
2080
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002081 auto server = std::make_unique<Server>();
2082 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002083
2084 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002085 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002086 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002087 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002088
2089 ASSERT_EQ(OK, trust(&validClient, server));
2090 ASSERT_EQ(OK, trust(&maliciousClient, server));
2091
2092 server->start();
2093
2094 // See UntrustedClient.
2095 bool readOk = rpcSecurity != RpcSecurity::TLS;
2096 maliciousClient.run(true, readOk);
2097}
2098
Yifan Hong67519322021-09-13 18:51:16 -07002099TEST_P(RpcTransportTest, Trigger) {
2100 std::string msg2 = ", world!";
2101 std::mutex writeMutex;
2102 std::condition_variable writeCv;
2103 bool shouldContinueWriting = false;
2104 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002105 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002106 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002107 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2108 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002109 if (status != OK) return AssertionFailure() << statusToString(status);
2110
2111 {
2112 std::unique_lock<std::mutex> lock(writeMutex);
2113 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2114 return AssertionFailure() << "write barrier not cleared in time!";
2115 }
2116 }
2117
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002118 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002119 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2120 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002121 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002122 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002123 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002124 << statusToString(status);
2125 return AssertionSuccess();
2126 };
2127
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002128 auto server = std::make_unique<Server>();
2129 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002130
2131 // Set up client
2132 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002133 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002134
2135 // Exchange keys
2136 ASSERT_EQ(OK, trust(&client, server));
2137 ASSERT_EQ(OK, trust(server, &client));
2138
2139 server->setPostConnect(serverPostConnect);
2140
Yifan Hong67519322021-09-13 18:51:16 -07002141 server->start();
2142 // connect() to server and do handshake
2143 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002144 // read the first message. This ensures that server has finished handshake and start handling
2145 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002146 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002147 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2148 // write is on an FdTrigger that has been shut down.
2149 server->shutdown();
2150 // Continues server thread to write the second message.
2151 {
Yifan Hong22211f82021-09-14 12:32:25 -07002152 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002153 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002154 }
Yifan Hong22211f82021-09-14 12:32:25 -07002155 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002156 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002157 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002158 // On the client side, second read fails with DEAD_OBJECT
2159 ASSERT_FALSE(client.readMessage(msg2));
2160}
2161
Pawan49d74cb2022-08-03 21:19:11 +00002162TEST_P(RpcTransportTest, CheckWaitingForRead) {
2163 std::mutex readMutex;
2164 std::condition_variable readCv;
2165 bool shouldContinueReading = false;
2166 // Server will write data on transport once its started
2167 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
2168 std::string message(RpcTransportTestUtils::kMessage);
2169 iovec messageIov{message.data(), message.size()};
2170 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2171 std::nullopt, nullptr);
2172 if (status != OK) return AssertionFailure() << statusToString(status);
2173
2174 {
2175 std::unique_lock<std::mutex> lock(readMutex);
2176 shouldContinueReading = true;
2177 lock.unlock();
2178 readCv.notify_all();
2179 }
2180 return AssertionSuccess();
2181 };
2182
2183 // Setup Server and client
2184 auto server = std::make_unique<Server>();
2185 ASSERT_TRUE(server->setUp(GetParam()));
2186
2187 Client client(server->getConnectToServerFn());
2188 ASSERT_TRUE(client.setUp(GetParam()));
2189
2190 ASSERT_EQ(OK, trust(&client, server));
2191 ASSERT_EQ(OK, trust(server, &client));
2192 server->setPostConnect(serverPostConnect);
2193
2194 server->start();
2195 ASSERT_TRUE(client.setUpTransport());
2196 {
2197 // Wait till server writes data
2198 std::unique_lock<std::mutex> lock(readMutex);
2199 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2200 }
2201
2202 // Since there is no read polling here, we will get polling count 0
2203 ASSERT_FALSE(client.isTransportWaiting());
2204 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2205 // Thread should increment polling count, read and decrement polling count
2206 // Again, polling count should be zero here
2207 ASSERT_FALSE(client.isTransportWaiting());
2208
2209 server->shutdown();
2210}
2211
Yifan Hong1deca4b2021-09-10 16:16:44 -07002212INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002213 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002214 RpcTransportTest::PrintParamInfo);
2215
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002216class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002217 : public testing::TestWithParam<
2218 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002219public:
2220 template <typename A, typename B>
2221 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002222 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2223 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002224 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2225 }
2226 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002227 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2228 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2229 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002230 };
2231};
2232
2233TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002234 if constexpr (!kEnableRpcThreads) {
2235 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2236 }
2237
Frederick Mayledc07cf82022-05-26 20:30:12 +00002238 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002239
2240 std::vector<uint8_t> pkeyData, certData;
2241 {
2242 auto pkey = makeKeyPairForSelfSignedCert();
2243 ASSERT_NE(nullptr, pkey);
2244 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2245 ASSERT_NE(nullptr, cert);
2246 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2247 certData = serializeCertificate(cert.get(), certificateFormat);
2248 }
2249
2250 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2251 auto desCert = deserializeCertificate(certData, certificateFormat);
2252 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002253 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2254 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002255
2256 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2257 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2258
2259 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2260 ASSERT_TRUE(client.setUp(utilsParam));
2261
2262 ASSERT_EQ(OK, trust(&client, server));
2263 ASSERT_EQ(OK, trust(server, &client));
2264
2265 server->start();
2266 client.run();
2267}
2268
2269INSTANTIATE_TEST_CASE_P(
2270 BinderRpc, RpcTransportTlsKeyTest,
2271 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2272 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002273 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2274 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002275 RpcTransportTlsKeyTest::PrintParamInfo);
2276
Steven Morelandc1635952021-04-01 16:20:47 +00002277} // namespace android
2278
2279int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002280 ::testing::InitGoogleTest(&argc, argv);
2281 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002282
Steven Moreland5553ac42020-11-11 02:14:45 +00002283 return RUN_ALL_TESTS();
2284}