blob: 72943051c7ccb930bd6195130e8a4d4fbd7003ce [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
David Brazdil21c887c2022-09-23 12:25:18 +0100257static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
258 base::unique_fd sockClient, sockServer;
259 if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
260 int savedErrno = errno;
261 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
262 }
263
264 int zero = 0;
265 iovec iov{&zero, sizeof(zero)};
266 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
267 fds.emplace_back(std::move(sockServer));
268
269 if (sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
270 int savedErrno = errno;
271 LOG(FATAL) << "Failed sendMessageOnSocket: " << strerror(savedErrno);
272 }
273 return std::move(sockClient);
274}
275
Andrei Homescu2a298012022-06-15 01:08:54 +0000276using RunServiceFn = void (*)(android::base::borrowed_fd writeEnd,
277 android::base::borrowed_fd readEnd);
278
279class BinderRpc : public ::testing::TestWithParam<
280 std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t, bool, bool>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000281public:
Frederick Mayle69a0c992022-05-26 20:38:39 +0000282 SocketType socketType() const { return std::get<0>(GetParam()); }
283 RpcSecurity rpcSecurity() const { return std::get<1>(GetParam()); }
284 uint32_t clientVersion() const { return std::get<2>(GetParam()); }
285 uint32_t serverVersion() const { return std::get<3>(GetParam()); }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000286 bool serverSingleThreaded() const { return std::get<4>(GetParam()); }
Andrei Homescu2a298012022-06-15 01:08:54 +0000287 bool noKernel() const { return std::get<5>(GetParam()); }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000288
Andrei Homescua858b0e2022-08-01 23:43:09 +0000289 bool clientOrServerSingleThreaded() const {
290 return !kEnableRpcThreads || serverSingleThreaded();
291 }
292
Frederick Mayle69a0c992022-05-26 20:38:39 +0000293 // Whether the test params support sending FDs in parcels.
294 bool supportsFdTransport() const {
295 return clientVersion() >= 1 && serverVersion() >= 1 && rpcSecurity() != RpcSecurity::TLS &&
David Brazdil21c887c2022-09-23 12:25:18 +0100296 (socketType() == SocketType::PRECONNECTED || socketType() == SocketType::UNIX ||
297 socketType() == SocketType::UNIX_BOOTSTRAP);
298 }
299
300 void SetUp() override {
301 if (socketType() == SocketType::UNIX_BOOTSTRAP && rpcSecurity() == RpcSecurity::TLS) {
302 GTEST_SKIP() << "Unix bootstrap not supported over a TLS transport";
303 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000304 }
305
Yifan Hong702115c2021-06-24 15:39:18 -0700306 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000307 auto [type, security, clientVersion, serverVersion, singleThreaded, noKernel] = info.param;
308 auto ret = PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
Frederick Mayledc07cf82022-05-26 20:30:12 +0000309 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Andrei Homescu2a298012022-06-15 01:08:54 +0000310 if (singleThreaded) {
311 ret += "_single_threaded";
312 }
313 if (noKernel) {
314 ret += "_no_kernel";
315 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700316 return ret;
317 }
318
Steven Morelandc1635952021-04-01 16:20:47 +0000319 // This creates a new process serving an interface on a certain number of
320 // threads.
Andrei Homescu2a298012022-06-15 01:08:54 +0000321 ProcessSession createRpcTestSocketServerProcessEtc(const BinderRpcOptions& options) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000322 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000323
Yifan Hong702115c2021-06-24 15:39:18 -0700324 SocketType socketType = std::get<0>(GetParam());
325 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000326 uint32_t clientVersion = std::get<2>(GetParam());
327 uint32_t serverVersion = std::get<3>(GetParam());
Andrei Homescu2a298012022-06-15 01:08:54 +0000328 bool singleThreaded = std::get<4>(GetParam());
329 bool noKernel = std::get<5>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000330
Andrei Homescu2a298012022-06-15 01:08:54 +0000331 std::string path = android::base::GetExecutableDirectory();
332 auto servicePath =
333 android::base::StringPrintf("%s/binder_rpc_test_service%s%s", path.c_str(),
334 singleThreaded ? "_single_threaded" : "",
335 noKernel ? "_no_kernel" : "");
Steven Morelandc1635952021-04-01 16:20:47 +0000336
David Brazdil21c887c2022-09-23 12:25:18 +0100337 base::unique_fd bootstrapClientFd, bootstrapServerFd;
338 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
339 // This is because we cannot pass ParcelFileDescriptor over a pipe.
340 if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &bootstrapServerFd)) {
341 int savedErrno = errno;
342 LOG(FATAL) << "Failed socketpair(): " << strerror(savedErrno);
343 }
344
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000345 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000346 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700347 android::base::borrowed_fd readEnd) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000348 auto writeFd = std::to_string(writeEnd.get());
349 auto readFd = std::to_string(readEnd.get());
350 execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(), readFd.c_str(),
351 NULL);
Steven Morelandc1635952021-04-01 16:20:47 +0000352 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000353 };
354
Andrei Homescu2a298012022-06-15 01:08:54 +0000355 BinderRpcTestServerConfig serverConfig;
356 serverConfig.numThreads = options.numThreads;
357 serverConfig.socketType = static_cast<int32_t>(socketType);
358 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
359 serverConfig.serverVersion = serverVersion;
360 serverConfig.vsockPort = allocateVsockPort();
361 serverConfig.addr = allocateSocketAddress();
David Brazdil21c887c2022-09-23 12:25:18 +0100362 serverConfig.unixBootstrapFd = bootstrapServerFd.get();
Andrei Homescu2a298012022-06-15 01:08:54 +0000363 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
364 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
365 static_cast<int32_t>(mode));
366 }
367 writeToFd(ret.host.writeEnd(), serverConfig);
368
Yifan Hong1deca4b2021-09-10 16:16:44 -0700369 std::vector<sp<RpcSession>> sessions;
370 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
371 for (size_t i = 0; i < options.numSessions; i++) {
372 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
373 }
374
375 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
376 BinderRpcTestClientInfo clientInfo;
377 for (const auto& session : sessions) {
378 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700379 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700380 }
381 writeToFd(ret.host.writeEnd(), clientInfo);
382
383 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700384 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700385 CHECK_NE(0, serverInfo.port);
386 }
387
388 if (rpcSecurity == RpcSecurity::TLS) {
389 const auto& serverCert = serverInfo.cert.data;
390 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700391 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
392 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700393 }
394
Steven Moreland2372f9d2021-08-05 15:42:01 -0700395 status_t status;
396
Yifan Hong1deca4b2021-09-10 16:16:44 -0700397 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000398 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700399 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700400 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000401 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Moreland659416d2021-05-11 00:47:50 +0000402
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000403 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700404 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700405 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescu2a298012022-06-15 01:08:54 +0000406 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700407 });
Steven Moreland4198a122021-08-03 17:37:58 -0700408 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000409 case SocketType::UNIX:
Andrei Homescu2a298012022-06-15 01:08:54 +0000410 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000411 break;
David Brazdil21c887c2022-09-23 12:25:18 +0100412 case SocketType::UNIX_BOOTSTRAP:
413 status = session->setupUnixDomainSocketBootstrapClient(
414 base::unique_fd(dup(bootstrapClientFd.get())));
415 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000416 case SocketType::VSOCK:
Andrei Homescu2a298012022-06-15 01:08:54 +0000417 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000418 break;
419 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700420 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000421 break;
422 default:
423 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000424 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000425 if (options.allowConnectFailure && status != OK) {
426 ret.sessions.clear();
427 break;
428 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700429 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000430 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000431 }
Steven Morelandc1635952021-04-01 16:20:47 +0000432 return ret;
433 }
434
Andrei Homescu2a298012022-06-15 01:08:54 +0000435 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const BinderRpcOptions& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000436 BinderRpcTestProcessSession ret{
Andrei Homescu2a298012022-06-15 01:08:54 +0000437 .proc = createRpcTestSocketServerProcessEtc(options),
Steven Morelandc1635952021-04-01 16:20:47 +0000438 };
439
Frederick Mayle69a0c992022-05-26 20:38:39 +0000440 ret.rootBinder = ret.proc.sessions.empty() ? nullptr : ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000441 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
442
443 return ret;
444 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700445
446 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
447 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000448};
449
Steven Morelandc1635952021-04-01 16:20:47 +0000450TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000451 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000452 ASSERT_NE(proc.rootBinder, nullptr);
453 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
454}
455
Steven Moreland4cf688f2021-03-31 01:48:58 +0000456TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000457 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000458 ASSERT_NE(proc.rootBinder, nullptr);
459 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
460}
461
Andrei Homescua858b0e2022-08-01 23:43:09 +0000462TEST_P(BinderRpc, MultipleSessions) {
463 if (serverSingleThreaded()) {
464 // Tests with multiple sessions require a multi-threaded service,
465 // but work fine on a single-threaded client
466 GTEST_SKIP() << "This test requires a multi-threaded service";
467 }
468
Steven Moreland4313d7e2021-07-15 23:41:22 +0000469 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000470 for (auto session : proc.proc.sessions) {
471 ASSERT_NE(nullptr, session.root);
472 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000473 }
474}
475
Andrei Homescua858b0e2022-08-01 23:43:09 +0000476TEST_P(BinderRpc, SeparateRootObject) {
477 if (serverSingleThreaded()) {
478 GTEST_SKIP() << "This test requires a multi-threaded service";
479 }
480
Steven Moreland51c44a92021-10-14 16:50:35 -0700481 SocketType type = std::get<0>(GetParam());
David Brazdil21c887c2022-09-23 12:25:18 +0100482 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX ||
483 type == SocketType::UNIX_BOOTSTRAP) {
Steven Moreland51c44a92021-10-14 16:50:35 -0700484 // we can't get port numbers for unix sockets
485 return;
486 }
487
488 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
489
490 int port1 = 0;
491 EXPECT_OK(proc.rootIface->getClientPort(&port1));
492
493 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
494 int port2;
495 EXPECT_OK(rootIface2->getClientPort(&port2));
496
497 // we should have a different IBinderRpcTest object created for each
498 // session, because we use setPerSessionRootObject
499 EXPECT_NE(port1, port2);
500}
501
Steven Morelandc1635952021-04-01 16:20:47 +0000502TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000503 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000504 Parcel data;
505 Parcel reply;
506 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
507}
508
Steven Moreland67753c32021-04-02 18:45:19 +0000509TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700510 auto proc1 = createRpcTestSocketServerProcess({});
511 auto proc2 = createRpcTestSocketServerProcess({});
512
513 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000514
515 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700516 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000517 p1.writeInt32(3);
518
Frederick Maylea4ed5672022-06-17 22:03:38 +0000519 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700520 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
521
Steven Moreland67753c32021-04-02 18:45:19 +0000522 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700523 p2.markForBinder(proc2.rootBinder);
524 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000525
526 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
527 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
528}
529
Steven Morelandc1635952021-04-01 16:20:47 +0000530TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000531 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000532 Parcel data;
533 data.markForBinder(proc.rootBinder);
534 Parcel reply;
535 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
536}
537
Steven Morelandc1635952021-04-01 16:20:47 +0000538TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000539 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000540 EXPECT_OK(proc.rootIface->sendString("asdf"));
541}
542
Steven Morelandc1635952021-04-01 16:20:47 +0000543TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000544 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000545 std::string doubled;
546 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
547 EXPECT_EQ("cool cool ", doubled);
548}
549
Steven Morelandc1635952021-04-01 16:20:47 +0000550TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000551 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000552 std::string single = std::string(1024, 'a');
553 std::string doubled;
554 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
555 EXPECT_EQ(single + single, doubled);
556}
557
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000558TEST_P(BinderRpc, InvalidNullBinderReturn) {
559 auto proc = createRpcTestSocketServerProcess({});
560
561 sp<IBinder> outBinder;
562 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
563}
564
Steven Morelandc1635952021-04-01 16:20:47 +0000565TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000566 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000567
568 int32_t pingResult;
569 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
570 EXPECT_EQ(OK, pingResult);
571
572 EXPECT_EQ(0, MyBinderRpcSession::gNum);
573}
574
Steven Morelandc1635952021-04-01 16:20:47 +0000575TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000576 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000577
578 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
579 sp<IBinder> outBinder;
580 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
581 EXPECT_EQ(inBinder, outBinder);
582
583 wp<IBinder> weak = inBinder;
584 inBinder = nullptr;
585 outBinder = nullptr;
586
587 // Force reading a reply, to process any pending dec refs from the other
588 // process (the other process will process dec refs there before processing
589 // the ping here).
590 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
591
592 EXPECT_EQ(nullptr, weak.promote());
593
594 EXPECT_EQ(0, MyBinderRpcSession::gNum);
595}
596
Steven Morelandc1635952021-04-01 16:20:47 +0000597TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000598 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000599
600 sp<IBinderRpcSession> session;
601 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
602
603 sp<IBinder> inBinder = IInterface::asBinder(session);
604 sp<IBinder> outBinder;
605 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
606 EXPECT_EQ(inBinder, outBinder);
607
608 wp<IBinder> weak = inBinder;
609 session = nullptr;
610 inBinder = nullptr;
611 outBinder = nullptr;
612
613 // Force reading a reply, to process any pending dec refs from the other
614 // process (the other process will process dec refs there before processing
615 // the ping here).
616 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
617
618 EXPECT_EQ(nullptr, weak.promote());
619}
620
Steven Morelandc1635952021-04-01 16:20:47 +0000621TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000622 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000623
624 sp<IBinder> outBinder;
625 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
626 EXPECT_EQ(nullptr, outBinder);
627}
628
Steven Morelandc1635952021-04-01 16:20:47 +0000629TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000630 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000631
632 IBinder* ptr = nullptr;
633 {
634 sp<IBinder> binder = new BBinder();
635 ptr = binder.get();
636 EXPECT_OK(proc.rootIface->holdBinder(binder));
637 }
638
639 sp<IBinder> held;
640 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
641
642 EXPECT_EQ(held.get(), ptr);
643
644 // stop holding binder, because we test to make sure references are cleaned
645 // up
646 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
647 // and flush ref counts
648 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
649}
650
651// START TESTS FOR LIMITATIONS OF SOCKET BINDER
652// These are behavioral differences form regular binder, where certain usecases
653// aren't supported.
654
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000655TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000656 auto proc1 = createRpcTestSocketServerProcess({});
657 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000658
659 sp<IBinder> outBinder;
660 EXPECT_EQ(INVALID_OPERATION,
661 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
662}
663
Andrei Homescua858b0e2022-08-01 23:43:09 +0000664TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
665 if (serverSingleThreaded()) {
666 GTEST_SKIP() << "This test requires a multi-threaded service";
667 }
668
Steven Moreland4313d7e2021-07-15 23:41:22 +0000669 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000670
671 sp<IBinder> outBinder;
672 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000673 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000674 .transactionError());
675}
676
Steven Morelandc1635952021-04-01 16:20:47 +0000677TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000678 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000679 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
680 "at build time.";
681 }
682
Steven Moreland4313d7e2021-07-15 23:41:22 +0000683 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000684
685 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
686 sp<IBinder> outBinder;
687 EXPECT_EQ(INVALID_OPERATION,
688 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
689}
690
Steven Morelandc1635952021-04-01 16:20:47 +0000691TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000692 if (!kEnableKernelIpc || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000693 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
694 "at build time.";
695 }
696
Steven Moreland4313d7e2021-07-15 23:41:22 +0000697 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000698
699 // for historical reasons, IServiceManager interface only returns the
700 // exception code
701 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
702 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
703}
704
705// END TESTS FOR LIMITATIONS OF SOCKET BINDER
706
Steven Morelandc1635952021-04-01 16:20:47 +0000707TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000708 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000709
710 sp<IBinder> outBinder;
711 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
712 EXPECT_EQ(proc.rootBinder, outBinder);
713}
714
Steven Morelandc1635952021-04-01 16:20:47 +0000715TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000716 auto proc = createRpcTestSocketServerProcess({
717 // Enable FD support because it uses more stack space and so represents
718 // something closer to a worst case scenario.
719 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
720 .serverSupportedFileDescriptorTransportModes =
721 {RpcSession::FileDescriptorTransportMode::UNIX},
722 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000723
724 auto nastyNester = sp<MyBinderRpcTest>::make();
725 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
726
727 wp<IBinder> weak = nastyNester;
728 nastyNester = nullptr;
729 EXPECT_EQ(nullptr, weak.promote());
730}
731
Steven Morelandc1635952021-04-01 16:20:47 +0000732TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000733 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000734
735 sp<IBinder> a;
736 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
737
738 sp<IBinder> b;
739 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
740
741 EXPECT_EQ(a, b);
742}
743
Steven Morelandc1635952021-04-01 16:20:47 +0000744TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000745 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000746
747 sp<IBinder> a;
748 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
749 wp<IBinder> weak = a;
750 a = nullptr;
751
752 sp<IBinder> b;
753 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
754
755 // this is the wrong behavior, since BpBinder
756 // doesn't implement onIncStrongAttempted
757 // but make sure there is no crash
758 EXPECT_EQ(nullptr, weak.promote());
759
760 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
761
762 // In order to fix this:
763 // - need to have incStrongAttempted reflected across IPC boundary (wait for
764 // response to promote - round trip...)
765 // - sendOnLastWeakRef, to delete entries out of RpcState table
766 EXPECT_EQ(b, weak.promote());
767}
768
769#define expectSessions(expected, iface) \
770 do { \
771 int session; \
772 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
773 EXPECT_EQ(expected, session); \
774 } while (false)
775
Steven Morelandc1635952021-04-01 16:20:47 +0000776TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000777 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000778
779 sp<IBinderRpcSession> session;
780 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
781 std::string out;
782 EXPECT_OK(session->getName(&out));
783 EXPECT_EQ("aoeu", out);
784
785 expectSessions(1, proc.rootIface);
786 session = nullptr;
787 expectSessions(0, proc.rootIface);
788}
789
Steven Morelandc1635952021-04-01 16:20:47 +0000790TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000791 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000792
793 std::vector<sp<IBinderRpcSession>> sessions;
794
795 for (size_t i = 0; i < 15; i++) {
796 expectSessions(i, proc.rootIface);
797 sp<IBinderRpcSession> session;
798 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
799 sessions.push_back(session);
800 }
801 expectSessions(sessions.size(), proc.rootIface);
802 for (size_t i = 0; i < sessions.size(); i++) {
803 std::string out;
804 EXPECT_OK(sessions.at(i)->getName(&out));
805 EXPECT_EQ(std::to_string(i), out);
806 }
807 expectSessions(sessions.size(), proc.rootIface);
808
809 while (!sessions.empty()) {
810 sessions.pop_back();
811 expectSessions(sessions.size(), proc.rootIface);
812 }
813 expectSessions(0, proc.rootIface);
814}
815
816size_t epochMillis() {
817 using std::chrono::duration_cast;
818 using std::chrono::milliseconds;
819 using std::chrono::seconds;
820 using std::chrono::system_clock;
821 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
822}
823
Andrei Homescua858b0e2022-08-01 23:43:09 +0000824TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
825 if (clientOrServerSingleThreaded()) {
826 GTEST_SKIP() << "This test requires multiple threads";
827 }
828
Steven Moreland5553ac42020-11-11 02:14:45 +0000829 constexpr size_t kNumThreads = 10;
830
Steven Moreland4313d7e2021-07-15 23:41:22 +0000831 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000832
833 EXPECT_OK(proc.rootIface->lock());
834
835 // block all but one thread taking locks
836 std::vector<std::thread> ts;
837 for (size_t i = 0; i < kNumThreads - 1; i++) {
838 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
839 }
840
Steven Morelanddd231e22022-09-08 19:47:49 +0000841 usleep(10000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000842
843 // other calls still work
844 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
845
Steven Morelanddd231e22022-09-08 19:47:49 +0000846 constexpr size_t blockTimeMs = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000847 size_t epochMsBefore = epochMillis();
848 // after this, we should never see a response within this time
849 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
850
851 // this call should be blocked for blockTimeMs
852 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
853
854 size_t epochMsAfter = epochMillis();
855 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
856
857 for (auto& t : ts) t.join();
858}
859
Yifan Hong1f44f982021-10-08 17:16:47 -0700860void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
861 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000862 size_t epochMsBefore = epochMillis();
863
864 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700865 for (size_t i = 0; i < numCalls; i++) {
866 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000867 }
868
869 for (auto& t : ts) t.join();
870
871 size_t epochMsAfter = epochMillis();
872
Yifan Hong1f44f982021-10-08 17:16:47 -0700873 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000874
875 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -0700876 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
877}
878
Andrei Homescua858b0e2022-08-01 23:43:09 +0000879TEST_P(BinderRpc, ThreadPoolOverSaturated) {
880 if (clientOrServerSingleThreaded()) {
881 GTEST_SKIP() << "This test requires multiple threads";
882 }
883
Yifan Hong1f44f982021-10-08 17:16:47 -0700884 constexpr size_t kNumThreads = 10;
885 constexpr size_t kNumCalls = kNumThreads + 3;
886 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
887 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
888}
889
Andrei Homescua858b0e2022-08-01 23:43:09 +0000890TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
891 if (clientOrServerSingleThreaded()) {
892 GTEST_SKIP() << "This test requires multiple threads";
893 }
894
Yifan Hong1f44f982021-10-08 17:16:47 -0700895 constexpr size_t kNumThreads = 20;
896 constexpr size_t kNumOutgoingConnections = 10;
897 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
898 auto proc = createRpcTestSocketServerProcess(
899 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
900 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +0000901}
902
Andrei Homescua858b0e2022-08-01 23:43:09 +0000903TEST_P(BinderRpc, ThreadingStressTest) {
904 if (clientOrServerSingleThreaded()) {
905 GTEST_SKIP() << "This test requires multiple threads";
906 }
907
Steven Moreland5553ac42020-11-11 02:14:45 +0000908 constexpr size_t kNumClientThreads = 10;
909 constexpr size_t kNumServerThreads = 10;
910 constexpr size_t kNumCalls = 100;
911
Steven Moreland4313d7e2021-07-15 23:41:22 +0000912 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000913
914 std::vector<std::thread> threads;
915 for (size_t i = 0; i < kNumClientThreads; i++) {
916 threads.push_back(std::thread([&] {
917 for (size_t j = 0; j < kNumCalls; j++) {
918 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000919 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000920 EXPECT_EQ(proc.rootBinder, out);
921 }
922 }));
923 }
924
925 for (auto& t : threads) t.join();
926}
927
Steven Moreland925ba0a2021-09-17 18:06:32 -0700928static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
929 std::vector<std::thread> threads;
930 for (size_t i = 0; i < threadCount; i++) {
931 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
932 }
933 for (auto& t : threads) t.join();
934}
935
Andrei Homescua858b0e2022-08-01 23:43:09 +0000936TEST_P(BinderRpc, OnewayStressTest) {
937 if (clientOrServerSingleThreaded()) {
938 GTEST_SKIP() << "This test requires multiple threads";
939 }
940
Steven Morelandc6046982021-04-20 00:49:42 +0000941 constexpr size_t kNumClientThreads = 10;
942 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700943 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000944
Steven Moreland4313d7e2021-07-15 23:41:22 +0000945 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000946
947 std::vector<std::thread> threads;
948 for (size_t i = 0; i < kNumClientThreads; i++) {
949 threads.push_back(std::thread([&] {
950 for (size_t j = 0; j < kNumCalls; j++) {
951 EXPECT_OK(proc.rootIface->sendString("a"));
952 }
Steven Morelandc6046982021-04-20 00:49:42 +0000953 }));
954 }
955
956 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700957
958 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000959}
960
Steven Morelandc1635952021-04-01 16:20:47 +0000961TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000962 constexpr size_t kReallyLongTimeMs = 100;
963 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
964
Steven Moreland4313d7e2021-07-15 23:41:22 +0000965 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000966
967 size_t epochMsBefore = epochMillis();
968
969 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
970
971 size_t epochMsAfter = epochMillis();
972 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
973}
974
Frederick Mayleb0221d12022-10-03 23:10:53 +0000975TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
976 if (!supportsFdTransport()) {
977 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
978 }
979 if (clientOrServerSingleThreaded()) {
980 GTEST_SKIP() << "This test requires multiple threads";
981 }
982
983 // This test forces a oneway transaction to be queued by issuing two
984 // `blockingSendFdOneway` calls, then drains the queue by issuing two
985 // `blockingRecvFd` calls.
986 //
987 // For more details about the queuing semantics see
988 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
989
990 auto proc = createRpcTestSocketServerProcess({
991 .numThreads = 3,
992 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
993 .serverSupportedFileDescriptorTransportModes =
994 {RpcSession::FileDescriptorTransportMode::UNIX},
995 });
996
997 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
998 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
999 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
1000 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
1001
1002 android::os::ParcelFileDescriptor fdA;
1003 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
1004 std::string result;
1005 CHECK(android::base::ReadFdToString(fdA.get(), &result));
1006 EXPECT_EQ(result, "a");
1007
1008 android::os::ParcelFileDescriptor fdB;
1009 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
1010 CHECK(android::base::ReadFdToString(fdB.get(), &result));
1011 EXPECT_EQ(result, "b");
1012}
1013
Andrei Homescua858b0e2022-08-01 23:43:09 +00001014TEST_P(BinderRpc, OnewayCallQueueing) {
1015 if (clientOrServerSingleThreaded()) {
1016 GTEST_SKIP() << "This test requires multiple threads";
1017 }
1018
Steven Moreland5553ac42020-11-11 02:14:45 +00001019 constexpr size_t kNumSleeps = 10;
1020 constexpr size_t kNumExtraServerThreads = 4;
1021 constexpr size_t kSleepMs = 50;
1022
1023 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001024 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001025
1026 EXPECT_OK(proc.rootIface->lock());
1027
Steven Moreland1c678802021-09-17 16:48:47 -07001028 size_t epochMsBefore = epochMillis();
1029
1030 // all these *Async commands should be queued on the server sequentially,
1031 // even though there are multiple threads.
1032 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001033 proc.rootIface->sleepMsAsync(kSleepMs);
1034 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001035 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1036
Steven Moreland1c678802021-09-17 16:48:47 -07001037 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +00001038 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -07001039
Steven Moreland5553ac42020-11-11 02:14:45 +00001040 size_t epochMsAfter = epochMillis();
1041
Frederick Mayle3fa815d2022-07-12 22:52:52 +00001042 EXPECT_GE(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001043
Steven Moreland925ba0a2021-09-17 18:06:32 -07001044 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001045}
1046
Andrei Homescua858b0e2022-08-01 23:43:09 +00001047TEST_P(BinderRpc, OnewayCallExhaustion) {
1048 if (clientOrServerSingleThreaded()) {
1049 GTEST_SKIP() << "This test requires multiple threads";
1050 }
1051
Steven Morelandd45be622021-06-04 02:19:37 +00001052 constexpr size_t kNumClients = 2;
1053 constexpr size_t kTooLongMs = 1000;
1054
Steven Moreland4313d7e2021-07-15 23:41:22 +00001055 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001056
1057 // Build up oneway calls on the second session to make sure it terminates
1058 // and shuts down. The first session should be unaffected (proc destructor
1059 // checks the first session).
1060 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1061
1062 std::vector<std::thread> threads;
1063 for (size_t i = 0; i < kNumClients; i++) {
1064 // one of these threads will get stuck queueing a transaction once the
1065 // socket fills up, the other will be able to fill up transactions on
1066 // this object
1067 threads.push_back(std::thread([&] {
1068 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1069 }
1070 }));
1071 }
1072 for (auto& t : threads) t.join();
1073
1074 Status status = iface->sleepMsAsync(kTooLongMs);
1075 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1076
Steven Moreland798e0d12021-07-14 23:19:25 +00001077 // now that it has died, wait for the remote session to shutdown
1078 std::vector<int32_t> remoteCounts;
1079 do {
1080 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1081 } while (remoteCounts.size() == kNumClients);
1082
Steven Morelandd45be622021-06-04 02:19:37 +00001083 // the second session should be shutdown in the other process by the time we
1084 // are able to join above (it'll only be hung up once it finishes processing
1085 // any pending commands). We need to erase this session from the record
1086 // here, so that the destructor for our session won't check that this
1087 // session is valid, but we still want it to test the other session.
1088 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1089}
1090
Steven Moreland659416d2021-05-11 00:47:50 +00001091TEST_P(BinderRpc, Callbacks) {
1092 const static std::string kTestString = "good afternoon!";
1093
Steven Morelandc7d40132021-06-10 03:42:11 +00001094 for (bool callIsOneway : {true, false}) {
1095 for (bool callbackIsOneway : {true, false}) {
1096 for (bool delayed : {true, false}) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001097 if (clientOrServerSingleThreaded() &&
1098 (callIsOneway || callbackIsOneway || delayed)) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001099 // we have no incoming connections to receive the callback
1100 continue;
1101 }
1102
Andrei Homescua858b0e2022-08-01 23:43:09 +00001103 size_t numIncomingConnections = clientOrServerSingleThreaded() ? 0 : 1;
Steven Moreland4313d7e2021-07-15 23:41:22 +00001104 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +00001105 {.numThreads = 1,
1106 .numSessions = 1,
Andrei Homescu2a298012022-06-15 01:08:54 +00001107 .numIncomingConnections = numIncomingConnections});
Steven Morelandc7d40132021-06-10 03:42:11 +00001108 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001109
Steven Morelandc7d40132021-06-10 03:42:11 +00001110 if (callIsOneway) {
1111 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1112 kTestString));
1113 } else {
1114 EXPECT_OK(
1115 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1116 }
Steven Moreland659416d2021-05-11 00:47:50 +00001117
Steven Moreland03ecce62022-05-13 23:22:05 +00001118 // if both transactions are synchronous and the response is sent back on the
1119 // same thread, everything should have happened in a nested call. Otherwise,
1120 // the callback will be processed on another thread.
1121 if (callIsOneway || callbackIsOneway || delayed) {
1122 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001123 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001124 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1125 }
Steven Moreland659416d2021-05-11 00:47:50 +00001126
Steven Morelandc7d40132021-06-10 03:42:11 +00001127 EXPECT_EQ(cb->mValues.size(), 1)
1128 << "callIsOneway: " << callIsOneway
1129 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1130 if (cb->mValues.empty()) continue;
1131 EXPECT_EQ(cb->mValues.at(0), kTestString)
1132 << "callIsOneway: " << callIsOneway
1133 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001134
Steven Morelandc7d40132021-06-10 03:42:11 +00001135 // since we are severing the connection, we need to go ahead and
1136 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001137 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1138 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1139 }
Steven Moreland659416d2021-05-11 00:47:50 +00001140
Steven Moreland1b304292021-07-15 22:59:34 +00001141 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001142 // need to manually shut it down
1143 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Morelandc7d40132021-06-10 03:42:11 +00001144 proc.expectAlreadyShutdown = true;
1145 }
Steven Moreland659416d2021-05-11 00:47:50 +00001146 }
1147 }
1148}
1149
Devin Moore66d5b7a2022-07-07 21:42:10 +00001150TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001151 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001152 GTEST_SKIP() << "This test requires multiple threads";
1153 }
1154 class MyDeathRec : public IBinder::DeathRecipient {
1155 public:
1156 void binderDied(const wp<IBinder>& /* who */) override {
1157 dead = true;
1158 mCv.notify_one();
1159 }
1160 std::mutex mMtx;
1161 std::condition_variable mCv;
1162 bool dead = false;
1163 };
1164
1165 // Death recipient needs to have an incoming connection to be called
1166 auto proc = createRpcTestSocketServerProcess(
1167 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1168
1169 auto dr = sp<MyDeathRec>::make();
1170 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1171
1172 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1173 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1174 }
1175
1176 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +00001177 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001178
1179 // need to wait for the session to shutdown so we don't "Leak session"
1180 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1181 proc.expectAlreadyShutdown = true;
1182}
1183
1184TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001185 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001186 GTEST_SKIP() << "This test requires multiple threads";
1187 }
1188 class MyDeathRec : public IBinder::DeathRecipient {
1189 public:
1190 void binderDied(const wp<IBinder>& /* who */) override {
1191 dead = true;
1192 mCv.notify_one();
1193 }
1194 std::mutex mMtx;
1195 std::condition_variable mCv;
1196 bool dead = false;
1197 };
1198
1199 // Death recipient needs to have an incoming connection to be called
1200 auto proc = createRpcTestSocketServerProcess(
1201 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1202
1203 auto dr = sp<MyDeathRec>::make();
1204 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1205
1206 // Explicitly calling shutDownAndWait will cause the death recipients
1207 // to be called.
1208 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1209
1210 std::unique_lock<std::mutex> lock(dr->mMtx);
1211 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001212 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +00001213 }
1214 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
1215
1216 proc.proc.host.terminate();
1217 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1218 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1219 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1220 });
1221 proc.expectAlreadyShutdown = true;
1222}
1223
1224TEST_P(BinderRpc, DeathRecipientFatalWithoutIncoming) {
1225 class MyDeathRec : public IBinder::DeathRecipient {
1226 public:
1227 void binderDied(const wp<IBinder>& /* who */) override {}
1228 };
1229
1230 auto proc = createRpcTestSocketServerProcess(
1231 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 0});
1232
1233 auto dr = sp<MyDeathRec>::make();
1234 EXPECT_DEATH(proc.rootBinder->linkToDeath(dr, (void*)1, 0),
1235 "Cannot register a DeathRecipient without any incoming connections.");
1236}
1237
1238TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +00001239 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +00001240 GTEST_SKIP() << "This test requires multiple threads";
1241 }
1242 class MyDeathRec : public IBinder::DeathRecipient {
1243 public:
1244 void binderDied(const wp<IBinder>& /* who */) override {
1245 GTEST_FAIL() << "This should not be called after unlinkToDeath";
1246 }
1247 };
1248
1249 // Death recipient needs to have an incoming connection to be called
1250 auto proc = createRpcTestSocketServerProcess(
1251 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
1252
1253 auto dr = sp<MyDeathRec>::make();
1254 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
1255 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
1256
1257 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1258 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1259 }
1260
1261 // need to wait for the session to shutdown so we don't "Leak session"
1262 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
1263 proc.expectAlreadyShutdown = true;
1264}
1265
Steven Moreland195edb82021-06-08 02:44:39 +00001266TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001267 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001268 auto cb = sp<MyBinderRpcCallback>::make();
1269
1270 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1271 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1272}
1273
Steven Morelandc1635952021-04-01 16:20:47 +00001274TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001275 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001276 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001277
1278 // make sure there is some state during crash
1279 // 1. we hold their binder
1280 sp<IBinderRpcSession> session;
1281 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1282 // 2. they hold our binder
1283 sp<IBinder> binder = new BBinder();
1284 EXPECT_OK(proc.rootIface->holdBinder(binder));
1285
1286 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1287 << "Do death cleanup: " << doDeathCleanup;
1288
Frederick Maylea12b0962022-06-25 01:13:22 +00001289 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1290 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1291 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1292 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001293 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001294 }
1295}
1296
Steven Morelandd7302072021-05-15 01:32:04 +00001297TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +00001298 // This test only works if the current process shared the internal state of
1299 // ProcessState with the service across the call to fork(). Both the static
1300 // libraries and libbinder.so have their own separate copies of all the
1301 // globals, so the test only works when the test client and service both use
1302 // libbinder.so (when using static libraries, even a client and service
1303 // using the same kind of static library should have separate copies of the
1304 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +00001305 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001306 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1307 "at build time.";
1308 }
1309
Steven Moreland4313d7e2021-07-15 23:41:22 +00001310 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001311
Andrei Homescu2a298012022-06-15 01:08:54 +00001312 // we can't allocate IPCThreadState so actually the first time should
1313 // succeed :(
1314 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +00001315
1316 // second time! we catch the error :)
1317 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1318
Frederick Maylea12b0962022-06-25 01:13:22 +00001319 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1320 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1321 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1322 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001323 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001324}
1325
Frederick Mayle69a0c992022-05-26 20:38:39 +00001326TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1327 auto proc = createRpcTestSocketServerProcess({
1328 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1329 .serverSupportedFileDescriptorTransportModes =
1330 {RpcSession::FileDescriptorTransportMode::UNIX},
1331 .allowConnectFailure = true,
1332 });
1333 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1334 proc.proc.host.terminate();
1335 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1336 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1337 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1338 });
1339 proc.expectAlreadyShutdown = true;
1340}
1341
1342TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1343 auto proc = createRpcTestSocketServerProcess({
1344 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1345 .serverSupportedFileDescriptorTransportModes =
1346 {RpcSession::FileDescriptorTransportMode::NONE},
1347 .allowConnectFailure = true,
1348 });
1349 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1350 proc.proc.host.terminate();
1351 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1352 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1353 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1354 });
1355 proc.expectAlreadyShutdown = true;
1356}
1357
1358TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1359 auto proc = createRpcTestSocketServerProcess({
1360 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1361 .serverSupportedFileDescriptorTransportModes =
1362 {RpcSession::FileDescriptorTransportMode::NONE,
1363 RpcSession::FileDescriptorTransportMode::UNIX},
1364 });
1365
1366 android::os::ParcelFileDescriptor out;
1367 auto status = proc.rootIface->echoAsFile("hello", &out);
1368 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1369}
1370
1371TEST_P(BinderRpc, ReceiveFile) {
1372 auto proc = createRpcTestSocketServerProcess({
1373 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1374 .serverSupportedFileDescriptorTransportModes =
1375 {RpcSession::FileDescriptorTransportMode::UNIX},
1376 });
1377
1378 android::os::ParcelFileDescriptor out;
1379 auto status = proc.rootIface->echoAsFile("hello", &out);
1380 if (!supportsFdTransport()) {
1381 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1382 return;
1383 }
1384 ASSERT_TRUE(status.isOk()) << status;
1385
1386 std::string result;
1387 CHECK(android::base::ReadFdToString(out.get(), &result));
1388 EXPECT_EQ(result, "hello");
1389}
1390
1391TEST_P(BinderRpc, SendFiles) {
1392 auto proc = createRpcTestSocketServerProcess({
1393 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1394 .serverSupportedFileDescriptorTransportModes =
1395 {RpcSession::FileDescriptorTransportMode::UNIX},
1396 });
1397
1398 std::vector<android::os::ParcelFileDescriptor> files;
1399 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1400 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1401 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1402 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1403
1404 android::os::ParcelFileDescriptor out;
1405 auto status = proc.rootIface->concatFiles(files, &out);
1406 if (!supportsFdTransport()) {
1407 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1408 return;
1409 }
1410 ASSERT_TRUE(status.isOk()) << status;
1411
1412 std::string result;
1413 CHECK(android::base::ReadFdToString(out.get(), &result));
1414 EXPECT_EQ(result, "123abcd");
1415}
1416
1417TEST_P(BinderRpc, SendMaxFiles) {
1418 if (!supportsFdTransport()) {
1419 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1420 }
1421
1422 auto proc = createRpcTestSocketServerProcess({
1423 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1424 .serverSupportedFileDescriptorTransportModes =
1425 {RpcSession::FileDescriptorTransportMode::UNIX},
1426 });
1427
1428 std::vector<android::os::ParcelFileDescriptor> files;
1429 for (int i = 0; i < 253; i++) {
1430 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1431 }
1432
1433 android::os::ParcelFileDescriptor out;
1434 auto status = proc.rootIface->concatFiles(files, &out);
1435 ASSERT_TRUE(status.isOk()) << status;
1436
1437 std::string result;
1438 CHECK(android::base::ReadFdToString(out.get(), &result));
1439 EXPECT_EQ(result, std::string(253, 'a'));
1440}
1441
1442TEST_P(BinderRpc, SendTooManyFiles) {
1443 if (!supportsFdTransport()) {
1444 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1445 }
1446
1447 auto proc = createRpcTestSocketServerProcess({
1448 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1449 .serverSupportedFileDescriptorTransportModes =
1450 {RpcSession::FileDescriptorTransportMode::UNIX},
1451 });
1452
1453 std::vector<android::os::ParcelFileDescriptor> files;
1454 for (int i = 0; i < 254; i++) {
1455 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1456 }
1457
1458 android::os::ParcelFileDescriptor out;
1459 auto status = proc.rootIface->concatFiles(files, &out);
1460 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1461}
1462
Steven Moreland37aff182021-03-26 02:04:16 +00001463TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001464 if constexpr (!kEnableSharedLibs) {
1465 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1466 }
1467
Steven Moreland4313d7e2021-07-15 23:41:22 +00001468 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001469
1470 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1471 ASSERT_NE(binder, nullptr);
1472
1473 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1474}
1475
1476TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001477 if constexpr (!kEnableSharedLibs) {
1478 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1479 }
1480
Steven Moreland4313d7e2021-07-15 23:41:22 +00001481 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001482
1483 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1484 ASSERT_NE(binder, nullptr);
1485
1486 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1487 ASSERT_NE(ndkBinder, nullptr);
1488
1489 std::string out;
1490 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1491 ASSERT_TRUE(status.isOk()) << status.getDescription();
1492 ASSERT_EQ("aoeuaoeu", out);
1493}
1494
Steven Moreland5553ac42020-11-11 02:14:45 +00001495ssize_t countFds() {
1496 DIR* dir = opendir("/proc/self/fd/");
1497 if (dir == nullptr) return -1;
1498 ssize_t ret = 0;
1499 dirent* ent;
1500 while ((ent = readdir(dir)) != nullptr) ret++;
1501 closedir(dir);
1502 return ret;
1503}
1504
Andrei Homescua858b0e2022-08-01 23:43:09 +00001505TEST_P(BinderRpc, Fds) {
1506 if (serverSingleThreaded()) {
1507 GTEST_SKIP() << "This test requires multiple threads";
1508 }
1509
Steven Moreland5553ac42020-11-11 02:14:45 +00001510 ssize_t beforeFds = countFds();
1511 ASSERT_GE(beforeFds, 0);
1512 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001513 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001514 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1515 }
1516 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1517}
1518
Devin Moore800b2252021-10-15 16:22:57 +00001519TEST_P(BinderRpc, AidlDelegatorTest) {
1520 auto proc = createRpcTestSocketServerProcess({});
1521 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1522 ASSERT_NE(nullptr, myDelegator);
1523
1524 std::string doubled;
1525 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1526 EXPECT_EQ("cool cool ", doubled);
1527}
1528
Steven Morelandda573042021-06-12 01:13:45 +00001529static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001530 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001531 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001532
Andrei Homescu992a4052022-06-28 21:26:18 +00001533 android::base::unique_fd serverFd(
1534 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1535 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1536
1537 sockaddr_vm serverAddr{
1538 .svm_family = AF_VSOCK,
1539 .svm_port = vsockPort,
1540 .svm_cid = VMADDR_CID_ANY,
1541 };
1542 int ret = TEMP_FAILURE_RETRY(
1543 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1544 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1545 strerror(errno));
1546
1547 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1548 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1549 strerror(errno));
1550
1551 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1552 // to see if the kernel supports it. It's safe to use a blocking
1553 // connect because vsock sockets have a 2 second connection timeout,
1554 // and they return ETIMEDOUT after that.
1555 android::base::unique_fd connectFd(
1556 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1557 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1558 strerror(errno));
1559
1560 bool success = false;
1561 sockaddr_vm connectAddr{
1562 .svm_family = AF_VSOCK,
1563 .svm_port = vsockPort,
1564 .svm_cid = VMADDR_CID_LOCAL,
1565 };
1566 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1567 sizeof(connectAddr)));
1568 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1569 android::base::unique_fd acceptFd;
1570 while (true) {
1571 pollfd pfd[]{
1572 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1573 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1574 };
1575 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1576 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1577
1578 if (pfd[0].revents & POLLIN) {
1579 sockaddr_vm acceptAddr;
1580 socklen_t acceptAddrLen = sizeof(acceptAddr);
1581 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1582 reinterpret_cast<sockaddr*>(&acceptAddr),
1583 &acceptAddrLen, SOCK_CLOEXEC));
1584 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1585 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1586 "Truncated address");
1587
1588 // Store the fd in acceptFd so we keep the connection alive
1589 // while polling connectFd
1590 acceptFd.reset(ret);
1591 }
1592
1593 if (pfd[1].revents & POLLOUT) {
1594 // Connect either succeeded or timed out
1595 int connectErrno;
1596 socklen_t connectErrnoLen = sizeof(connectErrno);
1597 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1598 &connectErrnoLen);
1599 LOG_ALWAYS_FATAL_IF(ret == -1,
1600 "Could not getsockopt() after connect() "
1601 "on non-blocking socket: %s.",
1602 strerror(errno));
1603
1604 // We're done, this is all we wanted
1605 success = connectErrno == 0;
1606 break;
1607 }
1608 }
1609 } else {
1610 success = ret == 0;
1611 }
1612
1613 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1614
1615 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001616}
1617
Yifan Hong1deca4b2021-09-10 16:16:44 -07001618static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
David Brazdil21c887c2022-09-23 12:25:18 +01001619 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001620
1621 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001622
1623 static bool hasVsockLoopback = testSupportVsockLoopback();
1624
1625 if (hasVsockLoopback) {
1626 ret.push_back(SocketType::VSOCK);
1627 }
1628
1629 return ret;
1630}
1631
Frederick Mayledc07cf82022-05-26 20:30:12 +00001632static std::vector<uint32_t> testVersions() {
1633 std::vector<uint32_t> versions;
1634 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1635 versions.push_back(i);
1636 }
1637 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1638 return versions;
1639}
1640
Yifan Hong702115c2021-06-24 15:39:18 -07001641INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1642 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001643 ::testing::ValuesIn(RpcSecurityValues()),
1644 ::testing::ValuesIn(testVersions()),
Andrei Homescu2a298012022-06-15 01:08:54 +00001645 ::testing::ValuesIn(testVersions()),
1646 ::testing::Values(false, true),
1647 ::testing::Values(false, true)),
Yifan Hong702115c2021-06-24 15:39:18 -07001648 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001649
Yifan Hong702115c2021-06-24 15:39:18 -07001650class BinderRpcServerRootObject
1651 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001652
1653TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1654 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1655 auto setRootObject = [](bool isStrong) -> SetFn {
1656 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1657 };
1658
Yifan Hong702115c2021-06-24 15:39:18 -07001659 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1660 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001661 auto binder1 = sp<BBinder>::make();
1662 IBinder* binderRaw1 = binder1.get();
1663 setRootObject(isStrong1)(server.get(), binder1);
1664 EXPECT_EQ(binderRaw1, server->getRootObject());
1665 binder1.clear();
1666 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1667
1668 auto binder2 = sp<BBinder>::make();
1669 IBinder* binderRaw2 = binder2.get();
1670 setRootObject(isStrong2)(server.get(), binder2);
1671 EXPECT_EQ(binderRaw2, server->getRootObject());
1672 binder2.clear();
1673 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1674}
1675
1676INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001677 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1678 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001679
Yifan Hong1a235852021-05-13 16:07:47 -07001680class OneOffSignal {
1681public:
1682 // If notify() was previously called, or is called within |duration|, return true; else false.
1683 template <typename R, typename P>
1684 bool wait(std::chrono::duration<R, P> duration) {
1685 std::unique_lock<std::mutex> lock(mMutex);
1686 return mCv.wait_for(lock, duration, [this] { return mValue; });
1687 }
1688 void notify() {
1689 std::unique_lock<std::mutex> lock(mMutex);
1690 mValue = true;
1691 lock.unlock();
1692 mCv.notify_all();
1693 }
1694
1695private:
1696 std::mutex mMutex;
1697 std::condition_variable mCv;
1698 bool mValue = false;
1699};
1700
Yifan Hong194acf22021-06-29 18:44:56 -07001701TEST(BinderRpc, Java) {
1702#if !defined(__ANDROID__)
1703 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1704 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1705 "to binderHostDeviceTest. Hence, just disable this test on host.";
1706#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001707 if constexpr (!kEnableKernelIpc) {
1708 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1709 "at build time.";
1710 }
1711
Yifan Hong194acf22021-06-29 18:44:56 -07001712 sp<IServiceManager> sm = defaultServiceManager();
1713 ASSERT_NE(nullptr, sm);
1714 // Any Java service with non-empty getInterfaceDescriptor() would do.
1715 // Let's pick batteryproperties.
1716 auto binder = sm->checkService(String16("batteryproperties"));
1717 ASSERT_NE(nullptr, binder);
1718 auto descriptor = binder->getInterfaceDescriptor();
1719 ASSERT_GE(descriptor.size(), 0);
1720 ASSERT_EQ(OK, binder->pingBinder());
1721
1722 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001723 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001724 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001725 auto socket = rpcServer->releaseServer();
1726
1727 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001728 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1729
Yifan Honge3caaf22022-01-12 14:46:56 -08001730 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1731 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001732 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001733 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1734 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001735 << statusToString(setRpcClientDebugStatus);
1736 GTEST_SKIP();
1737 }
1738
1739 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001740
1741 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001742 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001743 auto rpcBinder = rpcSession->getRootObject();
1744 ASSERT_NE(nullptr, rpcBinder);
1745
1746 ASSERT_EQ(OK, rpcBinder->pingBinder());
1747
1748 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1749 << "getInterfaceDescriptor should not crash system_server";
1750 ASSERT_EQ(OK, rpcBinder->pingBinder());
1751}
1752
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001753class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1754public:
1755 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1756 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1757 std::to_string(std::get<1>(info.param));
1758 }
1759};
1760
1761TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1762 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1763 int sinkFd = sink.get();
1764 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1765 server->setProtocolVersion(std::get<1>(GetParam()));
1766 ASSERT_FALSE(server->hasServer());
1767 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1768 ASSERT_TRUE(server->hasServer());
1769 base::unique_fd retrieved = server->releaseServer();
1770 ASSERT_FALSE(server->hasServer());
1771 ASSERT_EQ(sinkFd, retrieved.get());
1772}
1773
1774TEST_P(BinderRpcServerOnly, Shutdown) {
1775 if constexpr (!kEnableRpcThreads) {
1776 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1777 }
1778
1779 auto addr = allocateSocketAddress();
1780 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1781 server->setProtocolVersion(std::get<1>(GetParam()));
1782 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1783 auto joinEnds = std::make_shared<OneOffSignal>();
1784
1785 // If things are broken and the thread never stops, don't block other tests. Because the thread
1786 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1787 // shared pointers are passed.
1788 std::thread([server, joinEnds] {
1789 server->join();
1790 joinEnds->notify();
1791 }).detach();
1792
1793 bool shutdown = false;
1794 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001795 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001796 if (server->shutdown()) shutdown = true;
1797 }
1798 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1799
1800 ASSERT_TRUE(joinEnds->wait(2s))
1801 << "After server->shutdown() returns true, join() did not stop after 2s";
1802}
1803
Frederick Mayledc07cf82022-05-26 20:30:12 +00001804INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1805 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1806 ::testing::ValuesIn(testVersions())),
1807 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001808
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001809class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001810public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001811 // Only parameterized only server version because `RpcSession` is bypassed
1812 // in the client half of the tests.
1813 using Param =
1814 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001815 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001816
1817 // A server that handles client socket connections.
1818 class Server {
1819 public:
David Brazdil21c887c2022-09-23 12:25:18 +01001820 using AcceptConnection = std::function<base::unique_fd(Server*)>;
1821
Yifan Hong1deca4b2021-09-10 16:16:44 -07001822 explicit Server() {}
1823 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001824 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001825 [[nodiscard]] AssertionResult setUp(
1826 const Param& param,
1827 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001828 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001829 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001830 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001831 switch (socketType) {
1832 case SocketType::PRECONNECTED: {
1833 return AssertionFailure() << "Not supported by this test";
1834 } break;
1835 case SocketType::UNIX: {
1836 auto addr = allocateSocketAddress();
1837 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1838 if (status != OK) {
1839 return AssertionFailure()
1840 << "setupUnixDomainServer: " << statusToString(status);
1841 }
1842 mConnectToServer = [addr] {
1843 return connectTo(UnixSocketAddress(addr.c_str()));
1844 };
1845 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001846 case SocketType::UNIX_BOOTSTRAP: {
1847 base::unique_fd bootstrapFdClient, bootstrapFdServer;
1848 if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1849 return AssertionFailure() << "Socketpair() failed";
1850 }
1851 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1852 std::move(bootstrapFdServer));
1853 if (status != OK) {
1854 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1855 << statusToString(status);
1856 }
1857 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1858 mAcceptConnection = &Server::recvmsgServerConnection;
1859 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1860 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001861 case SocketType::VSOCK: {
1862 auto port = allocateVsockPort();
1863 auto status = rpcServer->setupVsockServer(port);
1864 if (status != OK) {
1865 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1866 }
1867 mConnectToServer = [port] {
1868 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1869 };
1870 } break;
1871 case SocketType::INET: {
1872 unsigned int port;
1873 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1874 if (status != OK) {
1875 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1876 }
1877 mConnectToServer = [port] {
1878 const char* addr = kLocalInetAddress;
1879 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1880 if (aiStart == nullptr) return base::unique_fd{};
1881 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1882 auto fd = connectTo(
1883 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1884 if (fd.ok()) return fd;
1885 }
1886 ALOGE("None of the socket address resolved for %s:%u can be connected",
1887 addr, port);
1888 return base::unique_fd{};
1889 };
1890 }
1891 }
1892 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001893 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001894 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001895 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1896 mSetup = true;
1897 return AssertionSuccess();
1898 }
1899 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1900 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1901 return mCertVerifier;
1902 }
1903 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1904 void start() {
1905 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1906 mThread = std::make_unique<std::thread>(&Server::run, this);
1907 }
David Brazdil21c887c2022-09-23 12:25:18 +01001908
1909 base::unique_fd acceptServerConnection() {
1910 return base::unique_fd(TEMP_FAILURE_RETRY(
1911 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1912 }
1913
1914 base::unique_fd recvmsgServerConnection() {
1915 std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
1916 int buf;
1917 iovec iov{&buf, sizeof(buf)};
1918
1919 if (receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1920 int savedErrno = errno;
1921 LOG(FATAL) << "Failed receiveMessage: " << strerror(savedErrno);
1922 }
1923 if (fds.size() != 1) {
1924 LOG(FATAL) << "Expected one FD from receiveMessage(), got " << fds.size();
1925 }
1926 return std::move(std::get<base::unique_fd>(fds[0]));
1927 }
1928
Yifan Hong1deca4b2021-09-10 16:16:44 -07001929 void run() {
1930 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1931
1932 std::vector<std::thread> threads;
1933 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001934 base::unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001935 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1936 }
1937
1938 for (auto& thread : threads) thread.join();
1939 }
1940 void handleOne(android::base::unique_fd acceptedFd) {
1941 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001942 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001943 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001944 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001945 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001946 }
Yifan Honge07d2732021-09-13 21:59:14 -07001947 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001948 shutdown();
1949 join();
1950 }
1951 void shutdown() { mFdTrigger->trigger(); }
1952
1953 void setPostConnect(
1954 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1955 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001956 }
1957
1958 private:
1959 std::unique_ptr<std::thread> mThread;
1960 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001961 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001962 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001963 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001964 std::unique_ptr<RpcTransportCtx> mCtx;
1965 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1966 std::make_shared<RpcCertificateVerifierSimple>();
1967 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001968 // The function invoked after connection and handshake. By default, it is
1969 // |defaultPostConnect| that sends |kMessage| to the client.
1970 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1971 Server::defaultPostConnect;
1972
1973 void join() {
1974 if (mThread != nullptr) {
1975 mThread->join();
1976 mThread = nullptr;
1977 }
1978 }
1979
1980 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1981 FdTrigger* fdTrigger) {
1982 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001983 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001984 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001985 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001986 if (status != OK) return AssertionFailure() << statusToString(status);
1987 return AssertionSuccess();
1988 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001989 };
1990
1991 class Client {
1992 public:
1993 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1994 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001995 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001996 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1997 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001998 mFdTrigger = FdTrigger::make();
1999 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
2000 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
2001 return AssertionSuccess();
2002 }
2003 RpcTransportCtx* getCtx() const { return mCtx.get(); }
2004 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
2005 return mCertVerifier;
2006 }
Yifan Hong67519322021-09-13 18:51:16 -07002007 // connect() and do handshake
2008 bool setUpTransport() {
2009 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00002010 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07002011 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
2012 return mClientTransport != nullptr;
2013 }
2014 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
2015 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
2016 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002017 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00002018 status_t readStatus =
2019 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00002020 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002021 if (readStatus != OK) {
2022 return AssertionFailure() << statusToString(readStatus);
2023 }
2024 if (readMessage != expectedMessage) {
2025 return AssertionFailure()
2026 << "Expected " << expectedMessage << ", actual " << readMessage;
2027 }
2028 return AssertionSuccess();
2029 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002030 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07002031 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07002032 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
2033 return;
2034 }
2035 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07002036 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07002037 }
2038
Pawan49d74cb2022-08-03 21:19:11 +00002039 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
2040
Yifan Hong1deca4b2021-09-10 16:16:44 -07002041 private:
2042 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00002043 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002044 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
2045 std::unique_ptr<RpcTransportCtx> mCtx;
2046 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
2047 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07002048 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002049 };
2050
2051 // Make A trust B.
2052 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002053 static status_t trust(RpcSecurity rpcSecurity,
2054 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
2055 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07002056 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07002057 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
2058 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
2059 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002060 }
2061
2062 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002063};
2064
2065class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
2066public:
2067 using Server = RpcTransportTestUtils::Server;
2068 using Client = RpcTransportTestUtils::Client;
2069 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002070 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002071 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
2072 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00002073 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002074 return ret;
2075 }
2076 static std::vector<ParamType> getRpcTranportTestParams() {
2077 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00002078 for (auto serverVersion : testVersions()) {
2079 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
2080 for (auto rpcSecurity : RpcSecurityValues()) {
2081 switch (rpcSecurity) {
2082 case RpcSecurity::RAW: {
2083 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
2084 } break;
2085 case RpcSecurity::TLS: {
2086 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
2087 serverVersion);
2088 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
2089 serverVersion);
2090 } break;
2091 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002092 }
2093 }
2094 }
2095 return ret;
2096 }
2097 template <typename A, typename B>
2098 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002099 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2100 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002101 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
2102 }
Andrei Homescu12106de2022-04-27 04:42:21 +00002103 void SetUp() override {
2104 if constexpr (!kEnableRpcThreads) {
2105 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2106 }
2107 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002108};
2109
2110TEST_P(RpcTransportTest, GoodCertificate) {
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 ASSERT_EQ(OK, trust(server, &client));
2119
2120 server->start();
2121 client.run();
2122}
2123
2124TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002125 auto server = std::make_unique<Server>();
2126 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002127
2128 std::vector<Client> clients;
2129 for (int i = 0; i < 2; i++) {
2130 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002131 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002132 ASSERT_EQ(OK, trust(&client, server));
2133 ASSERT_EQ(OK, trust(server, &client));
2134 }
2135
2136 server->start();
2137 for (auto& client : clients) client.run();
2138}
2139
2140TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002141 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2142 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002143
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002144 auto untrustedServer = std::make_unique<Server>();
2145 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002146
2147 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002148 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002149
2150 ASSERT_EQ(OK, trust(untrustedServer, &client));
2151
2152 untrustedServer->start();
2153
2154 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2155 // the client can't verify the server's identity.
2156 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2157 client.run(handshakeOk);
2158}
2159TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002160 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2161 (void)serverVersion;
2162
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002163 auto validServer = std::make_unique<Server>();
2164 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002165
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002166 auto maliciousServer = std::make_unique<Server>();
2167 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002168
2169 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002170 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002171
2172 ASSERT_EQ(OK, trust(&client, validServer));
2173 ASSERT_EQ(OK, trust(validServer, &client));
2174 ASSERT_EQ(OK, trust(maliciousServer, &client));
2175
2176 maliciousServer->start();
2177
2178 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2179 // the client can't verify the server's identity.
2180 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2181 client.run(handshakeOk);
2182}
2183
2184TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002185 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2186 (void)serverVersion;
2187
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002188 auto server = std::make_unique<Server>();
2189 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002190
2191 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002192 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002193
2194 ASSERT_EQ(OK, trust(&client, server));
2195
2196 server->start();
2197
2198 // For TLS, Client should be able to verify server's identity, so client should see
2199 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2200 // identity and should drop the connection, so client shouldn't be able to read anything.
2201 bool readOk = rpcSecurity != RpcSecurity::TLS;
2202 client.run(true, readOk);
2203}
2204
2205TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002206 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2207 (void)serverVersion;
2208
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002209 auto server = std::make_unique<Server>();
2210 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002211
2212 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002213 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002214 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002215 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002216
2217 ASSERT_EQ(OK, trust(&validClient, server));
2218 ASSERT_EQ(OK, trust(&maliciousClient, server));
2219
2220 server->start();
2221
2222 // See UntrustedClient.
2223 bool readOk = rpcSecurity != RpcSecurity::TLS;
2224 maliciousClient.run(true, readOk);
2225}
2226
Yifan Hong67519322021-09-13 18:51:16 -07002227TEST_P(RpcTransportTest, Trigger) {
2228 std::string msg2 = ", world!";
2229 std::mutex writeMutex;
2230 std::condition_variable writeCv;
2231 bool shouldContinueWriting = false;
2232 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002233 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002234 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002235 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2236 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002237 if (status != OK) return AssertionFailure() << statusToString(status);
2238
2239 {
2240 std::unique_lock<std::mutex> lock(writeMutex);
2241 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2242 return AssertionFailure() << "write barrier not cleared in time!";
2243 }
2244 }
2245
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002246 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002247 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2248 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002249 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002250 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002251 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002252 << statusToString(status);
2253 return AssertionSuccess();
2254 };
2255
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002256 auto server = std::make_unique<Server>();
2257 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002258
2259 // Set up client
2260 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002261 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002262
2263 // Exchange keys
2264 ASSERT_EQ(OK, trust(&client, server));
2265 ASSERT_EQ(OK, trust(server, &client));
2266
2267 server->setPostConnect(serverPostConnect);
2268
Yifan Hong67519322021-09-13 18:51:16 -07002269 server->start();
2270 // connect() to server and do handshake
2271 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002272 // read the first message. This ensures that server has finished handshake and start handling
2273 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002274 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002275 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2276 // write is on an FdTrigger that has been shut down.
2277 server->shutdown();
2278 // Continues server thread to write the second message.
2279 {
Yifan Hong22211f82021-09-14 12:32:25 -07002280 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002281 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002282 }
Yifan Hong22211f82021-09-14 12:32:25 -07002283 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002284 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002285 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002286 // On the client side, second read fails with DEAD_OBJECT
2287 ASSERT_FALSE(client.readMessage(msg2));
2288}
2289
Pawan49d74cb2022-08-03 21:19:11 +00002290TEST_P(RpcTransportTest, CheckWaitingForRead) {
2291 std::mutex readMutex;
2292 std::condition_variable readCv;
2293 bool shouldContinueReading = false;
2294 // Server will write data on transport once its started
2295 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
2296 std::string message(RpcTransportTestUtils::kMessage);
2297 iovec messageIov{message.data(), message.size()};
2298 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2299 std::nullopt, nullptr);
2300 if (status != OK) return AssertionFailure() << statusToString(status);
2301
2302 {
2303 std::unique_lock<std::mutex> lock(readMutex);
2304 shouldContinueReading = true;
2305 lock.unlock();
2306 readCv.notify_all();
2307 }
2308 return AssertionSuccess();
2309 };
2310
2311 // Setup Server and client
2312 auto server = std::make_unique<Server>();
2313 ASSERT_TRUE(server->setUp(GetParam()));
2314
2315 Client client(server->getConnectToServerFn());
2316 ASSERT_TRUE(client.setUp(GetParam()));
2317
2318 ASSERT_EQ(OK, trust(&client, server));
2319 ASSERT_EQ(OK, trust(server, &client));
2320 server->setPostConnect(serverPostConnect);
2321
2322 server->start();
2323 ASSERT_TRUE(client.setUpTransport());
2324 {
2325 // Wait till server writes data
2326 std::unique_lock<std::mutex> lock(readMutex);
2327 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2328 }
2329
2330 // Since there is no read polling here, we will get polling count 0
2331 ASSERT_FALSE(client.isTransportWaiting());
2332 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2333 // Thread should increment polling count, read and decrement polling count
2334 // Again, polling count should be zero here
2335 ASSERT_FALSE(client.isTransportWaiting());
2336
2337 server->shutdown();
2338}
2339
Yifan Hong1deca4b2021-09-10 16:16:44 -07002340INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002341 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002342 RpcTransportTest::PrintParamInfo);
2343
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002344class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002345 : public testing::TestWithParam<
2346 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002347public:
2348 template <typename A, typename B>
2349 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002350 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2351 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002352 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2353 }
2354 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002355 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2356 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2357 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002358 };
2359};
2360
2361TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002362 if constexpr (!kEnableRpcThreads) {
2363 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2364 }
2365
Frederick Mayledc07cf82022-05-26 20:30:12 +00002366 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002367
2368 std::vector<uint8_t> pkeyData, certData;
2369 {
2370 auto pkey = makeKeyPairForSelfSignedCert();
2371 ASSERT_NE(nullptr, pkey);
2372 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2373 ASSERT_NE(nullptr, cert);
2374 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2375 certData = serializeCertificate(cert.get(), certificateFormat);
2376 }
2377
2378 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2379 auto desCert = deserializeCertificate(certData, certificateFormat);
2380 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002381 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2382 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002383
2384 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2385 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2386
2387 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2388 ASSERT_TRUE(client.setUp(utilsParam));
2389
2390 ASSERT_EQ(OK, trust(&client, server));
2391 ASSERT_EQ(OK, trust(server, &client));
2392
2393 server->start();
2394 client.run();
2395}
2396
2397INSTANTIATE_TEST_CASE_P(
2398 BinderRpc, RpcTransportTlsKeyTest,
2399 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2400 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002401 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2402 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002403 RpcTransportTlsKeyTest::PrintParamInfo);
2404
Steven Morelandc1635952021-04-01 16:20:47 +00002405} // namespace android
2406
2407int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002408 ::testing::InitGoogleTest(&argc, argv);
2409 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002410
Steven Moreland5553ac42020-11-11 02:14:45 +00002411 return RUN_ALL_TESTS();
2412}