blob: d736cd2de7e04af53fb7065255430b88fb78e908 [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
Steven Morelanddd231e22022-09-08 19:47:49 +0000801 usleep(10000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000802
803 // other calls still work
804 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
805
Steven Morelanddd231e22022-09-08 19:47:49 +0000806 constexpr size_t blockTimeMs = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000807 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
Frederick Mayleb0221d12022-10-03 23:10:53 +0000935TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
936 if (!supportsFdTransport()) {
937 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
938 }
939 if (clientOrServerSingleThreaded()) {
940 GTEST_SKIP() << "This test requires multiple threads";
941 }
942
943 // This test forces a oneway transaction to be queued by issuing two
944 // `blockingSendFdOneway` calls, then drains the queue by issuing two
945 // `blockingRecvFd` calls.
946 //
947 // For more details about the queuing semantics see
948 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
949
950 auto proc = createRpcTestSocketServerProcess({
951 .numThreads = 3,
952 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
953 .serverSupportedFileDescriptorTransportModes =
954 {RpcSession::FileDescriptorTransportMode::UNIX},
955 });
956
957 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
958 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
959 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
960 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
961
962 android::os::ParcelFileDescriptor fdA;
963 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
964 std::string result;
965 CHECK(android::base::ReadFdToString(fdA.get(), &result));
966 EXPECT_EQ(result, "a");
967
968 android::os::ParcelFileDescriptor fdB;
969 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
970 CHECK(android::base::ReadFdToString(fdB.get(), &result));
971 EXPECT_EQ(result, "b");
972}
973
Andrei Homescua858b0e2022-08-01 23:43:09 +0000974TEST_P(BinderRpc, OnewayCallQueueing) {
975 if (clientOrServerSingleThreaded()) {
976 GTEST_SKIP() << "This test requires multiple threads";
977 }
978
Steven Moreland5553ac42020-11-11 02:14:45 +0000979 constexpr size_t kNumSleeps = 10;
980 constexpr size_t kNumExtraServerThreads = 4;
981 constexpr size_t kSleepMs = 50;
982
983 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000984 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000985
986 EXPECT_OK(proc.rootIface->lock());
987
Steven Moreland1c678802021-09-17 16:48:47 -0700988 size_t epochMsBefore = epochMillis();
989
990 // all these *Async commands should be queued on the server sequentially,
991 // even though there are multiple threads.
992 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000993 proc.rootIface->sleepMsAsync(kSleepMs);
994 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000995 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
996
Steven Moreland1c678802021-09-17 16:48:47 -0700997 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +0000998 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -0700999
Steven Moreland5553ac42020-11-11 02:14:45 +00001000 size_t epochMsAfter = epochMillis();
1001
Frederick Mayle3fa815d2022-07-12 22:52:52 +00001002 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001003
Steven Moreland925ba0a2021-09-17 18:06:32 -07001004 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001005}
1006
Andrei Homescua858b0e2022-08-01 23:43:09 +00001007TEST_P(BinderRpc, OnewayCallExhaustion) {
1008 if (clientOrServerSingleThreaded()) {
1009 GTEST_SKIP() << "This test requires multiple threads";
1010 }
1011
Steven Morelandd45be622021-06-04 02:19:37 +00001012 constexpr size_t kNumClients = 2;
1013 constexpr size_t kTooLongMs = 1000;
1014
Steven Moreland4313d7e2021-07-15 23:41:22 +00001015 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001016
1017 // Build up oneway calls on the second session to make sure it terminates
1018 // and shuts down. The first session should be unaffected (proc destructor
1019 // checks the first session).
1020 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1021
1022 std::vector<std::thread> threads;
1023 for (size_t i = 0; i < kNumClients; i++) {
1024 // one of these threads will get stuck queueing a transaction once the
1025 // socket fills up, the other will be able to fill up transactions on
1026 // this object
1027 threads.push_back(std::thread([&] {
1028 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1029 }
1030 }));
1031 }
1032 for (auto& t : threads) t.join();
1033
1034 Status status = iface->sleepMsAsync(kTooLongMs);
1035 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1036
Steven Moreland798e0d12021-07-14 23:19:25 +00001037 // now that it has died, wait for the remote session to shutdown
1038 std::vector<int32_t> remoteCounts;
1039 do {
1040 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1041 } while (remoteCounts.size() == kNumClients);
1042
Steven Morelandd45be622021-06-04 02:19:37 +00001043 // the second session should be shutdown in the other process by the time we
1044 // are able to join above (it'll only be hung up once it finishes processing
1045 // any pending commands). We need to erase this session from the record
1046 // here, so that the destructor for our session won't check that this
1047 // session is valid, but we still want it to test the other session.
1048 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1049}
1050
Steven Moreland659416d2021-05-11 00:47:50 +00001051TEST_P(BinderRpc, Callbacks) {
1052 const static std::string kTestString = "good afternoon!";
1053
Steven Morelandc7d40132021-06-10 03:42:11 +00001054 for (bool callIsOneway : {true, false}) {
1055 for (bool callbackIsOneway : {true, false}) {
1056 for (bool delayed : {true, false}) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001057 if (clientOrServerSingleThreaded() &&
1058 (callIsOneway || callbackIsOneway || delayed)) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001059 // we have no incoming connections to receive the callback
1060 continue;
1061 }
1062
Andrei Homescua858b0e2022-08-01 23:43:09 +00001063 size_t numIncomingConnections = clientOrServerSingleThreaded() ? 0 : 1;
Steven Moreland4313d7e2021-07-15 23:41:22 +00001064 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +00001065 {.numThreads = 1,
1066 .numSessions = 1,
Andrei Homescu2a298012022-06-15 01:08:54 +00001067 .numIncomingConnections = numIncomingConnections});
Steven Morelandc7d40132021-06-10 03:42:11 +00001068 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001069
Steven Morelandc7d40132021-06-10 03:42:11 +00001070 if (callIsOneway) {
1071 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1072 kTestString));
1073 } else {
1074 EXPECT_OK(
1075 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1076 }
Steven Moreland659416d2021-05-11 00:47:50 +00001077
Steven Moreland03ecce62022-05-13 23:22:05 +00001078 // if both transactions are synchronous and the response is sent back on the
1079 // same thread, everything should have happened in a nested call. Otherwise,
1080 // the callback will be processed on another thread.
1081 if (callIsOneway || callbackIsOneway || delayed) {
1082 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001083 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001084 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1085 }
Steven Moreland659416d2021-05-11 00:47:50 +00001086
Steven Morelandc7d40132021-06-10 03:42:11 +00001087 EXPECT_EQ(cb->mValues.size(), 1)
1088 << "callIsOneway: " << callIsOneway
1089 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1090 if (cb->mValues.empty()) continue;
1091 EXPECT_EQ(cb->mValues.at(0), kTestString)
1092 << "callIsOneway: " << callIsOneway
1093 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001094
Steven Morelandc7d40132021-06-10 03:42:11 +00001095 // since we are severing the connection, we need to go ahead and
1096 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001097 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1098 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1099 }
Steven Moreland659416d2021-05-11 00:47:50 +00001100
Steven Moreland1b304292021-07-15 22:59:34 +00001101 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001102 // need to manually shut it down
1103 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Morelandc7d40132021-06-10 03:42:11 +00001104 proc.expectAlreadyShutdown = true;
1105 }
Steven Moreland659416d2021-05-11 00:47:50 +00001106 }
1107 }
1108}
1109
Devin Moore66d5b7a2022-07-07 21:42:10 +00001110TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001111 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001112 GTEST_SKIP() << "This test requires multiple threads";
1113 }
1114 class MyDeathRec : public IBinder::DeathRecipient {
1115 public:
1116 void binderDied(const wp<IBinder>& /* who */) override {
1117 dead = true;
1118 mCv.notify_one();
1119 }
1120 std::mutex mMtx;
1121 std::condition_variable mCv;
1122 bool dead = false;
1123 };
1124
1125 // Death recipient needs to have an incoming connection to be called
1126 auto proc = createRpcTestSocketServerProcess(
1127 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1128
1129 auto dr = sp<MyDeathRec>::make();
1130 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1131
1132 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1133 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1134 }
1135
1136 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +00001137 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001138
1139 // need to wait for the session to shutdown so we don't "Leak session"
1140 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1141 proc.expectAlreadyShutdown = true;
1142}
1143
1144TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001145 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001146 GTEST_SKIP() << "This test requires multiple threads";
1147 }
1148 class MyDeathRec : public IBinder::DeathRecipient {
1149 public:
1150 void binderDied(const wp<IBinder>& /* who */) override {
1151 dead = true;
1152 mCv.notify_one();
1153 }
1154 std::mutex mMtx;
1155 std::condition_variable mCv;
1156 bool dead = false;
1157 };
1158
1159 // Death recipient needs to have an incoming connection to be called
1160 auto proc = createRpcTestSocketServerProcess(
1161 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1162
1163 auto dr = sp<MyDeathRec>::make();
1164 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1165
1166 // Explicitly calling shutDownAndWait will cause the death recipients
1167 // to be called.
1168 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1169
1170 std::unique_lock<std::mutex> lock(dr->mMtx);
1171 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001172 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001173 }
1174 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1175
1176 proc.proc.host.terminate();
1177 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1178 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1179 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1180 });
1181 proc.expectAlreadyShutdown = true;
1182}
1183
1184TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1185 class MyDeathRec : public IBinder::DeathRecipient {
1186 public:
1187 void binderDied(const wp<IBinder>& /* who */) override {}
1188 };
1189
1190 auto proc = createRpcTestSocketServerProcess(
1191 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1192
1193 auto dr = sp<MyDeathRec>::make();
1194 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1195 "Cannot register a DeathRecipient without any incoming connections.");
1196}
1197
1198TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001199 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001200 GTEST_SKIP() << "This test requires multiple threads";
1201 }
1202 class MyDeathRec : public IBinder::DeathRecipient {
1203 public:
1204 void binderDied(const wp<IBinder>& /* who */) override {
1205 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1206 }
1207 };
1208
1209 // Death recipient needs to have an incoming connection to be called
1210 auto proc = createRpcTestSocketServerProcess(
1211 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1212
1213 auto dr = sp<MyDeathRec>::make();
1214 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1215 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1216
1217 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1218 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1219 }
1220
1221 // need to wait for the session to shutdown so we don't "Leak session"
1222 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1223 proc.expectAlreadyShutdown = true;
1224}
1225
Steven Moreland195edb82021-06-08 02:44:39 +00001226TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001227 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001228 auto cb = sp<MyBinderRpcCallback>::make();
1229
1230 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1231 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1232}
1233
Steven Morelandc1635952021-04-01 16:20:47 +00001234TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001235 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001236 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001237
1238 // make sure there is some state during crash
1239 // 1. we hold their binder
1240 sp<IBinderRpcSession> session;
1241 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1242 // 2. they hold our binder
1243 sp<IBinder> binder = new BBinder();
1244 EXPECT_OK(proc.rootIface->holdBinder(binder));
1245
1246 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1247 << "Do death cleanup: " << doDeathCleanup;
1248
Frederick Maylea12b0962022-06-25 01:13:22 +00001249 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1250 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1251 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1252 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001253 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001254 }
1255}
1256
Steven Morelandd7302072021-05-15 01:32:04 +00001257TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001258 // This test only works if the current process shared the internal state of
1259 // ProcessState with the service across the call to fork(). Both the static
1260 // libraries and libbinder.so have their own separate copies of all the
1261 // globals, so the test only works when the test client and service both use
1262 // libbinder.so (when using static libraries, even a client and service
1263 // using the same kind of static library should have separate copies of the
1264 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +00001265 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001266 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1267 "at build time.";
1268 }
1269
Steven Moreland4313d7e2021-07-15 23:41:22 +00001270 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001271
Andrei Homescu2a298012022-06-15 01:08:54 +00001272 // we can't allocate IPCThreadState so actually the first time should
1273 // succeed :(
1274 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001275
1276 // second time! we catch the error :)
1277 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1278
Frederick Maylea12b0962022-06-25 01:13:22 +00001279 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1280 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1281 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1282 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001283 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001284}
1285
Frederick Mayle69a0c992022-05-26 20:38:39 +00001286TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1287 auto proc = createRpcTestSocketServerProcess({
1288 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1289 .serverSupportedFileDescriptorTransportModes =
1290 {RpcSession::FileDescriptorTransportMode::UNIX},
1291 .allowConnectFailure = true,
1292 });
1293 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1294 proc.proc.host.terminate();
1295 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1296 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1297 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1298 });
1299 proc.expectAlreadyShutdown = true;
1300}
1301
1302TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1303 auto proc = createRpcTestSocketServerProcess({
1304 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1305 .serverSupportedFileDescriptorTransportModes =
1306 {RpcSession::FileDescriptorTransportMode::NONE},
1307 .allowConnectFailure = true,
1308 });
1309 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1310 proc.proc.host.terminate();
1311 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1312 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1313 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1314 });
1315 proc.expectAlreadyShutdown = true;
1316}
1317
1318TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1319 auto proc = createRpcTestSocketServerProcess({
1320 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1321 .serverSupportedFileDescriptorTransportModes =
1322 {RpcSession::FileDescriptorTransportMode::NONE,
1323 RpcSession::FileDescriptorTransportMode::UNIX},
1324 });
1325
1326 android::os::ParcelFileDescriptor out;
1327 auto status = proc.rootIface->echoAsFile("hello", &out);
1328 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1329}
1330
1331TEST_P(BinderRpc, ReceiveFile) {
1332 auto proc = createRpcTestSocketServerProcess({
1333 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1334 .serverSupportedFileDescriptorTransportModes =
1335 {RpcSession::FileDescriptorTransportMode::UNIX},
1336 });
1337
1338 android::os::ParcelFileDescriptor out;
1339 auto status = proc.rootIface->echoAsFile("hello", &out);
1340 if (!supportsFdTransport()) {
1341 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1342 return;
1343 }
1344 ASSERT_TRUE(status.isOk()) << status;
1345
1346 std::string result;
1347 CHECK(android::base::ReadFdToString(out.get(), &result));
1348 EXPECT_EQ(result, "hello");
1349}
1350
1351TEST_P(BinderRpc, SendFiles) {
1352 auto proc = createRpcTestSocketServerProcess({
1353 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1354 .serverSupportedFileDescriptorTransportModes =
1355 {RpcSession::FileDescriptorTransportMode::UNIX},
1356 });
1357
1358 std::vector<android::os::ParcelFileDescriptor> files;
1359 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1360 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1361 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1362 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1363
1364 android::os::ParcelFileDescriptor out;
1365 auto status = proc.rootIface->concatFiles(files, &out);
1366 if (!supportsFdTransport()) {
1367 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1368 return;
1369 }
1370 ASSERT_TRUE(status.isOk()) << status;
1371
1372 std::string result;
1373 CHECK(android::base::ReadFdToString(out.get(), &result));
1374 EXPECT_EQ(result, "123abcd");
1375}
1376
1377TEST_P(BinderRpc, SendMaxFiles) {
1378 if (!supportsFdTransport()) {
1379 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1380 }
1381
1382 auto proc = createRpcTestSocketServerProcess({
1383 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1384 .serverSupportedFileDescriptorTransportModes =
1385 {RpcSession::FileDescriptorTransportMode::UNIX},
1386 });
1387
1388 std::vector<android::os::ParcelFileDescriptor> files;
1389 for (int i = 0; i < 253; i++) {
1390 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1391 }
1392
1393 android::os::ParcelFileDescriptor out;
1394 auto status = proc.rootIface->concatFiles(files, &out);
1395 ASSERT_TRUE(status.isOk()) << status;
1396
1397 std::string result;
1398 CHECK(android::base::ReadFdToString(out.get(), &result));
1399 EXPECT_EQ(result, std::string(253, 'a'));
1400}
1401
1402TEST_P(BinderRpc, SendTooManyFiles) {
1403 if (!supportsFdTransport()) {
1404 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1405 }
1406
1407 auto proc = createRpcTestSocketServerProcess({
1408 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1409 .serverSupportedFileDescriptorTransportModes =
1410 {RpcSession::FileDescriptorTransportMode::UNIX},
1411 });
1412
1413 std::vector<android::os::ParcelFileDescriptor> files;
1414 for (int i = 0; i < 254; i++) {
1415 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1416 }
1417
1418 android::os::ParcelFileDescriptor out;
1419 auto status = proc.rootIface->concatFiles(files, &out);
1420 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1421}
1422
Steven Moreland37aff182021-03-26 02:04:16 +00001423TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001424 if constexpr (!kEnableSharedLibs) {
1425 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1426 }
1427
Steven Moreland4313d7e2021-07-15 23:41:22 +00001428 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001429
1430 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1431 ASSERT_NE(binder, nullptr);
1432
1433 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1434}
1435
1436TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001437 if constexpr (!kEnableSharedLibs) {
1438 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1439 }
1440
Steven Moreland4313d7e2021-07-15 23:41:22 +00001441 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001442
1443 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1444 ASSERT_NE(binder, nullptr);
1445
1446 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1447 ASSERT_NE(ndkBinder, nullptr);
1448
1449 std::string out;
1450 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1451 ASSERT_TRUE(status.isOk()) << status.getDescription();
1452 ASSERT_EQ("aoeuaoeu", out);
1453}
1454
Steven Moreland5553ac42020-11-11 02:14:45 +00001455ssize_t countFds() {
1456 DIR* dir = opendir("/proc/self/fd/");
1457 if (dir == nullptr) return -1;
1458 ssize_t ret = 0;
1459 dirent* ent;
1460 while ((ent = readdir(dir)) != nullptr) ret++;
1461 closedir(dir);
1462 return ret;
1463}
1464
Andrei Homescua858b0e2022-08-01 23:43:09 +00001465TEST_P(BinderRpc, Fds) {
1466 if (serverSingleThreaded()) {
1467 GTEST_SKIP() << "This test requires multiple threads";
1468 }
1469
Steven Moreland5553ac42020-11-11 02:14:45 +00001470 ssize_t beforeFds = countFds();
1471 ASSERT_GE(beforeFds, 0);
1472 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001473 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001474 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1475 }
1476 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1477}
1478
Devin Moore800b2252021-10-15 16:22:57 +00001479TEST_P(BinderRpc, AidlDelegatorTest) {
1480 auto proc = createRpcTestSocketServerProcess({});
1481 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1482 ASSERT_NE(nullptr, myDelegator);
1483
1484 std::string doubled;
1485 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1486 EXPECT_EQ("cool cool ", doubled);
1487}
1488
Steven Morelandda573042021-06-12 01:13:45 +00001489static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001490 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001491 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001492
Andrei Homescu992a4052022-06-28 21:26:18 +00001493 android::base::unique_fd serverFd(
1494 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1495 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1496
1497 sockaddr_vm serverAddr{
1498 .svm_family = AF_VSOCK,
1499 .svm_port = vsockPort,
1500 .svm_cid = VMADDR_CID_ANY,
1501 };
1502 int ret = TEMP_FAILURE_RETRY(
1503 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1504 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1505 strerror(errno));
1506
1507 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1508 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1509 strerror(errno));
1510
1511 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1512 // to see if the kernel supports it. It's safe to use a blocking
1513 // connect because vsock sockets have a 2 second connection timeout,
1514 // and they return ETIMEDOUT after that.
1515 android::base::unique_fd connectFd(
1516 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1517 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1518 strerror(errno));
1519
1520 bool success = false;
1521 sockaddr_vm connectAddr{
1522 .svm_family = AF_VSOCK,
1523 .svm_port = vsockPort,
1524 .svm_cid = VMADDR_CID_LOCAL,
1525 };
1526 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1527 sizeof(connectAddr)));
1528 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1529 android::base::unique_fd acceptFd;
1530 while (true) {
1531 pollfd pfd[]{
1532 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1533 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1534 };
1535 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1536 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1537
1538 if (pfd[0].revents & POLLIN) {
1539 sockaddr_vm acceptAddr;
1540 socklen_t acceptAddrLen = sizeof(acceptAddr);
1541 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1542 reinterpret_cast<sockaddr*>(&acceptAddr),
1543 &acceptAddrLen, SOCK_CLOEXEC));
1544 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1545 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1546 "Truncated address");
1547
1548 // Store the fd in acceptFd so we keep the connection alive
1549 // while polling connectFd
1550 acceptFd.reset(ret);
1551 }
1552
1553 if (pfd[1].revents & POLLOUT) {
1554 // Connect either succeeded or timed out
1555 int connectErrno;
1556 socklen_t connectErrnoLen = sizeof(connectErrno);
1557 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1558 &connectErrnoLen);
1559 LOG_ALWAYS_FATAL_IF(ret == -1,
1560 "Could not getsockopt() after connect() "
1561 "on non-blocking socket: %s.",
1562 strerror(errno));
1563
1564 // We're done, this is all we wanted
1565 success = connectErrno == 0;
1566 break;
1567 }
1568 }
1569 } else {
1570 success = ret == 0;
1571 }
1572
1573 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1574
1575 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001576}
1577
Yifan Hong1deca4b2021-09-10 16:16:44 -07001578static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1579 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1580
1581 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001582
1583 static bool hasVsockLoopback = testSupportVsockLoopback();
1584
1585 if (hasVsockLoopback) {
1586 ret.push_back(SocketType::VSOCK);
1587 }
1588
1589 return ret;
1590}
1591
Frederick Mayledc07cf82022-05-26 20:30:12 +00001592static std::vector<uint32_t> testVersions() {
1593 std::vector<uint32_t> versions;
1594 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1595 versions.push_back(i);
1596 }
1597 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1598 return versions;
1599}
1600
Yifan Hong702115c2021-06-24 15:39:18 -07001601INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1602 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001603 ::testing::ValuesIn(RpcSecurityValues()),
1604 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001605 ::testing::ValuesIn(testVersions()),
1606 ::testing::Values(false, true),
1607 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001608 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001609
Yifan Hong702115c2021-06-24 15:39:18 -07001610class BinderRpcServerRootObject
1611 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001612
1613TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1614 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1615 auto setRootObject = [](bool isStrong) -> SetFn {
1616 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1617 };
1618
Yifan Hong702115c2021-06-24 15:39:18 -07001619 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1620 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001621 auto binder1 = sp<BBinder>::make();
1622 IBinder* binderRaw1 = binder1.get();
1623 setRootObject(isStrong1)(server.get(), binder1);
1624 EXPECT_EQ(binderRaw1, server->getRootObject());
1625 binder1.clear();
1626 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1627
1628 auto binder2 = sp<BBinder>::make();
1629 IBinder* binderRaw2 = binder2.get();
1630 setRootObject(isStrong2)(server.get(), binder2);
1631 EXPECT_EQ(binderRaw2, server->getRootObject());
1632 binder2.clear();
1633 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1634}
1635
1636INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001637 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1638 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001639
Yifan Hong1a235852021-05-13 16:07:47 -07001640class OneOffSignal {
1641public:
1642 // If notify() was previously called, or is called within |duration|, return true; else false.
1643 template <typename R, typename P>
1644 bool wait(std::chrono::duration<R, P> duration) {
1645 std::unique_lock<std::mutex> lock(mMutex);
1646 return mCv.wait_for(lock, duration, [this] { return mValue; });
1647 }
1648 void notify() {
1649 std::unique_lock<std::mutex> lock(mMutex);
1650 mValue = true;
1651 lock.unlock();
1652 mCv.notify_all();
1653 }
1654
1655private:
1656 std::mutex mMutex;
1657 std::condition_variable mCv;
1658 bool mValue = false;
1659};
1660
Yifan Hong194acf22021-06-29 18:44:56 -07001661TEST(BinderRpc, Java) {
1662#if !defined(__ANDROID__)
1663 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1664 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1665 "to binderHostDeviceTest. Hence, just disable this test on host.";
1666#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001667 if constexpr (!kEnableKernelIpc) {
1668 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1669 "at build time.";
1670 }
1671
Yifan Hong194acf22021-06-29 18:44:56 -07001672 sp<IServiceManager> sm = defaultServiceManager();
1673 ASSERT_NE(nullptr, sm);
1674 // Any Java service with non-empty getInterfaceDescriptor() would do.
1675 // Let's pick batteryproperties.
1676 auto binder = sm->checkService(String16("batteryproperties"));
1677 ASSERT_NE(nullptr, binder);
1678 auto descriptor = binder->getInterfaceDescriptor();
1679 ASSERT_GE(descriptor.size(), 0);
1680 ASSERT_EQ(OK, binder->pingBinder());
1681
1682 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001683 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001684 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001685 auto socket = rpcServer->releaseServer();
1686
1687 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001688 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1689
Yifan Honge3caaf22022-01-12 14:46:56 -08001690 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1691 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001692 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001693 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1694 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001695 << statusToString(setRpcClientDebugStatus);
1696 GTEST_SKIP();
1697 }
1698
1699 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001700
1701 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001702 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001703 auto rpcBinder = rpcSession->getRootObject();
1704 ASSERT_NE(nullptr, rpcBinder);
1705
1706 ASSERT_EQ(OK, rpcBinder->pingBinder());
1707
1708 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1709 << "getInterfaceDescriptor should not crash system_server";
1710 ASSERT_EQ(OK, rpcBinder->pingBinder());
1711}
1712
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001713class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1714public:
1715 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1716 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1717 std::to_string(std::get<1>(info.param));
1718 }
1719};
1720
1721TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1722 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1723 int sinkFd = sink.get();
1724 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1725 server->setProtocolVersion(std::get<1>(GetParam()));
1726 ASSERT_FALSE(server->hasServer());
1727 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1728 ASSERT_TRUE(server->hasServer());
1729 base::unique_fd retrieved = server->releaseServer();
1730 ASSERT_FALSE(server->hasServer());
1731 ASSERT_EQ(sinkFd, retrieved.get());
1732}
1733
1734TEST_P(BinderRpcServerOnly, Shutdown) {
1735 if constexpr (!kEnableRpcThreads) {
1736 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1737 }
1738
1739 auto addr = allocateSocketAddress();
1740 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1741 server->setProtocolVersion(std::get<1>(GetParam()));
1742 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1743 auto joinEnds = std::make_shared<OneOffSignal>();
1744
1745 // If things are broken and the thread never stops, don't block other tests. Because the thread
1746 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1747 // shared pointers are passed.
1748 std::thread([server, joinEnds] {
1749 server->join();
1750 joinEnds->notify();
1751 }).detach();
1752
1753 bool shutdown = false;
1754 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001755 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001756 if (server->shutdown()) shutdown = true;
1757 }
1758 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1759
1760 ASSERT_TRUE(joinEnds->wait(2s))
1761 << "After server->shutdown() returns true, join() did not stop after 2s";
1762}
1763
Frederick Mayledc07cf82022-05-26 20:30:12 +00001764INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1765 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1766 ::testing::ValuesIn(testVersions())),
1767 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001768
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001769class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001770public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001771 // Only parameterized only server version because `RpcSession` is bypassed
1772 // in the client half of the tests.
1773 using Param =
1774 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001775 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001776
1777 // A server that handles client socket connections.
1778 class Server {
1779 public:
1780 explicit Server() {}
1781 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001782 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001783 [[nodiscard]] AssertionResult setUp(
1784 const Param& param,
1785 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001786 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001787 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001788 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001789 switch (socketType) {
1790 case SocketType::PRECONNECTED: {
1791 return AssertionFailure() << "Not supported by this test";
1792 } break;
1793 case SocketType::UNIX: {
1794 auto addr = allocateSocketAddress();
1795 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1796 if (status != OK) {
1797 return AssertionFailure()
1798 << "setupUnixDomainServer: " << statusToString(status);
1799 }
1800 mConnectToServer = [addr] {
1801 return connectTo(UnixSocketAddress(addr.c_str()));
1802 };
1803 } break;
1804 case SocketType::VSOCK: {
1805 auto port = allocateVsockPort();
1806 auto status = rpcServer->setupVsockServer(port);
1807 if (status != OK) {
1808 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1809 }
1810 mConnectToServer = [port] {
1811 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1812 };
1813 } break;
1814 case SocketType::INET: {
1815 unsigned int port;
1816 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1817 if (status != OK) {
1818 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1819 }
1820 mConnectToServer = [port] {
1821 const char* addr = kLocalInetAddress;
1822 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1823 if (aiStart == nullptr) return base::unique_fd{};
1824 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1825 auto fd = connectTo(
1826 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1827 if (fd.ok()) return fd;
1828 }
1829 ALOGE("None of the socket address resolved for %s:%u can be connected",
1830 addr, port);
1831 return base::unique_fd{};
1832 };
1833 }
1834 }
1835 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001836 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001837 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001838 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1839 mSetup = true;
1840 return AssertionSuccess();
1841 }
1842 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1843 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1844 return mCertVerifier;
1845 }
1846 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1847 void start() {
1848 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1849 mThread = std::make_unique<std::thread>(&Server::run, this);
1850 }
1851 void run() {
1852 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1853
1854 std::vector<std::thread> threads;
1855 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1856 base::unique_fd acceptedFd(
Pawan49d74cb2022-08-03 21:19:11 +00001857 TEMP_FAILURE_RETRY(accept4(mFd.fd.get(), nullptr, nullptr /*length*/,
Yifan Hong1deca4b2021-09-10 16:16:44 -07001858 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1859 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1860 }
1861
1862 for (auto& thread : threads) thread.join();
1863 }
1864 void handleOne(android::base::unique_fd acceptedFd) {
1865 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001866 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001867 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001868 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001869 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001870 }
Yifan Honge07d2732021-09-13 21:59:14 -07001871 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001872 shutdown();
1873 join();
1874 }
1875 void shutdown() { mFdTrigger->trigger(); }
1876
1877 void setPostConnect(
1878 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1879 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001880 }
1881
1882 private:
1883 std::unique_ptr<std::thread> mThread;
1884 ConnectToServer mConnectToServer;
1885 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
Pawan3e0061c2022-08-26 21:08:34 +00001886 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001887 std::unique_ptr<RpcTransportCtx> mCtx;
1888 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1889 std::make_shared<RpcCertificateVerifierSimple>();
1890 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001891 // The function invoked after connection and handshake. By default, it is
1892 // |defaultPostConnect| that sends |kMessage| to the client.
1893 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1894 Server::defaultPostConnect;
1895
1896 void join() {
1897 if (mThread != nullptr) {
1898 mThread->join();
1899 mThread = nullptr;
1900 }
1901 }
1902
1903 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1904 FdTrigger* fdTrigger) {
1905 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001906 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001907 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001908 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001909 if (status != OK) return AssertionFailure() << statusToString(status);
1910 return AssertionSuccess();
1911 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001912 };
1913
1914 class Client {
1915 public:
1916 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1917 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001918 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001919 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1920 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001921 mFdTrigger = FdTrigger::make();
1922 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1923 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1924 return AssertionSuccess();
1925 }
1926 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1927 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1928 return mCertVerifier;
1929 }
Yifan Hong67519322021-09-13 18:51:16 -07001930 // connect() and do handshake
1931 bool setUpTransport() {
1932 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001933 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001934 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1935 return mClientTransport != nullptr;
1936 }
1937 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1938 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1939 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001940 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001941 status_t readStatus =
1942 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001943 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001944 if (readStatus != OK) {
1945 return AssertionFailure() << statusToString(readStatus);
1946 }
1947 if (readMessage != expectedMessage) {
1948 return AssertionFailure()
1949 << "Expected " << expectedMessage << ", actual " << readMessage;
1950 }
1951 return AssertionSuccess();
1952 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001953 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001954 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001955 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1956 return;
1957 }
1958 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001959 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001960 }
1961
Pawan49d74cb2022-08-03 21:19:11 +00001962 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1963
Yifan Hong1deca4b2021-09-10 16:16:44 -07001964 private:
1965 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001966 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001967 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1968 std::unique_ptr<RpcTransportCtx> mCtx;
1969 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1970 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001971 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001972 };
1973
1974 // Make A trust B.
1975 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001976 static status_t trust(RpcSecurity rpcSecurity,
1977 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1978 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001979 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001980 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1981 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1982 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001983 }
1984
1985 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001986};
1987
1988class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1989public:
1990 using Server = RpcTransportTestUtils::Server;
1991 using Client = RpcTransportTestUtils::Client;
1992 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001993 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001994 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1995 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001996 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001997 return ret;
1998 }
1999 static std::vector<ParamType> getRpcTranportTestParams() {
2000 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00002001 for (auto serverVersion : testVersions()) {
2002 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
2003 for (auto rpcSecurity : RpcSecurityValues()) {
2004 switch (rpcSecurity) {
2005 case RpcSecurity::RAW: {
2006 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
2007 } break;
2008 case RpcSecurity::TLS: {
2009 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
2010 serverVersion);
2011 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
2012 serverVersion);
2013 } break;
2014 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002015 }
2016 }
2017 }
2018 return ret;
2019 }
2020 template <typename A, typename B>
2021 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002022 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2023 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002024 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
2025 }
Andrei Homescu12106de2022-04-27 04:42:21 +00002026 void SetUp() override {
2027 if constexpr (!kEnableRpcThreads) {
2028 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2029 }
2030 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002031};
2032
2033TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002034 auto server = std::make_unique<Server>();
2035 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002036
2037 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002038 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002039
2040 ASSERT_EQ(OK, trust(&client, server));
2041 ASSERT_EQ(OK, trust(server, &client));
2042
2043 server->start();
2044 client.run();
2045}
2046
2047TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002048 auto server = std::make_unique<Server>();
2049 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002050
2051 std::vector<Client> clients;
2052 for (int i = 0; i < 2; i++) {
2053 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002054 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002055 ASSERT_EQ(OK, trust(&client, server));
2056 ASSERT_EQ(OK, trust(server, &client));
2057 }
2058
2059 server->start();
2060 for (auto& client : clients) client.run();
2061}
2062
2063TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002064 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2065 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002066
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002067 auto untrustedServer = std::make_unique<Server>();
2068 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002069
2070 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002071 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002072
2073 ASSERT_EQ(OK, trust(untrustedServer, &client));
2074
2075 untrustedServer->start();
2076
2077 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2078 // the client can't verify the server's identity.
2079 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2080 client.run(handshakeOk);
2081}
2082TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002083 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2084 (void)serverVersion;
2085
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002086 auto validServer = std::make_unique<Server>();
2087 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002088
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002089 auto maliciousServer = std::make_unique<Server>();
2090 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002091
2092 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002093 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002094
2095 ASSERT_EQ(OK, trust(&client, validServer));
2096 ASSERT_EQ(OK, trust(validServer, &client));
2097 ASSERT_EQ(OK, trust(maliciousServer, &client));
2098
2099 maliciousServer->start();
2100
2101 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2102 // the client can't verify the server's identity.
2103 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2104 client.run(handshakeOk);
2105}
2106
2107TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002108 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2109 (void)serverVersion;
2110
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002111 auto server = std::make_unique<Server>();
2112 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002113
2114 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002115 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002116
2117 ASSERT_EQ(OK, trust(&client, server));
2118
2119 server->start();
2120
2121 // For TLS, Client should be able to verify server's identity, so client should see
2122 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2123 // identity and should drop the connection, so client shouldn't be able to read anything.
2124 bool readOk = rpcSecurity != RpcSecurity::TLS;
2125 client.run(true, readOk);
2126}
2127
2128TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002129 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2130 (void)serverVersion;
2131
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002132 auto server = std::make_unique<Server>();
2133 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002134
2135 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002136 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002137 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002138 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002139
2140 ASSERT_EQ(OK, trust(&validClient, server));
2141 ASSERT_EQ(OK, trust(&maliciousClient, server));
2142
2143 server->start();
2144
2145 // See UntrustedClient.
2146 bool readOk = rpcSecurity != RpcSecurity::TLS;
2147 maliciousClient.run(true, readOk);
2148}
2149
Yifan Hong67519322021-09-13 18:51:16 -07002150TEST_P(RpcTransportTest, Trigger) {
2151 std::string msg2 = ", world!";
2152 std::mutex writeMutex;
2153 std::condition_variable writeCv;
2154 bool shouldContinueWriting = false;
2155 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002156 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002157 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002158 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2159 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002160 if (status != OK) return AssertionFailure() << statusToString(status);
2161
2162 {
2163 std::unique_lock<std::mutex> lock(writeMutex);
2164 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2165 return AssertionFailure() << "write barrier not cleared in time!";
2166 }
2167 }
2168
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002169 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002170 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2171 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002172 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002173 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002174 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002175 << statusToString(status);
2176 return AssertionSuccess();
2177 };
2178
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002179 auto server = std::make_unique<Server>();
2180 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002181
2182 // Set up client
2183 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002184 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002185
2186 // Exchange keys
2187 ASSERT_EQ(OK, trust(&client, server));
2188 ASSERT_EQ(OK, trust(server, &client));
2189
2190 server->setPostConnect(serverPostConnect);
2191
Yifan Hong67519322021-09-13 18:51:16 -07002192 server->start();
2193 // connect() to server and do handshake
2194 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002195 // read the first message. This ensures that server has finished handshake and start handling
2196 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002197 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002198 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2199 // write is on an FdTrigger that has been shut down.
2200 server->shutdown();
2201 // Continues server thread to write the second message.
2202 {
Yifan Hong22211f82021-09-14 12:32:25 -07002203 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002204 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002205 }
Yifan Hong22211f82021-09-14 12:32:25 -07002206 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002207 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002208 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002209 // On the client side, second read fails with DEAD_OBJECT
2210 ASSERT_FALSE(client.readMessage(msg2));
2211}
2212
Pawan49d74cb2022-08-03 21:19:11 +00002213TEST_P(RpcTransportTest, CheckWaitingForRead) {
2214 std::mutex readMutex;
2215 std::condition_variable readCv;
2216 bool shouldContinueReading = false;
2217 // Server will write data on transport once its started
2218 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
2219 std::string message(RpcTransportTestUtils::kMessage);
2220 iovec messageIov{message.data(), message.size()};
2221 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2222 std::nullopt, nullptr);
2223 if (status != OK) return AssertionFailure() << statusToString(status);
2224
2225 {
2226 std::unique_lock<std::mutex> lock(readMutex);
2227 shouldContinueReading = true;
2228 lock.unlock();
2229 readCv.notify_all();
2230 }
2231 return AssertionSuccess();
2232 };
2233
2234 // Setup Server and client
2235 auto server = std::make_unique<Server>();
2236 ASSERT_TRUE(server->setUp(GetParam()));
2237
2238 Client client(server->getConnectToServerFn());
2239 ASSERT_TRUE(client.setUp(GetParam()));
2240
2241 ASSERT_EQ(OK, trust(&client, server));
2242 ASSERT_EQ(OK, trust(server, &client));
2243 server->setPostConnect(serverPostConnect);
2244
2245 server->start();
2246 ASSERT_TRUE(client.setUpTransport());
2247 {
2248 // Wait till server writes data
2249 std::unique_lock<std::mutex> lock(readMutex);
2250 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2251 }
2252
2253 // Since there is no read polling here, we will get polling count 0
2254 ASSERT_FALSE(client.isTransportWaiting());
2255 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2256 // Thread should increment polling count, read and decrement polling count
2257 // Again, polling count should be zero here
2258 ASSERT_FALSE(client.isTransportWaiting());
2259
2260 server->shutdown();
2261}
2262
Yifan Hong1deca4b2021-09-10 16:16:44 -07002263INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002264 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002265 RpcTransportTest::PrintParamInfo);
2266
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002267class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002268 : public testing::TestWithParam<
2269 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002270public:
2271 template <typename A, typename B>
2272 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002273 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2274 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002275 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2276 }
2277 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002278 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2279 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2280 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002281 };
2282};
2283
2284TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002285 if constexpr (!kEnableRpcThreads) {
2286 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2287 }
2288
Frederick Mayledc07cf82022-05-26 20:30:12 +00002289 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002290
2291 std::vector<uint8_t> pkeyData, certData;
2292 {
2293 auto pkey = makeKeyPairForSelfSignedCert();
2294 ASSERT_NE(nullptr, pkey);
2295 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2296 ASSERT_NE(nullptr, cert);
2297 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2298 certData = serializeCertificate(cert.get(), certificateFormat);
2299 }
2300
2301 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2302 auto desCert = deserializeCertificate(certData, certificateFormat);
2303 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002304 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2305 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002306
2307 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2308 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2309
2310 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2311 ASSERT_TRUE(client.setUp(utilsParam));
2312
2313 ASSERT_EQ(OK, trust(&client, server));
2314 ASSERT_EQ(OK, trust(server, &client));
2315
2316 server->start();
2317 client.run();
2318}
2319
2320INSTANTIATE_TEST_CASE_P(
2321 BinderRpc, RpcTransportTlsKeyTest,
2322 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2323 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002324 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2325 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002326 RpcTransportTlsKeyTest::PrintParamInfo);
2327
Steven Morelandc1635952021-04-01 16:20:47 +00002328} // namespace android
2329
2330int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002331 ::testing::InitGoogleTest(&argc, argv);
2332 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002333
Steven Moreland5553ac42020-11-11 02:14:45 +00002334 return RUN_ALL_TESTS();
2335}