blob: 499fdd27730e25087884d306673341b53d1138a9 [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Frederick Maylea12b0962022-06-25 01:13:22 +000017#include <android-base/stringprintf.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000018#include <gtest/gtest.h>
19
Steven Morelandc1635952021-04-01 16:20:47 +000020#include <chrono>
21#include <cstdlib>
22#include <iostream>
23#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000024#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000025
Andrei Homescu2a298012022-06-15 01:08:54 +000026#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070027#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000029#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000030
Andrei Homescu2a298012022-06-15 01:08:54 +000031#include "binderRpcTestCommon.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000032
Yifan Hong1a235852021-05-13 16:07:47 -070033using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070034using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070035using testing::AssertionFailure;
36using testing::AssertionResult;
37using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070038
Steven Moreland5553ac42020-11-11 02:14:45 +000039namespace android {
40
Andrei Homescu12106de2022-04-27 04:42:21 +000041#ifdef BINDER_TEST_NO_SHARED_LIBS
42constexpr bool kEnableSharedLibs = false;
43#else
44constexpr bool kEnableSharedLibs = true;
45#endif
46
Steven Morelandbf57bce2021-07-26 15:26:12 -070047static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
48 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Frederick Mayle69a0c992022-05-26 20:38:39 +000049
Steven Moreland1fda67b2021-04-02 18:35:50 +000050TEST(BinderRpcParcel, EntireParcelFormatted) {
51 Parcel p;
52 p.writeInt32(3);
53
Devin Moore66d5b7a2022-07-07 21:42:10 +000054 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "format must be set before data is written");
Steven Moreland1fda67b2021-04-02 18:35:50 +000055}
56
Steven Morelandbf57bce2021-07-26 15:26:12 -070057TEST(BinderRpc, CannotUseNextWireVersion) {
58 auto session = RpcSession::make();
59 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
60 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
61 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
62 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
63}
64
65TEST(BinderRpc, CanUseExperimentalWireVersion) {
66 auto session = RpcSession::make();
67 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
68}
69
Steven Moreland5553ac42020-11-11 02:14:45 +000070using android::binder::Status;
71
72#define EXPECT_OK(status) \
73 do { \
74 Status stat = (status); \
75 EXPECT_TRUE(stat.isOk()) << stat; \
76 } while (false)
77
Frederick Maylea12b0962022-06-25 01:13:22 +000078static std::string WaitStatusToString(int wstatus) {
79 if (WIFEXITED(wstatus)) {
80 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
81 }
82 if (WIFSIGNALED(wstatus)) {
83 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
84 }
85 return base::StringPrintf("unexpected state %d", wstatus);
86}
87
Steven Moreland276d8df2022-09-28 23:56:39 +000088static void debugBacktrace(pid_t pid) {
89 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
90 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
91}
92
Steven Moreland5553ac42020-11-11 02:14:45 +000093class Process {
94public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -070095 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -070096 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
97 android::base::borrowed_fd /* readEnd */)>& f) {
98 android::base::unique_fd childWriteEnd;
99 android::base::unique_fd childReadEnd;
Andrei Homescu2a298012022-06-15 01:08:54 +0000100 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) << strerror(errno);
101 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000102 if (0 == (mPid = fork())) {
103 // racey: assume parent doesn't crash before this is set
104 prctl(PR_SET_PDEATHSIG, SIGHUP);
105
Yifan Hong1deca4b2021-09-10 16:16:44 -0700106 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000107
108 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000109 }
110 }
111 ~Process() {
112 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000113 int wstatus;
114 waitpid(mPid, &wstatus, 0);
115 if (mCustomExitStatusCheck) {
116 mCustomExitStatusCheck(wstatus);
117 } else {
118 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
119 << "server process failed: " << WaitStatusToString(wstatus);
120 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000121 }
122 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700123 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700124 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000125
Frederick Maylea12b0962022-06-25 01:13:22 +0000126 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
127 mCustomExitStatusCheck = std::move(f);
128 }
129
Frederick Mayle69a0c992022-05-26 20:38:39 +0000130 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
131 void terminate() { kill(mPid, SIGTERM); }
132
Steven Moreland276d8df2022-09-28 23:56:39 +0000133 pid_t getPid() { return mPid; }
134
Steven Moreland5553ac42020-11-11 02:14:45 +0000135private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000136 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000137 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700138 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700139 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000140};
141
142static std::string allocateSocketAddress() {
143 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000144 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700145 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
146 unlink(ret.c_str());
147 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000148};
149
Steven Morelandda573042021-06-12 01:13:45 +0000150static unsigned int allocateVsockPort() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000151 static unsigned int vsockPort = 34567;
Steven Morelandda573042021-06-12 01:13:45 +0000152 return vsockPort++;
153}
154
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000155struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000156 // reference to process hosting a socket server
157 Process host;
158
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000159 struct SessionInfo {
160 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000161 sp<IBinder> root;
162 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000163
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000164 // client session objects associated with other process
165 // each one represents a separate session
166 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000167
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000168 ProcessSession(ProcessSession&&) = default;
169 ~ProcessSession() {
170 for (auto& session : sessions) {
171 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000172 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000173
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000174 for (auto& info : sessions) {
175 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000176
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000177 EXPECT_NE(nullptr, session);
178 EXPECT_NE(nullptr, session->state());
179 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000180
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000181 wp<RpcSession> weakSession = session;
182 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000183
Steven Moreland57042712022-10-04 23:56:45 +0000184 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
185 // the object should not actually be promotable. By looping, we distinguish a race here
186 // from a bug causing the object to not be promotable.
187 for (size_t i = 0; i < 3; i++) {
188 sp<RpcSession> strongSession = weakSession.promote();
189 EXPECT_EQ(nullptr, strongSession)
190 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
191 "Leaked sess: ")
192 << strongSession->getStrongCount() << " checked time " << i;
193
194 if (strongSession != nullptr) {
195 sleep(1);
196 }
197 }
Steven Moreland736664b2021-05-01 04:27:25 +0000198 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000199 }
200};
201
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000202// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000203// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000204struct BinderRpcTestProcessSession {
205 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000206
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000207 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000208 sp<IBinder> rootBinder;
209
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000210 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000211 sp<IBinderRpcTest> rootIface;
212
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000213 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000214 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000215
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000216 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
217 ~BinderRpcTestProcessSession() {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000218 if (!expectAlreadyShutdown) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000219 EXPECT_NE(nullptr, rootIface);
220 if (rootIface == nullptr) return;
221
Steven Moreland736664b2021-05-01 04:27:25 +0000222 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000223 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000224 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000225 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000226 for (auto remoteCount : remoteCounts) {
227 EXPECT_EQ(remoteCount, 1);
228 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000229
Steven Moreland798e0d12021-07-14 23:19:25 +0000230 // even though it is on another thread, shutdown races with
231 // the transaction reply being written
232 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
233 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
234 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000235 }
236
237 rootIface = nullptr;
238 rootBinder = nullptr;
239 }
240};
241
Yifan Hong1deca4b2021-09-10 16:16:44 -0700242static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700243 base::unique_fd serverFd(
244 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
245 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700246 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
247 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700248
249 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
250 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700251 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
252 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700253 }
254 return serverFd;
255}
256
Andrei Homescu2a298012022-06-15 01:08:54 +0000257using RunServiceFn = void (*)(android::base::borrowed_fd writeEnd,
258 android::base::borrowed_fd readEnd);
259
260class BinderRpc : public ::testing::TestWithParam<
261 std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t, bool, bool>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000262public:
Frederick Mayle69a0c992022-05-26 20:38:39 +0000263 SocketType socketType() const { return std::get<0>(GetParam()); }
264 RpcSecurity rpcSecurity() const { return std::get<1>(GetParam()); }
265 uint32_t clientVersion() const { return std::get<2>(GetParam()); }
266 uint32_t serverVersion() const { return std::get<3>(GetParam()); }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000267 bool serverSingleThreaded() const { return std::get<4>(GetParam()); }
Andrei Homescu2a298012022-06-15 01:08:54 +0000268 bool noKernel() const { return std::get<5>(GetParam()); }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000269
Andrei Homescua858b0e2022-08-01 23:43:09 +0000270 bool clientOrServerSingleThreaded() const {
271 return !kEnableRpcThreads || serverSingleThreaded();
272 }
273
Frederick Mayle69a0c992022-05-26 20:38:39 +0000274 // Whether the test params support sending FDs in parcels.
275 bool supportsFdTransport() const {
276 return clientVersion() >= 1 && serverVersion() >= 1 && rpcSecurity() != RpcSecurity::TLS &&
277 (socketType() == SocketType::PRECONNECTED || socketType() == SocketType::UNIX);
278 }
279
Yifan Hong702115c2021-06-24 15:39:18 -0700280 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000281 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
282 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
Frederick Mayledc07cf82022-05-26 20:30:12 +0000283 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Andrei Homescu2a298012022-06-15 01:08:54 +0000284 if (singleThreaded) {
285 ret += "_single_threaded";
286 }
287 if (noKernel) {
288 ret += "_no_kernel";
289 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700290 return ret;
291 }
292
Steven Morelandc1635952021-04-01 16:20:47 +0000293 // This creates a new process serving an interface on a certain number of
294 // threads.
Andrei Homescu2a298012022-06-15 01:08:54 +0000295 ProcessSession createRpcTestSocketServerProcessEtc(const BinderRpcOptions& options) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000296 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000297
Yifan Hong702115c2021-06-24 15:39:18 -0700298 SocketType socketType = std::get<0>(GetParam());
299 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000300 uint32_t clientVersion = std::get<2>(GetParam());
301 uint32_t serverVersion = std::get<3>(GetParam());
Andrei Homescu2a298012022-06-15 01:08:54 +0000302 bool singleThreaded = std::get<4>(GetParam());
303 bool noKernel = std::get<5>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000304
Andrei Homescu2a298012022-06-15 01:08:54 +0000305 std::string path = android::base::GetExecutableDirectory();
306 auto servicePath =
307 android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
308 singleThreaded ? "_single_threaded" : "",
309 noKernel ? "_no_kernel" : "");
Steven Morelandc1635952021-04-01 16:20:47 +0000310
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000311 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000312 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700313 android::base::borrowed_fd readEnd) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000314 auto writeFd = std::to_string(writeEnd.get());
315 auto readFd = std::to_string(readEnd.get());
316 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
317 NULL);
Steven Morelandc1635952021-04-01 16:20:47 +0000318 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000319 };
320
Andrei Homescu2a298012022-06-15 01:08:54 +0000321 BinderRpcTestServerConfig serverConfig;
322 serverConfig.numThreads = options.numThreads;
323 serverConfig.socketType = static_cast<int32_t>(socketType);
324 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
325 serverConfig.serverVersion = serverVersion;
326 serverConfig.vsockPort = allocateVsockPort();
327 serverConfig.addr = allocateSocketAddress();
328 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
329 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
330 static_cast<int32_t>(mode));
331 }
332 writeToFd(ret.host.writeEnd(), serverConfig);
333
Yifan Hong1deca4b2021-09-10 16:16:44 -0700334 std::vector<sp<RpcSession>> sessions;
335 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
336 for (size_t i = 0; i < options.numSessions; i++) {
337 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
338 }
339
340 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
341 BinderRpcTestClientInfo clientInfo;
342 for (const auto& session : sessions) {
343 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700344 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700345 }
346 writeToFd(ret.host.writeEnd(), clientInfo);
347
348 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700349 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700350 CHECK_NE(0, serverInfo.port);
351 }
352
353 if (rpcSecurity == RpcSecurity::TLS) {
354 const auto& serverCert = serverInfo.cert.data;
355 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700356 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
357 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700358 }
359
Steven Moreland2372f9d2021-08-05 15:42:01 -0700360 status_t status;
361
Yifan Hong1deca4b2021-09-10 16:16:44 -0700362 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000363 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700364 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700365 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000366 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Moreland659416d2021-05-11 00:47:50 +0000367
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000368 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700369 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700370 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000371 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700372 });
Steven Moreland4198a122021-08-03 17:37:58 -0700373 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000374 case SocketType::UNIX:
Andrei Homescu2a298012022-06-15 01:08:54 +0000375 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000376 break;
377 case SocketType::VSOCK:
Andrei Homescu2a298012022-06-15 01:08:54 +0000378 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000379 break;
380 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700381 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000382 break;
383 default:
384 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000385 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000386 if (options.allowConnectFailure && status != OK) {
387 ret.sessions.clear();
388 break;
389 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700390 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000391 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000392 }
Steven Morelandc1635952021-04-01 16:20:47 +0000393 return ret;
394 }
395
Andrei Homescu2a298012022-06-15 01:08:54 +0000396 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const BinderRpcOptions& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000397 BinderRpcTestProcessSession ret{
Andrei Homescu2a298012022-06-15 01:08:54 +0000398 .proc = createRpcTestSocketServerProcessEtc(options),
Steven Morelandc1635952021-04-01 16:20:47 +0000399 };
400
Frederick Mayle69a0c992022-05-26 20:38:39 +0000401 ret.rootBinder = ret.proc.sessions.empty() ? nullptr : ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000402 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
403
404 return ret;
405 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700406
407 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
408 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000409};
410
Steven Morelandc1635952021-04-01 16:20:47 +0000411TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000412 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000413 ASSERT_NE(proc.rootBinder, nullptr);
414 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
415}
416
Steven Moreland4cf688f2021-03-31 01:48:58 +0000417TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000418 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000419 ASSERT_NE(proc.rootBinder, nullptr);
420 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
421}
422
Andrei Homescua858b0e2022-08-01 23:43:09 +0000423TEST_P(BinderRpc, MultipleSessions) {
424 if (serverSingleThreaded()) {
425 // Tests with multiple sessions require a multi-threaded service,
426 // but work fine on a single-threaded client
427 GTEST_SKIP() << "This test requires a multi-threaded service";
428 }
429
Steven Moreland4313d7e2021-07-15 23:41:22 +0000430 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000431 for (auto session : proc.proc.sessions) {
432 ASSERT_NE(nullptr, session.root);
433 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000434 }
435}
436
Andrei Homescua858b0e2022-08-01 23:43:09 +0000437TEST_P(BinderRpc, SeparateRootObject) {
438 if (serverSingleThreaded()) {
439 GTEST_SKIP() << "This test requires a multi-threaded service";
440 }
441
Steven Moreland51c44a92021-10-14 16:50:35 -0700442 SocketType type = std::get<0>(GetParam());
443 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
444 // we can't get port numbers for unix sockets
445 return;
446 }
447
448 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
449
450 int port1 = 0;
451 EXPECT_OK(proc.rootIface->getClientPort(&port1));
452
453 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
454 int port2;
455 EXPECT_OK(rootIface2->getClientPort(&port2));
456
457 // we should have a different IBinderRpcTest object created for each
458 // session, because we use setPerSessionRootObject
459 EXPECT_NE(port1, port2);
460}
461
Steven Morelandc1635952021-04-01 16:20:47 +0000462TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000463 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000464 Parcel data;
465 Parcel reply;
466 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
467}
468
Steven Moreland67753c32021-04-02 18:45:19 +0000469TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700470 auto proc1 = createRpcTestSocketServerProcess({});
471 auto proc2 = createRpcTestSocketServerProcess({});
472
473 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000474
475 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700476 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000477 p1.writeInt32(3);
478
Frederick Maylea4ed5672022-06-17 22:03:38 +0000479 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700480 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
481
Steven Moreland67753c32021-04-02 18:45:19 +0000482 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700483 p2.markForBinder(proc2.rootBinder);
484 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000485
486 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
487 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
488}
489
Steven Morelandc1635952021-04-01 16:20:47 +0000490TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000491 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000492 Parcel data;
493 data.markForBinder(proc.rootBinder);
494 Parcel reply;
495 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
496}
497
Steven Morelandc1635952021-04-01 16:20:47 +0000498TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000499 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000500 EXPECT_OK(proc.rootIface->sendString("asdf"));
501}
502
Steven Morelandc1635952021-04-01 16:20:47 +0000503TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000504 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000505 std::string doubled;
506 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
507 EXPECT_EQ("cool cool ", doubled);
508}
509
Steven Morelandc1635952021-04-01 16:20:47 +0000510TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000511 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000512 std::string single = std::string(1024, 'a');
513 std::string doubled;
514 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
515 EXPECT_EQ(single + single, doubled);
516}
517
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000518TEST_P(BinderRpc, InvalidNullBinderReturn) {
519 auto proc = createRpcTestSocketServerProcess({});
520
521 sp<IBinder> outBinder;
522 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
523}
524
Steven Morelandc1635952021-04-01 16:20:47 +0000525TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000526 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000527
528 int32_t pingResult;
529 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
530 EXPECT_EQ(OK, pingResult);
531
532 EXPECT_EQ(0, MyBinderRpcSession::gNum);
533}
534
Steven Morelandc1635952021-04-01 16:20:47 +0000535TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000536 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000537
538 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
539 sp<IBinder> outBinder;
540 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
541 EXPECT_EQ(inBinder, outBinder);
542
543 wp<IBinder> weak = inBinder;
544 inBinder = nullptr;
545 outBinder = nullptr;
546
547 // Force reading a reply, to process any pending dec refs from the other
548 // process (the other process will process dec refs there before processing
549 // the ping here).
550 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
551
552 EXPECT_EQ(nullptr, weak.promote());
553
554 EXPECT_EQ(0, MyBinderRpcSession::gNum);
555}
556
Steven Morelandc1635952021-04-01 16:20:47 +0000557TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000558 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000559
560 sp<IBinderRpcSession> session;
561 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
562
563 sp<IBinder> inBinder = IInterface::asBinder(session);
564 sp<IBinder> outBinder;
565 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
566 EXPECT_EQ(inBinder, outBinder);
567
568 wp<IBinder> weak = inBinder;
569 session = nullptr;
570 inBinder = nullptr;
571 outBinder = nullptr;
572
573 // Force reading a reply, to process any pending dec refs from the other
574 // process (the other process will process dec refs there before processing
575 // the ping here).
576 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
577
578 EXPECT_EQ(nullptr, weak.promote());
579}
580
Steven Morelandc1635952021-04-01 16:20:47 +0000581TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000582 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000583
584 sp<IBinder> outBinder;
585 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
586 EXPECT_EQ(nullptr, outBinder);
587}
588
Steven Morelandc1635952021-04-01 16:20:47 +0000589TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000590 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000591
592 IBinder* ptr = nullptr;
593 {
594 sp<IBinder> binder = new BBinder();
595 ptr = binder.get();
596 EXPECT_OK(proc.rootIface->holdBinder(binder));
597 }
598
599 sp<IBinder> held;
600 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
601
602 EXPECT_EQ(held.get(), ptr);
603
604 // stop holding binder, because we test to make sure references are cleaned
605 // up
606 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
607 // and flush ref counts
608 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
609}
610
611// START TESTS FOR LIMITATIONS OF SOCKET BINDER
612// These are behavioral differences form regular binder, where certain usecases
613// aren't supported.
614
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000615TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000616 auto proc1 = createRpcTestSocketServerProcess({});
617 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000618
619 sp<IBinder> outBinder;
620 EXPECT_EQ(INVALID_OPERATION,
621 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
622}
623
Andrei Homescua858b0e2022-08-01 23:43:09 +0000624TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
625 if (serverSingleThreaded()) {
626 GTEST_SKIP() << "This test requires a multi-threaded service";
627 }
628
Steven Moreland4313d7e2021-07-15 23:41:22 +0000629 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000630
631 sp<IBinder> outBinder;
632 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000633 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000634 .transactionError());
635}
636
Steven Morelandc1635952021-04-01 16:20:47 +0000637TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000638 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000639 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
640 "at build time.";
641 }
642
Steven Moreland4313d7e2021-07-15 23:41:22 +0000643 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000644
645 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
646 sp<IBinder> outBinder;
647 EXPECT_EQ(INVALID_OPERATION,
648 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
649}
650
Steven Morelandc1635952021-04-01 16:20:47 +0000651TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000652 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000653 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
654 "at build time.";
655 }
656
Steven Moreland4313d7e2021-07-15 23:41:22 +0000657 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000658
659 // for historical reasons, IServiceManager interface only returns the
660 // exception code
661 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
662 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
663}
664
665// END TESTS FOR LIMITATIONS OF SOCKET BINDER
666
Steven Morelandc1635952021-04-01 16:20:47 +0000667TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000668 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000669
670 sp<IBinder> outBinder;
671 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
672 EXPECT_EQ(proc.rootBinder, outBinder);
673}
674
Steven Morelandc1635952021-04-01 16:20:47 +0000675TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000676 auto proc = createRpcTestSocketServerProcess({
677 // Enable FD support because it uses more stack space and so represents
678 // something closer to a worst case scenario.
679 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
680 .serverSupportedFileDescriptorTransportModes =
681 {RpcSession::FileDescriptorTransportMode::UNIX},
682 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000683
684 auto nastyNester = sp<MyBinderRpcTest>::make();
685 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
686
687 wp<IBinder> weak = nastyNester;
688 nastyNester = nullptr;
689 EXPECT_EQ(nullptr, weak.promote());
690}
691
Steven Morelandc1635952021-04-01 16:20:47 +0000692TEST_P(BinderRpc, SameBinderEquality) {
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
698 sp<IBinder> b;
699 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
700
701 EXPECT_EQ(a, b);
702}
703
Steven Morelandc1635952021-04-01 16:20:47 +0000704TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000705 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000706
707 sp<IBinder> a;
708 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
709 wp<IBinder> weak = a;
710 a = nullptr;
711
712 sp<IBinder> b;
713 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
714
715 // this is the wrong behavior, since BpBinder
716 // doesn't implement onIncStrongAttempted
717 // but make sure there is no crash
718 EXPECT_EQ(nullptr, weak.promote());
719
720 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
721
722 // In order to fix this:
723 // - need to have incStrongAttempted reflected across IPC boundary (wait for
724 // response to promote - round trip...)
725 // - sendOnLastWeakRef, to delete entries out of RpcState table
726 EXPECT_EQ(b, weak.promote());
727}
728
729#define expectSessions(expected, iface) \
730 do { \
731 int session; \
732 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
733 EXPECT_EQ(expected, session); \
734 } while (false)
735
Steven Morelandc1635952021-04-01 16:20:47 +0000736TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000737 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000738
739 sp<IBinderRpcSession> session;
740 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
741 std::string out;
742 EXPECT_OK(session->getName(&out));
743 EXPECT_EQ("aoeu", out);
744
745 expectSessions(1, proc.rootIface);
746 session = nullptr;
747 expectSessions(0, proc.rootIface);
748}
749
Steven Morelandc1635952021-04-01 16:20:47 +0000750TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000751 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000752
753 std::vector<sp<IBinderRpcSession>> sessions;
754
755 for (size_t i = 0; i < 15; i++) {
756 expectSessions(i, proc.rootIface);
757 sp<IBinderRpcSession> session;
758 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
759 sessions.push_back(session);
760 }
761 expectSessions(sessions.size(), proc.rootIface);
762 for (size_t i = 0; i < sessions.size(); i++) {
763 std::string out;
764 EXPECT_OK(sessions.at(i)->getName(&out));
765 EXPECT_EQ(std::to_string(i), out);
766 }
767 expectSessions(sessions.size(), proc.rootIface);
768
769 while (!sessions.empty()) {
770 sessions.pop_back();
771 expectSessions(sessions.size(), proc.rootIface);
772 }
773 expectSessions(0, proc.rootIface);
774}
775
776size_t epochMillis() {
777 using std::chrono::duration_cast;
778 using std::chrono::milliseconds;
779 using std::chrono::seconds;
780 using std::chrono::system_clock;
781 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
782}
783
Andrei Homescua858b0e2022-08-01 23:43:09 +0000784TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
785 if (clientOrServerSingleThreaded()) {
786 GTEST_SKIP() << "This test requires multiple threads";
787 }
788
Steven Moreland5553ac42020-11-11 02:14:45 +0000789 constexpr size_t kNumThreads = 10;
790
Steven Moreland4313d7e2021-07-15 23:41:22 +0000791 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000792
793 EXPECT_OK(proc.rootIface->lock());
794
795 // block all but one thread taking locks
796 std::vector<std::thread> ts;
797 for (size_t i = 0; i < kNumThreads - 1; i++) {
798 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
799 }
800
801 usleep(100000); // give chance for calls on other threads
802
803 // other calls still work
804 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
805
806 constexpr size_t blockTimeMs = 500;
807 size_t epochMsBefore = epochMillis();
808 // after this, we should never see a response within this time
809 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
810
811 // this call should be blocked for blockTimeMs
812 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
813
814 size_t epochMsAfter = epochMillis();
815 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
816
817 for (auto& t : ts) t.join();
818}
819
Yifan Hong1f44f982021-10-08 17:16:47 -0700820void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
821 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000822 size_t epochMsBefore = epochMillis();
823
824 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700825 for (size_t i = 0; i < numCalls; i++) {
826 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000827 }
828
829 for (auto& t : ts) t.join();
830
831 size_t epochMsAfter = epochMillis();
832
Yifan Hong1f44f982021-10-08 17:16:47 -0700833 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000834
835 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700836 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
837}
838
Andrei Homescua858b0e2022-08-01 23:43:09 +0000839TEST_P(BinderRpc, ThreadPoolOverSaturated) {
840 if (clientOrServerSingleThreaded()) {
841 GTEST_SKIP() << "This test requires multiple threads";
842 }
843
Yifan Hong1f44f982021-10-08 17:16:47 -0700844 constexpr size_t kNumThreads = 10;
845 constexpr size_t kNumCalls = kNumThreads + 3;
846 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
847 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
848}
849
Andrei Homescua858b0e2022-08-01 23:43:09 +0000850TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
851 if (clientOrServerSingleThreaded()) {
852 GTEST_SKIP() << "This test requires multiple threads";
853 }
854
Yifan Hong1f44f982021-10-08 17:16:47 -0700855 constexpr size_t kNumThreads = 20;
856 constexpr size_t kNumOutgoingConnections = 10;
857 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
858 auto proc = createRpcTestSocketServerProcess(
859 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
860 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000861}
862
Andrei Homescua858b0e2022-08-01 23:43:09 +0000863TEST_P(BinderRpc, ThreadingStressTest) {
864 if (clientOrServerSingleThreaded()) {
865 GTEST_SKIP() << "This test requires multiple threads";
866 }
867
Steven Moreland5553ac42020-11-11 02:14:45 +0000868 constexpr size_t kNumClientThreads = 10;
869 constexpr size_t kNumServerThreads = 10;
870 constexpr size_t kNumCalls = 100;
871
Steven Moreland4313d7e2021-07-15 23:41:22 +0000872 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000873
874 std::vector<std::thread> threads;
875 for (size_t i = 0; i < kNumClientThreads; i++) {
876 threads.push_back(std::thread([&] {
877 for (size_t j = 0; j < kNumCalls; j++) {
878 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000879 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000880 EXPECT_EQ(proc.rootBinder, out);
881 }
882 }));
883 }
884
885 for (auto& t : threads) t.join();
886}
887
Steven Moreland925ba0a2021-09-17 18:06:32 -0700888static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
889 std::vector<std::thread> threads;
890 for (size_t i = 0; i < threadCount; i++) {
891 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
892 }
893 for (auto& t : threads) t.join();
894}
895
Andrei Homescua858b0e2022-08-01 23:43:09 +0000896TEST_P(BinderRpc, OnewayStressTest) {
897 if (clientOrServerSingleThreaded()) {
898 GTEST_SKIP() << "This test requires multiple threads";
899 }
900
Steven Morelandc6046982021-04-20 00:49:42 +0000901 constexpr size_t kNumClientThreads = 10;
902 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700903 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000904
Steven Moreland4313d7e2021-07-15 23:41:22 +0000905 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000906
907 std::vector<std::thread> threads;
908 for (size_t i = 0; i < kNumClientThreads; i++) {
909 threads.push_back(std::thread([&] {
910 for (size_t j = 0; j < kNumCalls; j++) {
911 EXPECT_OK(proc.rootIface->sendString("a"));
912 }
Steven Morelandc6046982021-04-20 00:49:42 +0000913 }));
914 }
915
916 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700917
918 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000919}
920
Steven Morelandc1635952021-04-01 16:20:47 +0000921TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000922 constexpr size_t kReallyLongTimeMs = 100;
923 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
924
Steven Moreland4313d7e2021-07-15 23:41:22 +0000925 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000926
927 size_t epochMsBefore = epochMillis();
928
929 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
930
931 size_t epochMsAfter = epochMillis();
932 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
933}
934
Andrei Homescua858b0e2022-08-01 23:43:09 +0000935TEST_P(BinderRpc, OnewayCallQueueing) {
936 if (clientOrServerSingleThreaded()) {
937 GTEST_SKIP() << "This test requires multiple threads";
938 }
939
Steven Moreland5553ac42020-11-11 02:14:45 +0000940 constexpr size_t kNumSleeps = 10;
941 constexpr size_t kNumExtraServerThreads = 4;
942 constexpr size_t kSleepMs = 50;
943
944 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000945 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000946
947 EXPECT_OK(proc.rootIface->lock());
948
Steven Moreland1c678802021-09-17 16:48:47 -0700949 size_t epochMsBefore = epochMillis();
950
951 // all these *Async commands should be queued on the server sequentially,
952 // even though there are multiple threads.
953 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000954 proc.rootIface->sleepMsAsync(kSleepMs);
955 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000956 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
957
Steven Moreland1c678802021-09-17 16:48:47 -0700958 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000959 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700960
Steven Moreland5553ac42020-11-11 02:14:45 +0000961 size_t epochMsAfter = epochMillis();
962
Frederick Mayle3fa815d2022-07-12 22:52:52 +0000963 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000964
Steven Moreland925ba0a2021-09-17 18:06:32 -0700965 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000966}
967
Andrei Homescua858b0e2022-08-01 23:43:09 +0000968TEST_P(BinderRpc, OnewayCallExhaustion) {
969 if (clientOrServerSingleThreaded()) {
970 GTEST_SKIP() << "This test requires multiple threads";
971 }
972
Steven Morelandd45be622021-06-04 02:19:37 +0000973 constexpr size_t kNumClients = 2;
974 constexpr size_t kTooLongMs = 1000;
975
Steven Moreland4313d7e2021-07-15 23:41:22 +0000976 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000977
978 // Build up oneway calls on the second session to make sure it terminates
979 // and shuts down. The first session should be unaffected (proc destructor
980 // checks the first session).
981 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
982
983 std::vector<std::thread> threads;
984 for (size_t i = 0; i < kNumClients; i++) {
985 // one of these threads will get stuck queueing a transaction once the
986 // socket fills up, the other will be able to fill up transactions on
987 // this object
988 threads.push_back(std::thread([&] {
989 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
990 }
991 }));
992 }
993 for (auto& t : threads) t.join();
994
995 Status status = iface->sleepMsAsync(kTooLongMs);
996 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
997
Steven Moreland798e0d12021-07-14 23:19:25 +0000998 // now that it has died, wait for the remote session to shutdown
999 std::vector<int32_t> remoteCounts;
1000 do {
1001 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1002 } while (remoteCounts.size() == kNumClients);
1003
Steven Morelandd45be622021-06-04 02:19:37 +00001004 // the second session should be shutdown in the other process by the time we
1005 // are able to join above (it'll only be hung up once it finishes processing
1006 // any pending commands). We need to erase this session from the record
1007 // here, so that the destructor for our session won't check that this
1008 // session is valid, but we still want it to test the other session.
1009 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1010}
1011
Steven Moreland659416d2021-05-11 00:47:50 +00001012TEST_P(BinderRpc, Callbacks) {
1013 const static std::string kTestString = "good afternoon!";
1014
Steven Morelandc7d40132021-06-10 03:42:11 +00001015 for (bool callIsOneway : {true, false}) {
1016 for (bool callbackIsOneway : {true, false}) {
1017 for (bool delayed : {true, false}) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001018 if (clientOrServerSingleThreaded() &&
1019 (callIsOneway || callbackIsOneway || delayed)) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001020 // we have no incoming connections to receive the callback
1021 continue;
1022 }
1023
Andrei Homescua858b0e2022-08-01 23:43:09 +00001024 size_t numIncomingConnections = clientOrServerSingleThreaded() ? 0 : 1;
Steven Moreland4313d7e2021-07-15 23:41:22 +00001025 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +00001026 {.numThreads = 1,
1027 .numSessions = 1,
Andrei Homescu2a298012022-06-15 01:08:54 +00001028 .numIncomingConnections = numIncomingConnections});
Steven Morelandc7d40132021-06-10 03:42:11 +00001029 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001030
Steven Morelandc7d40132021-06-10 03:42:11 +00001031 if (callIsOneway) {
1032 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1033 kTestString));
1034 } else {
1035 EXPECT_OK(
1036 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1037 }
Steven Moreland659416d2021-05-11 00:47:50 +00001038
Steven Moreland03ecce62022-05-13 23:22:05 +00001039 // if both transactions are synchronous and the response is sent back on the
1040 // same thread, everything should have happened in a nested call. Otherwise,
1041 // the callback will be processed on another thread.
1042 if (callIsOneway || callbackIsOneway || delayed) {
1043 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001044 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001045 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1046 }
Steven Moreland659416d2021-05-11 00:47:50 +00001047
Steven Morelandc7d40132021-06-10 03:42:11 +00001048 EXPECT_EQ(cb->mValues.size(), 1)
1049 << "callIsOneway: " << callIsOneway
1050 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1051 if (cb->mValues.empty()) continue;
1052 EXPECT_EQ(cb->mValues.at(0), kTestString)
1053 << "callIsOneway: " << callIsOneway
1054 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001055
Steven Morelandc7d40132021-06-10 03:42:11 +00001056 // since we are severing the connection, we need to go ahead and
1057 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001058 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1059 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1060 }
Steven Moreland659416d2021-05-11 00:47:50 +00001061
Steven Moreland1b304292021-07-15 22:59:34 +00001062 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001063 // need to manually shut it down
1064 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Morelandc7d40132021-06-10 03:42:11 +00001065 proc.expectAlreadyShutdown = true;
1066 }
Steven Moreland659416d2021-05-11 00:47:50 +00001067 }
1068 }
1069}
1070
Devin Moore66d5b7a2022-07-07 21:42:10 +00001071TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001072 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001073 GTEST_SKIP() << "This test requires multiple threads";
1074 }
1075 class MyDeathRec : public IBinder::DeathRecipient {
1076 public:
1077 void binderDied(const wp<IBinder>& /* who */) override {
1078 dead = true;
1079 mCv.notify_one();
1080 }
1081 std::mutex mMtx;
1082 std::condition_variable mCv;
1083 bool dead = false;
1084 };
1085
1086 // Death recipient needs to have an incoming connection to be called
1087 auto proc = createRpcTestSocketServerProcess(
1088 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1089
1090 auto dr = sp<MyDeathRec>::make();
1091 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1092
1093 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1094 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1095 }
1096
1097 std::unique_lock<std::mutex> lock(dr->mMtx);
Devin Moore47a12012022-08-19 21:16:17 +00001098 ASSERT_TRUE(dr->mCv.wait_for(lock, 1000ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001099
1100 // need to wait for the session to shutdown so we don't "Leak session"
1101 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1102 proc.expectAlreadyShutdown = true;
1103}
1104
1105TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001106 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001107 GTEST_SKIP() << "This test requires multiple threads";
1108 }
1109 class MyDeathRec : public IBinder::DeathRecipient {
1110 public:
1111 void binderDied(const wp<IBinder>& /* who */) override {
1112 dead = true;
1113 mCv.notify_one();
1114 }
1115 std::mutex mMtx;
1116 std::condition_variable mCv;
1117 bool dead = false;
1118 };
1119
1120 // Death recipient needs to have an incoming connection to be called
1121 auto proc = createRpcTestSocketServerProcess(
1122 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1123
1124 auto dr = sp<MyDeathRec>::make();
1125 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1126
1127 // Explicitly calling shutDownAndWait will cause the death recipients
1128 // to be called.
1129 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1130
1131 std::unique_lock<std::mutex> lock(dr->mMtx);
1132 if (!dr->dead) {
1133 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 1000ms));
1134 }
1135 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1136
1137 proc.proc.host.terminate();
1138 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1139 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1140 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1141 });
1142 proc.expectAlreadyShutdown = true;
1143}
1144
1145TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1146 class MyDeathRec : public IBinder::DeathRecipient {
1147 public:
1148 void binderDied(const wp<IBinder>& /* who */) override {}
1149 };
1150
1151 auto proc = createRpcTestSocketServerProcess(
1152 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1153
1154 auto dr = sp<MyDeathRec>::make();
1155 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1156 "Cannot register a DeathRecipient without any incoming connections.");
1157}
1158
1159TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001160 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001161 GTEST_SKIP() << "This test requires multiple threads";
1162 }
1163 class MyDeathRec : public IBinder::DeathRecipient {
1164 public:
1165 void binderDied(const wp<IBinder>& /* who */) override {
1166 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1167 }
1168 };
1169
1170 // Death recipient needs to have an incoming connection to be called
1171 auto proc = createRpcTestSocketServerProcess(
1172 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1173
1174 auto dr = sp<MyDeathRec>::make();
1175 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1176 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1177
1178 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1179 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1180 }
1181
1182 // need to wait for the session to shutdown so we don't "Leak session"
1183 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1184 proc.expectAlreadyShutdown = true;
1185}
1186
Steven Moreland195edb82021-06-08 02:44:39 +00001187TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001188 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001189 auto cb = sp<MyBinderRpcCallback>::make();
1190
1191 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1192 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1193}
1194
Steven Morelandc1635952021-04-01 16:20:47 +00001195TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001196 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001197 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001198
1199 // make sure there is some state during crash
1200 // 1. we hold their binder
1201 sp<IBinderRpcSession> session;
1202 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1203 // 2. they hold our binder
1204 sp<IBinder> binder = new BBinder();
1205 EXPECT_OK(proc.rootIface->holdBinder(binder));
1206
1207 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1208 << "Do death cleanup: " << doDeathCleanup;
1209
Frederick Maylea12b0962022-06-25 01:13:22 +00001210 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1211 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1212 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1213 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001214 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001215 }
1216}
1217
Steven Morelandd7302072021-05-15 01:32:04 +00001218TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001219 // This test only works if the current process shared the internal state of
1220 // ProcessState with the service across the call to fork(). Both the static
1221 // libraries and libbinder.so have their own separate copies of all the
1222 // globals, so the test only works when the test client and service both use
1223 // libbinder.so (when using static libraries, even a client and service
1224 // using the same kind of static library should have separate copies of the
1225 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +00001226 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001227 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1228 "at build time.";
1229 }
1230
Steven Moreland4313d7e2021-07-15 23:41:22 +00001231 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001232
Andrei Homescu2a298012022-06-15 01:08:54 +00001233 // we can't allocate IPCThreadState so actually the first time should
1234 // succeed :(
1235 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001236
1237 // second time! we catch the error :)
1238 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1239
Frederick Maylea12b0962022-06-25 01:13:22 +00001240 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1241 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1242 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1243 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001244 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001245}
1246
Frederick Mayle69a0c992022-05-26 20:38:39 +00001247TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1248 auto proc = createRpcTestSocketServerProcess({
1249 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1250 .serverSupportedFileDescriptorTransportModes =
1251 {RpcSession::FileDescriptorTransportMode::UNIX},
1252 .allowConnectFailure = true,
1253 });
1254 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1255 proc.proc.host.terminate();
1256 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1257 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1258 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1259 });
1260 proc.expectAlreadyShutdown = true;
1261}
1262
1263TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1264 auto proc = createRpcTestSocketServerProcess({
1265 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1266 .serverSupportedFileDescriptorTransportModes =
1267 {RpcSession::FileDescriptorTransportMode::NONE},
1268 .allowConnectFailure = true,
1269 });
1270 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1271 proc.proc.host.terminate();
1272 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1273 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1274 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1275 });
1276 proc.expectAlreadyShutdown = true;
1277}
1278
1279TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1280 auto proc = createRpcTestSocketServerProcess({
1281 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1282 .serverSupportedFileDescriptorTransportModes =
1283 {RpcSession::FileDescriptorTransportMode::NONE,
1284 RpcSession::FileDescriptorTransportMode::UNIX},
1285 });
1286
1287 android::os::ParcelFileDescriptor out;
1288 auto status = proc.rootIface->echoAsFile("hello", &out);
1289 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1290}
1291
1292TEST_P(BinderRpc, ReceiveFile) {
1293 auto proc = createRpcTestSocketServerProcess({
1294 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1295 .serverSupportedFileDescriptorTransportModes =
1296 {RpcSession::FileDescriptorTransportMode::UNIX},
1297 });
1298
1299 android::os::ParcelFileDescriptor out;
1300 auto status = proc.rootIface->echoAsFile("hello", &out);
1301 if (!supportsFdTransport()) {
1302 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1303 return;
1304 }
1305 ASSERT_TRUE(status.isOk()) << status;
1306
1307 std::string result;
1308 CHECK(android::base::ReadFdToString(out.get(), &result));
1309 EXPECT_EQ(result, "hello");
1310}
1311
1312TEST_P(BinderRpc, SendFiles) {
1313 auto proc = createRpcTestSocketServerProcess({
1314 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1315 .serverSupportedFileDescriptorTransportModes =
1316 {RpcSession::FileDescriptorTransportMode::UNIX},
1317 });
1318
1319 std::vector<android::os::ParcelFileDescriptor> files;
1320 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1321 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1322 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1323 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1324
1325 android::os::ParcelFileDescriptor out;
1326 auto status = proc.rootIface->concatFiles(files, &out);
1327 if (!supportsFdTransport()) {
1328 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1329 return;
1330 }
1331 ASSERT_TRUE(status.isOk()) << status;
1332
1333 std::string result;
1334 CHECK(android::base::ReadFdToString(out.get(), &result));
1335 EXPECT_EQ(result, "123abcd");
1336}
1337
1338TEST_P(BinderRpc, SendMaxFiles) {
1339 if (!supportsFdTransport()) {
1340 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1341 }
1342
1343 auto proc = createRpcTestSocketServerProcess({
1344 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1345 .serverSupportedFileDescriptorTransportModes =
1346 {RpcSession::FileDescriptorTransportMode::UNIX},
1347 });
1348
1349 std::vector<android::os::ParcelFileDescriptor> files;
1350 for (int i = 0; i < 253; i++) {
1351 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1352 }
1353
1354 android::os::ParcelFileDescriptor out;
1355 auto status = proc.rootIface->concatFiles(files, &out);
1356 ASSERT_TRUE(status.isOk()) << status;
1357
1358 std::string result;
1359 CHECK(android::base::ReadFdToString(out.get(), &result));
1360 EXPECT_EQ(result, std::string(253, 'a'));
1361}
1362
1363TEST_P(BinderRpc, SendTooManyFiles) {
1364 if (!supportsFdTransport()) {
1365 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1366 }
1367
1368 auto proc = createRpcTestSocketServerProcess({
1369 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1370 .serverSupportedFileDescriptorTransportModes =
1371 {RpcSession::FileDescriptorTransportMode::UNIX},
1372 });
1373
1374 std::vector<android::os::ParcelFileDescriptor> files;
1375 for (int i = 0; i < 254; i++) {
1376 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1377 }
1378
1379 android::os::ParcelFileDescriptor out;
1380 auto status = proc.rootIface->concatFiles(files, &out);
1381 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1382}
1383
Steven Moreland37aff182021-03-26 02:04:16 +00001384TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001385 if constexpr (!kEnableSharedLibs) {
1386 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1387 }
1388
Steven Moreland4313d7e2021-07-15 23:41:22 +00001389 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001390
1391 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1392 ASSERT_NE(binder, nullptr);
1393
1394 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1395}
1396
1397TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001398 if constexpr (!kEnableSharedLibs) {
1399 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1400 }
1401
Steven Moreland4313d7e2021-07-15 23:41:22 +00001402 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001403
1404 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1405 ASSERT_NE(binder, nullptr);
1406
1407 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1408 ASSERT_NE(ndkBinder, nullptr);
1409
1410 std::string out;
1411 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1412 ASSERT_TRUE(status.isOk()) << status.getDescription();
1413 ASSERT_EQ("aoeuaoeu", out);
1414}
1415
Steven Moreland5553ac42020-11-11 02:14:45 +00001416ssize_t countFds() {
1417 DIR* dir = opendir("/proc/self/fd/");
1418 if (dir == nullptr) return -1;
1419 ssize_t ret = 0;
1420 dirent* ent;
1421 while ((ent = readdir(dir)) != nullptr) ret++;
1422 closedir(dir);
1423 return ret;
1424}
1425
Andrei Homescua858b0e2022-08-01 23:43:09 +00001426TEST_P(BinderRpc, Fds) {
1427 if (serverSingleThreaded()) {
1428 GTEST_SKIP() << "This test requires multiple threads";
1429 }
1430
Steven Moreland5553ac42020-11-11 02:14:45 +00001431 ssize_t beforeFds = countFds();
1432 ASSERT_GE(beforeFds, 0);
1433 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001434 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001435 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1436 }
1437 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1438}
1439
Devin Moore800b2252021-10-15 16:22:57 +00001440TEST_P(BinderRpc, AidlDelegatorTest) {
1441 auto proc = createRpcTestSocketServerProcess({});
1442 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1443 ASSERT_NE(nullptr, myDelegator);
1444
1445 std::string doubled;
1446 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1447 EXPECT_EQ("cool cool ", doubled);
1448}
1449
Steven Morelandda573042021-06-12 01:13:45 +00001450static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001451 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001452 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001453
Andrei Homescu992a4052022-06-28 21:26:18 +00001454 android::base::unique_fd serverFd(
1455 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1456 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1457
1458 sockaddr_vm serverAddr{
1459 .svm_family = AF_VSOCK,
1460 .svm_port = vsockPort,
1461 .svm_cid = VMADDR_CID_ANY,
1462 };
1463 int ret = TEMP_FAILURE_RETRY(
1464 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1465 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1466 strerror(errno));
1467
1468 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1469 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1470 strerror(errno));
1471
1472 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1473 // to see if the kernel supports it. It's safe to use a blocking
1474 // connect because vsock sockets have a 2 second connection timeout,
1475 // and they return ETIMEDOUT after that.
1476 android::base::unique_fd connectFd(
1477 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1478 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1479 strerror(errno));
1480
1481 bool success = false;
1482 sockaddr_vm connectAddr{
1483 .svm_family = AF_VSOCK,
1484 .svm_port = vsockPort,
1485 .svm_cid = VMADDR_CID_LOCAL,
1486 };
1487 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1488 sizeof(connectAddr)));
1489 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1490 android::base::unique_fd acceptFd;
1491 while (true) {
1492 pollfd pfd[]{
1493 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1494 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1495 };
1496 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1497 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1498
1499 if (pfd[0].revents & POLLIN) {
1500 sockaddr_vm acceptAddr;
1501 socklen_t acceptAddrLen = sizeof(acceptAddr);
1502 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1503 reinterpret_cast<sockaddr*>(&acceptAddr),
1504 &acceptAddrLen, SOCK_CLOEXEC));
1505 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1506 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1507 "Truncated address");
1508
1509 // Store the fd in acceptFd so we keep the connection alive
1510 // while polling connectFd
1511 acceptFd.reset(ret);
1512 }
1513
1514 if (pfd[1].revents & POLLOUT) {
1515 // Connect either succeeded or timed out
1516 int connectErrno;
1517 socklen_t connectErrnoLen = sizeof(connectErrno);
1518 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1519 &connectErrnoLen);
1520 LOG_ALWAYS_FATAL_IF(ret == -1,
1521 "Could not getsockopt() after connect() "
1522 "on non-blocking socket: %s.",
1523 strerror(errno));
1524
1525 // We're done, this is all we wanted
1526 success = connectErrno == 0;
1527 break;
1528 }
1529 }
1530 } else {
1531 success = ret == 0;
1532 }
1533
1534 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1535
1536 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001537}
1538
Yifan Hong1deca4b2021-09-10 16:16:44 -07001539static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1540 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1541
1542 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001543
1544 static bool hasVsockLoopback = testSupportVsockLoopback();
1545
1546 if (hasVsockLoopback) {
1547 ret.push_back(SocketType::VSOCK);
1548 }
1549
1550 return ret;
1551}
1552
Frederick Mayledc07cf82022-05-26 20:30:12 +00001553static std::vector<uint32_t> testVersions() {
1554 std::vector<uint32_t> versions;
1555 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1556 versions.push_back(i);
1557 }
1558 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1559 return versions;
1560}
1561
Yifan Hong702115c2021-06-24 15:39:18 -07001562INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1563 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001564 ::testing::ValuesIn(RpcSecurityValues()),
1565 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001566 ::testing::ValuesIn(testVersions()),
1567 ::testing::Values(false, true),
1568 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001569 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001570
Yifan Hong702115c2021-06-24 15:39:18 -07001571class BinderRpcServerRootObject
1572 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001573
1574TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1575 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1576 auto setRootObject = [](bool isStrong) -> SetFn {
1577 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1578 };
1579
Yifan Hong702115c2021-06-24 15:39:18 -07001580 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1581 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001582 auto binder1 = sp<BBinder>::make();
1583 IBinder* binderRaw1 = binder1.get();
1584 setRootObject(isStrong1)(server.get(), binder1);
1585 EXPECT_EQ(binderRaw1, server->getRootObject());
1586 binder1.clear();
1587 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1588
1589 auto binder2 = sp<BBinder>::make();
1590 IBinder* binderRaw2 = binder2.get();
1591 setRootObject(isStrong2)(server.get(), binder2);
1592 EXPECT_EQ(binderRaw2, server->getRootObject());
1593 binder2.clear();
1594 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1595}
1596
1597INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001598 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1599 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001600
Yifan Hong1a235852021-05-13 16:07:47 -07001601class OneOffSignal {
1602public:
1603 // If notify() was previously called, or is called within |duration|, return true; else false.
1604 template <typename R, typename P>
1605 bool wait(std::chrono::duration<R, P> duration) {
1606 std::unique_lock<std::mutex> lock(mMutex);
1607 return mCv.wait_for(lock, duration, [this] { return mValue; });
1608 }
1609 void notify() {
1610 std::unique_lock<std::mutex> lock(mMutex);
1611 mValue = true;
1612 lock.unlock();
1613 mCv.notify_all();
1614 }
1615
1616private:
1617 std::mutex mMutex;
1618 std::condition_variable mCv;
1619 bool mValue = false;
1620};
1621
Yifan Hong194acf22021-06-29 18:44:56 -07001622TEST(BinderRpc, Java) {
1623#if !defined(__ANDROID__)
1624 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1625 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1626 "to binderHostDeviceTest. Hence, just disable this test on host.";
1627#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001628 if constexpr (!kEnableKernelIpc) {
1629 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1630 "at build time.";
1631 }
1632
Yifan Hong194acf22021-06-29 18:44:56 -07001633 sp<IServiceManager> sm = defaultServiceManager();
1634 ASSERT_NE(nullptr, sm);
1635 // Any Java service with non-empty getInterfaceDescriptor() would do.
1636 // Let's pick batteryproperties.
1637 auto binder = sm->checkService(String16("batteryproperties"));
1638 ASSERT_NE(nullptr, binder);
1639 auto descriptor = binder->getInterfaceDescriptor();
1640 ASSERT_GE(descriptor.size(), 0);
1641 ASSERT_EQ(OK, binder->pingBinder());
1642
1643 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001644 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001645 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001646 auto socket = rpcServer->releaseServer();
1647
1648 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001649 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1650
Yifan Honge3caaf22022-01-12 14:46:56 -08001651 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1652 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001653 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001654 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1655 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001656 << statusToString(setRpcClientDebugStatus);
1657 GTEST_SKIP();
1658 }
1659
1660 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001661
1662 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001663 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001664 auto rpcBinder = rpcSession->getRootObject();
1665 ASSERT_NE(nullptr, rpcBinder);
1666
1667 ASSERT_EQ(OK, rpcBinder->pingBinder());
1668
1669 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1670 << "getInterfaceDescriptor should not crash system_server";
1671 ASSERT_EQ(OK, rpcBinder->pingBinder());
1672}
1673
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001674class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1675public:
1676 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1677 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1678 std::to_string(std::get<1>(info.param));
1679 }
1680};
1681
1682TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1683 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1684 int sinkFd = sink.get();
1685 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1686 server->setProtocolVersion(std::get<1>(GetParam()));
1687 ASSERT_FALSE(server->hasServer());
1688 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1689 ASSERT_TRUE(server->hasServer());
1690 base::unique_fd retrieved = server->releaseServer();
1691 ASSERT_FALSE(server->hasServer());
1692 ASSERT_EQ(sinkFd, retrieved.get());
1693}
1694
1695TEST_P(BinderRpcServerOnly, Shutdown) {
1696 if constexpr (!kEnableRpcThreads) {
1697 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1698 }
1699
1700 auto addr = allocateSocketAddress();
1701 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1702 server->setProtocolVersion(std::get<1>(GetParam()));
1703 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1704 auto joinEnds = std::make_shared<OneOffSignal>();
1705
1706 // If things are broken and the thread never stops, don't block other tests. Because the thread
1707 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1708 // shared pointers are passed.
1709 std::thread([server, joinEnds] {
1710 server->join();
1711 joinEnds->notify();
1712 }).detach();
1713
1714 bool shutdown = false;
1715 for (int i = 0; i < 10 && !shutdown; i++) {
1716 usleep(300 * 1000); // 300ms; total 3s
1717 if (server->shutdown()) shutdown = true;
1718 }
1719 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1720
1721 ASSERT_TRUE(joinEnds->wait(2s))
1722 << "After server->shutdown() returns true, join() did not stop after 2s";
1723}
1724
Frederick Mayledc07cf82022-05-26 20:30:12 +00001725INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1726 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1727 ::testing::ValuesIn(testVersions())),
1728 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001729
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001730class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001731public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001732 // Only parameterized only server version because `RpcSession` is bypassed
1733 // in the client half of the tests.
1734 using Param =
1735 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001736 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001737
1738 // A server that handles client socket connections.
1739 class Server {
1740 public:
1741 explicit Server() {}
1742 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001743 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001744 [[nodiscard]] AssertionResult setUp(
1745 const Param& param,
1746 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001747 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001748 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001749 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001750 switch (socketType) {
1751 case SocketType::PRECONNECTED: {
1752 return AssertionFailure() << "Not supported by this test";
1753 } break;
1754 case SocketType::UNIX: {
1755 auto addr = allocateSocketAddress();
1756 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1757 if (status != OK) {
1758 return AssertionFailure()
1759 << "setupUnixDomainServer: " << statusToString(status);
1760 }
1761 mConnectToServer = [addr] {
1762 return connectTo(UnixSocketAddress(addr.c_str()));
1763 };
1764 } break;
1765 case SocketType::VSOCK: {
1766 auto port = allocateVsockPort();
1767 auto status = rpcServer->setupVsockServer(port);
1768 if (status != OK) {
1769 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1770 }
1771 mConnectToServer = [port] {
1772 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1773 };
1774 } break;
1775 case SocketType::INET: {
1776 unsigned int port;
1777 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1778 if (status != OK) {
1779 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1780 }
1781 mConnectToServer = [port] {
1782 const char* addr = kLocalInetAddress;
1783 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1784 if (aiStart == nullptr) return base::unique_fd{};
1785 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1786 auto fd = connectTo(
1787 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1788 if (fd.ok()) return fd;
1789 }
1790 ALOGE("None of the socket address resolved for %s:%u can be connected",
1791 addr, port);
1792 return base::unique_fd{};
1793 };
1794 }
1795 }
1796 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001797 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001798 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001799 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1800 mSetup = true;
1801 return AssertionSuccess();
1802 }
1803 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1804 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1805 return mCertVerifier;
1806 }
1807 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1808 void start() {
1809 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1810 mThread = std::make_unique<std::thread>(&Server::run, this);
1811 }
1812 void run() {
1813 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1814
1815 std::vector<std::thread> threads;
1816 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1817 base::unique_fd acceptedFd(
Pawan49d74cb2022-08-03 21:19:11 +00001818 TEMP_FAILURE_RETRY(accept4(mFd.fd.get(), nullptr, nullptr /*length*/,
Yifan Hong1deca4b2021-09-10 16:16:44 -07001819 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1820 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1821 }
1822
1823 for (auto& thread : threads) thread.join();
1824 }
1825 void handleOne(android::base::unique_fd acceptedFd) {
1826 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001827 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001828 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001829 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001830 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001831 }
Yifan Honge07d2732021-09-13 21:59:14 -07001832 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001833 shutdown();
1834 join();
1835 }
1836 void shutdown() { mFdTrigger->trigger(); }
1837
1838 void setPostConnect(
1839 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1840 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001841 }
1842
1843 private:
1844 std::unique_ptr<std::thread> mThread;
1845 ConnectToServer mConnectToServer;
1846 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
Pawan3e0061c2022-08-26 21:08:34 +00001847 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001848 std::unique_ptr<RpcTransportCtx> mCtx;
1849 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1850 std::make_shared<RpcCertificateVerifierSimple>();
1851 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001852 // The function invoked after connection and handshake. By default, it is
1853 // |defaultPostConnect| that sends |kMessage| to the client.
1854 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1855 Server::defaultPostConnect;
1856
1857 void join() {
1858 if (mThread != nullptr) {
1859 mThread->join();
1860 mThread = nullptr;
1861 }
1862 }
1863
1864 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1865 FdTrigger* fdTrigger) {
1866 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001867 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001868 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001869 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001870 if (status != OK) return AssertionFailure() << statusToString(status);
1871 return AssertionSuccess();
1872 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001873 };
1874
1875 class Client {
1876 public:
1877 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1878 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001879 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001880 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1881 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001882 mFdTrigger = FdTrigger::make();
1883 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1884 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1885 return AssertionSuccess();
1886 }
1887 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1888 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1889 return mCertVerifier;
1890 }
Yifan Hong67519322021-09-13 18:51:16 -07001891 // connect() and do handshake
1892 bool setUpTransport() {
1893 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001894 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001895 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1896 return mClientTransport != nullptr;
1897 }
1898 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1899 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1900 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001901 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001902 status_t readStatus =
1903 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001904 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001905 if (readStatus != OK) {
1906 return AssertionFailure() << statusToString(readStatus);
1907 }
1908 if (readMessage != expectedMessage) {
1909 return AssertionFailure()
1910 << "Expected " << expectedMessage << ", actual " << readMessage;
1911 }
1912 return AssertionSuccess();
1913 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001914 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001915 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001916 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1917 return;
1918 }
1919 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001920 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001921 }
1922
Pawan49d74cb2022-08-03 21:19:11 +00001923 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1924
Yifan Hong1deca4b2021-09-10 16:16:44 -07001925 private:
1926 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001927 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001928 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1929 std::unique_ptr<RpcTransportCtx> mCtx;
1930 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1931 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001932 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001933 };
1934
1935 // Make A trust B.
1936 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001937 static status_t trust(RpcSecurity rpcSecurity,
1938 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1939 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001940 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001941 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1942 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1943 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001944 }
1945
1946 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001947};
1948
1949class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1950public:
1951 using Server = RpcTransportTestUtils::Server;
1952 using Client = RpcTransportTestUtils::Client;
1953 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001954 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001955 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1956 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001957 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001958 return ret;
1959 }
1960 static std::vector<ParamType> getRpcTranportTestParams() {
1961 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001962 for (auto serverVersion : testVersions()) {
1963 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1964 for (auto rpcSecurity : RpcSecurityValues()) {
1965 switch (rpcSecurity) {
1966 case RpcSecurity::RAW: {
1967 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1968 } break;
1969 case RpcSecurity::TLS: {
1970 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1971 serverVersion);
1972 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1973 serverVersion);
1974 } break;
1975 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001976 }
1977 }
1978 }
1979 return ret;
1980 }
1981 template <typename A, typename B>
1982 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001983 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1984 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001985 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1986 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001987 void SetUp() override {
1988 if constexpr (!kEnableRpcThreads) {
1989 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1990 }
1991 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001992};
1993
1994TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001995 auto server = std::make_unique<Server>();
1996 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001997
1998 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001999 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002000
2001 ASSERT_EQ(OK, trust(&client, server));
2002 ASSERT_EQ(OK, trust(server, &client));
2003
2004 server->start();
2005 client.run();
2006}
2007
2008TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002009 auto server = std::make_unique<Server>();
2010 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002011
2012 std::vector<Client> clients;
2013 for (int i = 0; i < 2; i++) {
2014 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002015 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002016 ASSERT_EQ(OK, trust(&client, server));
2017 ASSERT_EQ(OK, trust(server, &client));
2018 }
2019
2020 server->start();
2021 for (auto& client : clients) client.run();
2022}
2023
2024TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002025 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2026 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002027
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002028 auto untrustedServer = std::make_unique<Server>();
2029 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002030
2031 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002032 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002033
2034 ASSERT_EQ(OK, trust(untrustedServer, &client));
2035
2036 untrustedServer->start();
2037
2038 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2039 // the client can't verify the server's identity.
2040 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2041 client.run(handshakeOk);
2042}
2043TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002044 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2045 (void)serverVersion;
2046
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002047 auto validServer = std::make_unique<Server>();
2048 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002049
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002050 auto maliciousServer = std::make_unique<Server>();
2051 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002052
2053 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002054 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002055
2056 ASSERT_EQ(OK, trust(&client, validServer));
2057 ASSERT_EQ(OK, trust(validServer, &client));
2058 ASSERT_EQ(OK, trust(maliciousServer, &client));
2059
2060 maliciousServer->start();
2061
2062 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2063 // the client can't verify the server's identity.
2064 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2065 client.run(handshakeOk);
2066}
2067
2068TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002069 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2070 (void)serverVersion;
2071
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002072 auto server = std::make_unique<Server>();
2073 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002074
2075 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002076 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002077
2078 ASSERT_EQ(OK, trust(&client, server));
2079
2080 server->start();
2081
2082 // For TLS, Client should be able to verify server's identity, so client should see
2083 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2084 // identity and should drop the connection, so client shouldn't be able to read anything.
2085 bool readOk = rpcSecurity != RpcSecurity::TLS;
2086 client.run(true, readOk);
2087}
2088
2089TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002090 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2091 (void)serverVersion;
2092
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002093 auto server = std::make_unique<Server>();
2094 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002095
2096 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002097 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002098 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002099 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002100
2101 ASSERT_EQ(OK, trust(&validClient, server));
2102 ASSERT_EQ(OK, trust(&maliciousClient, server));
2103
2104 server->start();
2105
2106 // See UntrustedClient.
2107 bool readOk = rpcSecurity != RpcSecurity::TLS;
2108 maliciousClient.run(true, readOk);
2109}
2110
Yifan Hong67519322021-09-13 18:51:16 -07002111TEST_P(RpcTransportTest, Trigger) {
2112 std::string msg2 = ", world!";
2113 std::mutex writeMutex;
2114 std::condition_variable writeCv;
2115 bool shouldContinueWriting = false;
2116 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002117 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002118 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002119 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2120 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002121 if (status != OK) return AssertionFailure() << statusToString(status);
2122
2123 {
2124 std::unique_lock<std::mutex> lock(writeMutex);
2125 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2126 return AssertionFailure() << "write barrier not cleared in time!";
2127 }
2128 }
2129
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002130 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002131 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2132 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002133 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002134 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002135 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002136 << statusToString(status);
2137 return AssertionSuccess();
2138 };
2139
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002140 auto server = std::make_unique<Server>();
2141 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002142
2143 // Set up client
2144 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002145 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002146
2147 // Exchange keys
2148 ASSERT_EQ(OK, trust(&client, server));
2149 ASSERT_EQ(OK, trust(server, &client));
2150
2151 server->setPostConnect(serverPostConnect);
2152
Yifan Hong67519322021-09-13 18:51:16 -07002153 server->start();
2154 // connect() to server and do handshake
2155 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002156 // read the first message. This ensures that server has finished handshake and start handling
2157 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002158 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002159 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2160 // write is on an FdTrigger that has been shut down.
2161 server->shutdown();
2162 // Continues server thread to write the second message.
2163 {
Yifan Hong22211f82021-09-14 12:32:25 -07002164 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002165 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002166 }
Yifan Hong22211f82021-09-14 12:32:25 -07002167 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002168 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002169 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002170 // On the client side, second read fails with DEAD_OBJECT
2171 ASSERT_FALSE(client.readMessage(msg2));
2172}
2173
Pawan49d74cb2022-08-03 21:19:11 +00002174TEST_P(RpcTransportTest, CheckWaitingForRead) {
2175 std::mutex readMutex;
2176 std::condition_variable readCv;
2177 bool shouldContinueReading = false;
2178 // Server will write data on transport once its started
2179 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
2180 std::string message(RpcTransportTestUtils::kMessage);
2181 iovec messageIov{message.data(), message.size()};
2182 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2183 std::nullopt, nullptr);
2184 if (status != OK) return AssertionFailure() << statusToString(status);
2185
2186 {
2187 std::unique_lock<std::mutex> lock(readMutex);
2188 shouldContinueReading = true;
2189 lock.unlock();
2190 readCv.notify_all();
2191 }
2192 return AssertionSuccess();
2193 };
2194
2195 // Setup Server and client
2196 auto server = std::make_unique<Server>();
2197 ASSERT_TRUE(server->setUp(GetParam()));
2198
2199 Client client(server->getConnectToServerFn());
2200 ASSERT_TRUE(client.setUp(GetParam()));
2201
2202 ASSERT_EQ(OK, trust(&client, server));
2203 ASSERT_EQ(OK, trust(server, &client));
2204 server->setPostConnect(serverPostConnect);
2205
2206 server->start();
2207 ASSERT_TRUE(client.setUpTransport());
2208 {
2209 // Wait till server writes data
2210 std::unique_lock<std::mutex> lock(readMutex);
2211 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2212 }
2213
2214 // Since there is no read polling here, we will get polling count 0
2215 ASSERT_FALSE(client.isTransportWaiting());
2216 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2217 // Thread should increment polling count, read and decrement polling count
2218 // Again, polling count should be zero here
2219 ASSERT_FALSE(client.isTransportWaiting());
2220
2221 server->shutdown();
2222}
2223
Yifan Hong1deca4b2021-09-10 16:16:44 -07002224INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002225 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002226 RpcTransportTest::PrintParamInfo);
2227
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002228class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002229 : public testing::TestWithParam<
2230 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002231public:
2232 template <typename A, typename B>
2233 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002234 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2235 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002236 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2237 }
2238 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002239 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2240 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2241 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002242 };
2243};
2244
2245TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002246 if constexpr (!kEnableRpcThreads) {
2247 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2248 }
2249
Frederick Mayledc07cf82022-05-26 20:30:12 +00002250 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002251
2252 std::vector<uint8_t> pkeyData, certData;
2253 {
2254 auto pkey = makeKeyPairForSelfSignedCert();
2255 ASSERT_NE(nullptr, pkey);
2256 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2257 ASSERT_NE(nullptr, cert);
2258 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2259 certData = serializeCertificate(cert.get(), certificateFormat);
2260 }
2261
2262 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2263 auto desCert = deserializeCertificate(certData, certificateFormat);
2264 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002265 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2266 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002267
2268 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2269 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2270
2271 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2272 ASSERT_TRUE(client.setUp(utilsParam));
2273
2274 ASSERT_EQ(OK, trust(&client, server));
2275 ASSERT_EQ(OK, trust(server, &client));
2276
2277 server->start();
2278 client.run();
2279}
2280
2281INSTANTIATE_TEST_CASE_P(
2282 BinderRpc, RpcTransportTlsKeyTest,
2283 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2284 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002285 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2286 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002287 RpcTransportTlsKeyTest::PrintParamInfo);
2288
Steven Morelandc1635952021-04-01 16:20:47 +00002289} // namespace android
2290
2291int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002292 ::testing::InitGoogleTest(&argc, argv);
2293 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002294
Steven Moreland5553ac42020-11-11 02:14:45 +00002295 return RUN_ALL_TESTS();
2296}