blob: 0ef200bcbe1ca7aa458733cb843b139766d4b7fd [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
Tomasz Wasilczyk38a22ee2023-10-19 20:04:46 +000017#ifndef __ANDROID_VENDOR__
18// only used on NDK tests outside of vendor
Andrei Homescu9d8adb12022-08-02 04:38:30 +000019#include <aidl/IBinderRpcTest.h>
Tomasz Wasilczyk38a22ee2023-10-19 20:04:46 +000020#endif
Steven Moreland5553ac42020-11-11 02:14:45 +000021
Devin Moore1df9c5f2024-07-23 22:09:29 +000022#if defined(__LP64__)
23#define TEST_FILE_SUFFIX "64"
24#else
25#define TEST_FILE_SUFFIX "32"
26#endif
27
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <chrono>
29#include <cstdlib>
30#include <iostream>
31#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000032#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000033
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070034#include <dirent.h>
Andrei Homescu2a298012022-06-15 01:08:54 +000035#include <dlfcn.h>
Yifan Hong1deca4b2021-09-10 16:16:44 -070036#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000037#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000038#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000039
Andrei Homescud65666d2023-03-03 07:28:02 +000040#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000041#include <binder/RpcTransportTipcAndroid.h>
42#include <trusty/tipc.h>
Andrei Homescud65666d2023-03-03 07:28:02 +000043#endif // BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000044
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -080045#include "../Utils.h"
Andrei Homescu2a298012022-06-15 01:08:54 +000046#include "binderRpcTestCommon.h"
Andrei Homescu96834632022-10-14 00:49:49 +000047#include "binderRpcTestFixture.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000048
Yifan Hong1a235852021-05-13 16:07:47 -070049using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070050using namespace std::placeholders;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070051using android::binder::borrowed_fd;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -070052using android::binder::GetExecutableDirectory;
53using android::binder::ReadFdToString;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070054using android::binder::unique_fd;
Yifan Hong1deca4b2021-09-10 16:16:44 -070055using testing::AssertionFailure;
56using testing::AssertionResult;
57using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070058
Steven Moreland5553ac42020-11-11 02:14:45 +000059namespace android {
60
Andrei Homescu12106de2022-04-27 04:42:21 +000061#ifdef BINDER_TEST_NO_SHARED_LIBS
62constexpr bool kEnableSharedLibs = false;
63#else
64constexpr bool kEnableSharedLibs = true;
65#endif
66
Andrei Homescud65666d2023-03-03 07:28:02 +000067#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +000068constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
69#endif
70
Frederick Maylea12b0962022-06-25 01:13:22 +000071static std::string WaitStatusToString(int wstatus) {
72 if (WIFEXITED(wstatus)) {
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070073 return "exit status " + std::to_string(WEXITSTATUS(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000074 }
75 if (WIFSIGNALED(wstatus)) {
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070076 return "term signal " + std::to_string(WTERMSIG(wstatus));
Frederick Maylea12b0962022-06-25 01:13:22 +000077 }
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -070078 return "unexpected state " + std::to_string(wstatus);
Frederick Maylea12b0962022-06-25 01:13:22 +000079}
80
Steven Moreland276d8df2022-09-28 23:56:39 +000081static void debugBacktrace(pid_t pid) {
82 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
83 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
84}
85
Steven Moreland5553ac42020-11-11 02:14:45 +000086class Process {
87public:
Andrei Homescu96834632022-10-14 00:49:49 +000088 Process(Process&& other)
89 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
90 mReadEnd(std::move(other.mReadEnd)),
91 mWriteEnd(std::move(other.mWriteEnd)) {
92 // The default move constructor doesn't clear mPid after moving it,
93 // which we need to do because the destructor checks for mPid!=0
94 mPid = other.mPid;
95 other.mPid = 0;
96 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070097 Process(const std::function<void(borrowed_fd /* writeEnd */, borrowed_fd /* readEnd */)>& f) {
98 unique_fd childWriteEnd;
99 unique_fd childReadEnd;
100 if (!binder::Pipe(&mReadEnd, &childWriteEnd, 0)) PLOGF("child write pipe failed");
101 if (!binder::Pipe(&childReadEnd, &mWriteEnd, 0)) PLOGF("child read pipe failed");
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 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700123 borrowed_fd readEnd() { return mReadEnd; }
124 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;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700138 unique_fd mReadEnd;
139 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";
Steven Morelanddfb05ad2023-03-07 17:00:53 +0000145 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700146 unlink(ret.c_str());
147 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000148};
149
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700150static unique_fd initUnixSocket(std::string addr) {
Alice Wang893a9912022-10-24 10:44:09 +0000151 auto socket_addr = UnixSocketAddress(addr.c_str());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700152 unique_fd fd(TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700153 if (!fd.ok()) PLOGF("initUnixSocket failed to create socket");
154 if (0 != TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize()))) {
155 PLOGF("initUnixSocket failed to bind");
156 }
Alice Wang893a9912022-10-24 10:44:09 +0000157 return fd;
158}
159
Andrei Homescu96834632022-10-14 00:49:49 +0000160// Destructors need to be defined, even if pure virtual
161ProcessSession::~ProcessSession() {}
162
163class LinuxProcessSession : public ProcessSession {
164public:
Steven Moreland5553ac42020-11-11 02:14:45 +0000165 // reference to process hosting a socket server
166 Process host;
167
Andrei Homescu96834632022-10-14 00:49:49 +0000168 LinuxProcessSession(LinuxProcessSession&&) = default;
169 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
170 ~LinuxProcessSession() override {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000171 for (auto& session : sessions) {
172 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000173 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000174
Steven Moreland67f85902023-03-15 01:13:49 +0000175 for (size_t sessionNum = 0; sessionNum < sessions.size(); sessionNum++) {
176 auto& info = sessions.at(sessionNum);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000177 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000178
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000179 EXPECT_NE(nullptr, session);
180 EXPECT_NE(nullptr, session->state());
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700181 EXPECT_EQ(0u, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000182
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000183 wp<RpcSession> weakSession = session;
184 session = nullptr;
Steven Moreland276d8df2022-09-28 23:56:39 +0000185
Steven Moreland57042712022-10-04 23:56:45 +0000186 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
187 // the object should not actually be promotable. By looping, we distinguish a race here
188 // from a bug causing the object to not be promotable.
189 for (size_t i = 0; i < 3; i++) {
190 sp<RpcSession> strongSession = weakSession.promote();
191 EXPECT_EQ(nullptr, strongSession)
Steven Moreland67f85902023-03-15 01:13:49 +0000192 << "For session " << sessionNum << ". "
Steven Moreland57042712022-10-04 23:56:45 +0000193 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
194 "Leaked sess: ")
195 << strongSession->getStrongCount() << " checked time " << i;
196
197 if (strongSession != nullptr) {
198 sleep(1);
199 }
200 }
Steven Moreland736664b2021-05-01 04:27:25 +0000201 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000202 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000203
Andrei Homescu96834632022-10-14 00:49:49 +0000204 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
205 host.setCustomExitStatusCheck(std::move(f));
Steven Moreland5553ac42020-11-11 02:14:45 +0000206 }
Andrei Homescu96834632022-10-14 00:49:49 +0000207
208 void terminate() override { host.terminate(); }
Steven Moreland5553ac42020-11-11 02:14:45 +0000209};
210
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700211static unique_fd connectTo(const RpcSocketAddress& addr) {
212 unique_fd serverFd(
Steven Moreland4198a122021-08-03 17:37:58 -0700213 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700214 if (!serverFd.ok()) {
215 PLOGF("Could not create socket %s", addr.toString().c_str());
216 }
Steven Moreland4198a122021-08-03 17:37:58 -0700217
218 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700219 PLOGF("Could not connect to socket %s", addr.toString().c_str());
Steven Moreland4198a122021-08-03 17:37:58 -0700220 }
221 return serverFd;
222}
223
Andrei Homescud65666d2023-03-03 07:28:02 +0000224#ifndef BINDER_RPC_TO_TRUSTY_TEST
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700225static unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
226 unique_fd sockClient, sockServer;
227 if (!binder::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700228 PLOGF("Failed socketpair()");
David Brazdil21c887c2022-09-23 12:25:18 +0100229 }
230
231 int zero = 0;
232 iovec iov{&zero, sizeof(zero)};
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700233 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +0100234 fds.emplace_back(std::move(sockServer));
235
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +0000236 if (binder::os::sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700237 PLOGF("Failed sendMessageOnSocket");
David Brazdil21c887c2022-09-23 12:25:18 +0100238 }
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700239 return sockClient;
David Brazdil21c887c2022-09-23 12:25:18 +0100240}
Andrei Homescud65666d2023-03-03 07:28:02 +0000241#endif // BINDER_RPC_TO_TRUSTY_TEST
David Brazdil21c887c2022-09-23 12:25:18 +0100242
Andrei Homescuf30148c2023-03-10 00:31:45 +0000243std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
244 return newTlsFactory(rpcSecurity);
Andrei Homescu96834632022-10-14 00:49:49 +0000245}
Andrei Homescu2a298012022-06-15 01:08:54 +0000246
Andrei Homescu96834632022-10-14 00:49:49 +0000247// This creates a new process serving an interface on a certain number of
248// threads.
249std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
250 const BinderRpcOptions& options) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700251 LOG_ALWAYS_FATAL_IF(options.numSessions < 1, "Must have at least one session to a server");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000252
Steven Moreland67f85902023-03-15 01:13:49 +0000253 if (options.numIncomingConnectionsBySession.size() != 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700254 LOG_ALWAYS_FATAL_IF(options.numIncomingConnectionsBySession.size() != options.numSessions,
255 "%s: %zu != %zu", __func__,
256 options.numIncomingConnectionsBySession.size(), options.numSessions);
Steven Moreland67f85902023-03-15 01:13:49 +0000257 }
258
Steven Morelandb469f432023-07-28 22:13:47 +0000259 SocketType socketType = GetParam().type;
260 RpcSecurity rpcSecurity = GetParam().security;
261 uint32_t clientVersion = GetParam().clientVersion;
262 uint32_t serverVersion = GetParam().serverVersion;
263 bool singleThreaded = GetParam().singleThreaded;
264 bool noKernel = GetParam().noKernel;
Andrei Homescu96834632022-10-14 00:49:49 +0000265
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700266 std::string path = GetExecutableDirectory();
Tomasz Wasilczyk68c42082024-05-20 11:59:35 -0700267 auto servicePath = path + "/binder_rpc_test_service" +
Devin Moore1df9c5f2024-07-23 22:09:29 +0000268 (singleThreaded ? "_single_threaded" : "") + (noKernel ? "_no_kernel" : "") +
269 TEST_FILE_SUFFIX;
Andrei Homescu96834632022-10-14 00:49:49 +0000270
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700271 unique_fd bootstrapClientFd, socketFd;
Alice Wang1ef010b2022-11-14 09:09:25 +0000272
Alice Wang893a9912022-10-24 10:44:09 +0000273 auto addr = allocateSocketAddress();
274 // Initializes the socket before the fork/exec.
275 if (socketType == SocketType::UNIX_RAW) {
276 socketFd = initUnixSocket(addr);
Alice Wang1ef010b2022-11-14 09:09:25 +0000277 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
278 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
279 // This is because we cannot pass ParcelFileDescriptor over a pipe.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700280 if (!binder::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700281 PLOGF("Failed socketpair()");
Alice Wang1ef010b2022-11-14 09:09:25 +0000282 }
Alice Wang893a9912022-10-24 10:44:09 +0000283 }
Andrei Homescua858b0e2022-08-01 23:43:09 +0000284
Andrei Homescu96834632022-10-14 00:49:49 +0000285 auto ret = std::make_unique<LinuxProcessSession>(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700286 Process([=](borrowed_fd writeEnd, borrowed_fd readEnd) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000287 if (socketType == SocketType::TIPC) {
288 // Trusty has a single persistent service
289 return;
290 }
291
Andrei Homescu96834632022-10-14 00:49:49 +0000292 auto writeFd = std::to_string(writeEnd.get());
293 auto readFd = std::to_string(readEnd.get());
Tomasz Wasilczyk7ba2e7e2023-11-13 13:18:57 -0800294 auto status = execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(),
295 readFd.c_str(), NULL);
296 PLOGF("execl('%s', _, %s, %s) should not return at all, but it returned %d",
297 servicePath.c_str(), writeFd.c_str(), readFd.c_str(), status);
Andrei Homescu96834632022-10-14 00:49:49 +0000298 }));
299
300 BinderRpcTestServerConfig serverConfig;
301 serverConfig.numThreads = options.numThreads;
302 serverConfig.socketType = static_cast<int32_t>(socketType);
303 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
304 serverConfig.serverVersion = serverVersion;
Alice Wang893a9912022-10-24 10:44:09 +0000305 serverConfig.addr = addr;
Alice Wang893a9912022-10-24 10:44:09 +0000306 serverConfig.socketFd = socketFd.get();
Andrei Homescu96834632022-10-14 00:49:49 +0000307 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
308 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
309 static_cast<int32_t>(mode));
310 }
Andrei Homescu68a55612022-08-02 01:25:15 +0000311 if (socketType != SocketType::TIPC) {
312 writeToFd(ret->host.writeEnd(), serverConfig);
313 }
Andrei Homescu96834632022-10-14 00:49:49 +0000314
315 std::vector<sp<RpcSession>> sessions;
316 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
317 for (size_t i = 0; i < options.numSessions; i++) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000318 std::unique_ptr<RpcTransportCtxFactory> factory;
319 if (socketType == SocketType::TIPC) {
Andrei Homescud65666d2023-03-03 07:28:02 +0000320#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000321 factory = RpcTransportCtxFactoryTipcAndroid::make();
322#else
323 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
324#endif
325 } else {
Andrei Homescuf30148c2023-03-10 00:31:45 +0000326 factory = newTlsFactory(rpcSecurity, certVerifier);
Andrei Homescu68a55612022-08-02 01:25:15 +0000327 }
328 sessions.emplace_back(RpcSession::make(std::move(factory)));
David Brazdil21c887c2022-09-23 12:25:18 +0100329 }
330
Andrei Homescu68a55612022-08-02 01:25:15 +0000331 BinderRpcTestServerInfo serverInfo;
332 if (socketType != SocketType::TIPC) {
333 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
334 BinderRpcTestClientInfo clientInfo;
335 for (const auto& session : sessions) {
336 auto& parcelableCert = clientInfo.certs.emplace_back();
337 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
338 }
339 writeToFd(ret->host.writeEnd(), clientInfo);
Andrei Homescu96834632022-10-14 00:49:49 +0000340
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700341 LOG_ALWAYS_FATAL_IF(serverInfo.port > std::numeric_limits<unsigned int>::max());
Andrei Homescu68a55612022-08-02 01:25:15 +0000342 if (socketType == SocketType::INET) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700343 LOG_ALWAYS_FATAL_IF(0 == serverInfo.port);
Andrei Homescu68a55612022-08-02 01:25:15 +0000344 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000345
Andrei Homescu68a55612022-08-02 01:25:15 +0000346 if (rpcSecurity == RpcSecurity::TLS) {
347 const auto& serverCert = serverInfo.cert.data;
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700348 LOG_ALWAYS_FATAL_IF(
349 OK !=
350 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
Andrei Homescu68a55612022-08-02 01:25:15 +0000351 }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700352 }
353
Andrei Homescu96834632022-10-14 00:49:49 +0000354 status_t status;
Steven Moreland736664b2021-05-01 04:27:25 +0000355
Steven Moreland67f85902023-03-15 01:13:49 +0000356 for (size_t i = 0; i < sessions.size(); i++) {
357 const auto& session = sessions.at(i);
358
359 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
360 ? options.numIncomingConnectionsBySession.at(i)
361 : 0;
362
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700363 LOG_ALWAYS_FATAL_IF(!session->setProtocolVersion(clientVersion));
Steven Moreland67f85902023-03-15 01:13:49 +0000364 session->setMaxIncomingThreads(numIncoming);
Steven Morelandfeb13e82023-03-01 01:25:33 +0000365 session->setMaxOutgoingConnections(options.numOutgoingConnections);
Andrei Homescu96834632022-10-14 00:49:49 +0000366 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Morelandc1635952021-04-01 16:20:47 +0000367
Devin Moore18f63752024-08-08 21:01:24 +0000368 sockaddr_storage addr{};
369 socklen_t addrLen = 0;
370
Andrei Homescu96834632022-10-14 00:49:49 +0000371 switch (socketType) {
Devin Moore18f63752024-08-08 21:01:24 +0000372 case SocketType::PRECONNECTED: {
373 sockaddr_un addr_un{};
374 addr_un.sun_family = AF_UNIX;
375 strcpy(addr_un.sun_path, serverConfig.addr.c_str());
376 addr = *reinterpret_cast<sockaddr_storage*>(&addr_un);
377 addrLen = sizeof(sockaddr_un);
378
Andrei Homescu96834632022-10-14 00:49:49 +0000379 status = session->setupPreconnectedClient({}, [=]() {
380 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
381 });
Devin Moore18f63752024-08-08 21:01:24 +0000382 } break;
Alice Wang893a9912022-10-24 10:44:09 +0000383 case SocketType::UNIX_RAW:
Devin Moore18f63752024-08-08 21:01:24 +0000384 case SocketType::UNIX: {
385 sockaddr_un addr_un{};
386 addr_un.sun_family = AF_UNIX;
387 strcpy(addr_un.sun_path, serverConfig.addr.c_str());
388 addr = *reinterpret_cast<sockaddr_storage*>(&addr_un);
389 addrLen = sizeof(sockaddr_un);
390
Andrei Homescu96834632022-10-14 00:49:49 +0000391 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
Devin Moore18f63752024-08-08 21:01:24 +0000392 } break;
Andrei Homescu96834632022-10-14 00:49:49 +0000393 case SocketType::UNIX_BOOTSTRAP:
394 status = session->setupUnixDomainSocketBootstrapClient(
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700395 unique_fd(dup(bootstrapClientFd.get())));
Andrei Homescu96834632022-10-14 00:49:49 +0000396 break;
Devin Moore18f63752024-08-08 21:01:24 +0000397 case SocketType::VSOCK: {
398 sockaddr_vm addr_vm{
399 .svm_family = AF_VSOCK,
400 .svm_port = static_cast<unsigned int>(serverInfo.port),
401 .svm_cid = VMADDR_CID_LOCAL,
402 };
403 addr = *reinterpret_cast<sockaddr_storage*>(&addr_vm);
404 addrLen = sizeof(sockaddr_vm);
405
Tomasz Wasilczyk022db682024-06-17 13:55:51 -0700406 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverInfo.port);
Devin Moore18f63752024-08-08 21:01:24 +0000407 } break;
408 case SocketType::INET: {
409 const std::string ip_addr = "127.0.0.1";
410 sockaddr_in addr_in{};
411 addr_in.sin_family = AF_INET;
412 addr_in.sin_port = htons(serverInfo.port);
413 inet_aton(ip_addr.c_str(), &addr_in.sin_addr);
414 addr = *reinterpret_cast<sockaddr_storage*>(&addr_in);
415 addrLen = sizeof(sockaddr_in);
416
417 status = session->setupInetClient(ip_addr.c_str(), serverInfo.port);
418 } break;
Andrei Homescu68a55612022-08-02 01:25:15 +0000419 case SocketType::TIPC:
420 status = session->setupPreconnectedClient({}, [=]() {
Andrei Homescud65666d2023-03-03 07:28:02 +0000421#ifdef BINDER_RPC_TO_TRUSTY_TEST
Andrei Homescu68a55612022-08-02 01:25:15 +0000422 auto port = trustyIpcPort(serverVersion);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000423 for (size_t i = 0; i < 5; i++) {
424 // Try to connect several times,
425 // in case the service is slow to start
426 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
427 if (tipcFd >= 0) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700428 return unique_fd(tipcFd);
Andrei Homescu4bea21772023-03-21 23:28:33 +0000429 }
430 usleep(50000);
431 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700432 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000433#else
434 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700435 return unique_fd();
Andrei Homescu68a55612022-08-02 01:25:15 +0000436#endif
437 });
438 break;
Andrei Homescu96834632022-10-14 00:49:49 +0000439 default:
440 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000441 }
Andrei Homescu96834632022-10-14 00:49:49 +0000442 if (options.allowConnectFailure && status != OK) {
443 ret->sessions.clear();
444 break;
445 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700446 LOG_ALWAYS_FATAL_IF(status != OK, "Could not connect: %s", statusToString(status).c_str());
Devin Moore18f63752024-08-08 21:01:24 +0000447 ret->sessions.push_back({session, session->getRootObject(), addr, addrLen});
Steven Morelandc1635952021-04-01 16:20:47 +0000448 }
Andrei Homescu96834632022-10-14 00:49:49 +0000449 return ret;
450}
Steven Morelandc1635952021-04-01 16:20:47 +0000451
Andrei Homescua858b0e2022-08-01 23:43:09 +0000452TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
453 if (clientOrServerSingleThreaded()) {
454 GTEST_SKIP() << "This test requires multiple threads";
455 }
456
Steven Moreland51cdc2c2024-09-17 17:21:27 +0000457 constexpr size_t kNumThreads = 5;
Steven Moreland5553ac42020-11-11 02:14:45 +0000458
Steven Moreland4313d7e2021-07-15 23:41:22 +0000459 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000460
461 EXPECT_OK(proc.rootIface->lock());
462
463 // block all but one thread taking locks
464 std::vector<std::thread> ts;
465 for (size_t i = 0; i < kNumThreads - 1; i++) {
466 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
467 }
468
Steven Morelandd6d816f2022-12-23 01:37:17 +0000469 usleep(100000); // give chance for calls on other threads
Steven Moreland5553ac42020-11-11 02:14:45 +0000470
471 // other calls still work
472 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
473
Steven Morelandd6d816f2022-12-23 01:37:17 +0000474 constexpr size_t blockTimeMs = 100;
Steven Moreland5553ac42020-11-11 02:14:45 +0000475 size_t epochMsBefore = epochMillis();
476 // after this, we should never see a response within this time
477 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
478
479 // this call should be blocked for blockTimeMs
480 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
481
482 size_t epochMsAfter = epochMillis();
483 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
484
485 for (auto& t : ts) t.join();
486}
487
Steven Moreland27f620a2023-03-06 19:44:36 +0000488static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000489 size_t epochMsBefore = epochMillis();
490
491 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -0700492 for (size_t i = 0; i < numCalls; i++) {
493 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +0000494 }
495
496 for (auto& t : ts) t.join();
497
498 size_t epochMsAfter = epochMillis();
499
Yifan Hong1f44f982021-10-08 17:16:47 -0700500 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +0000501
Steven Moreland68e2ee22024-09-18 01:18:48 +0000502 // b/272429574, b/365294257
503 // This flakes too much to test. Parallelization is tested
504 // in ThreadPoolGreaterThanEqualRequested and other tests.
505 // Test to make sure calls are handled in parallel.
506 // EXPECT_LE(epochMsAfter, epochMsBefore + (numCalls - 1) * sleepMs);
Yifan Hong1f44f982021-10-08 17:16:47 -0700507}
508
Andrei Homescua858b0e2022-08-01 23:43:09 +0000509TEST_P(BinderRpc, ThreadPoolOverSaturated) {
510 if (clientOrServerSingleThreaded()) {
511 GTEST_SKIP() << "This test requires multiple threads";
512 }
513
Yifan Hong1f44f982021-10-08 17:16:47 -0700514 constexpr size_t kNumThreads = 10;
515 constexpr size_t kNumCalls = kNumThreads + 3;
516 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000517
Steven Moreland68e2ee22024-09-18 01:18:48 +0000518 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 200 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700519}
520
Andrei Homescua858b0e2022-08-01 23:43:09 +0000521TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
522 if (clientOrServerSingleThreaded()) {
523 GTEST_SKIP() << "This test requires multiple threads";
524 }
525
Yifan Hong1f44f982021-10-08 17:16:47 -0700526 constexpr size_t kNumThreads = 20;
527 constexpr size_t kNumOutgoingConnections = 10;
528 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
529 auto proc = createRpcTestSocketServerProcess(
530 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000531
Steven Moreland68e2ee22024-09-18 01:18:48 +0000532 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 200 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000533}
534
Andrei Homescua858b0e2022-08-01 23:43:09 +0000535TEST_P(BinderRpc, ThreadingStressTest) {
536 if (clientOrServerSingleThreaded()) {
537 GTEST_SKIP() << "This test requires multiple threads";
538 }
539
Steven Moreland27f620a2023-03-06 19:44:36 +0000540 constexpr size_t kNumClientThreads = 5;
541 constexpr size_t kNumServerThreads = 5;
542 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000543
Steven Moreland4313d7e2021-07-15 23:41:22 +0000544 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000545
546 std::vector<std::thread> threads;
547 for (size_t i = 0; i < kNumClientThreads; i++) {
548 threads.push_back(std::thread([&] {
549 for (size_t j = 0; j < kNumCalls; j++) {
550 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000551 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000552 EXPECT_EQ(proc.rootBinder, out);
553 }
554 }));
555 }
556
557 for (auto& t : threads) t.join();
558}
559
Steven Moreland925ba0a2021-09-17 18:06:32 -0700560static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
561 std::vector<std::thread> threads;
562 for (size_t i = 0; i < threadCount; i++) {
563 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
564 }
565 for (auto& t : threads) t.join();
566}
567
Andrei Homescua858b0e2022-08-01 23:43:09 +0000568TEST_P(BinderRpc, OnewayStressTest) {
569 if (clientOrServerSingleThreaded()) {
570 GTEST_SKIP() << "This test requires multiple threads";
571 }
572
Steven Morelandc6046982021-04-20 00:49:42 +0000573 constexpr size_t kNumClientThreads = 10;
574 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700575 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000576
Steven Moreland4313d7e2021-07-15 23:41:22 +0000577 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000578
579 std::vector<std::thread> threads;
580 for (size_t i = 0; i < kNumClientThreads; i++) {
581 threads.push_back(std::thread([&] {
582 for (size_t j = 0; j < kNumCalls; j++) {
583 EXPECT_OK(proc.rootIface->sendString("a"));
584 }
Steven Morelandc6046982021-04-20 00:49:42 +0000585 }));
586 }
587
588 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700589
590 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000591}
592
Frederick Mayleb0221d12022-10-03 23:10:53 +0000593TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
594 if (!supportsFdTransport()) {
595 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
596 }
597 if (clientOrServerSingleThreaded()) {
598 GTEST_SKIP() << "This test requires multiple threads";
599 }
600
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000601 constexpr size_t kNumServerThreads = 3;
602
Frederick Mayleb0221d12022-10-03 23:10:53 +0000603 // This test forces a oneway transaction to be queued by issuing two
604 // `blockingSendFdOneway` calls, then drains the queue by issuing two
605 // `blockingRecvFd` calls.
606 //
607 // For more details about the queuing semantics see
608 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
609
610 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000611 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000612 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
613 .serverSupportedFileDescriptorTransportModes =
614 {RpcSession::FileDescriptorTransportMode::UNIX},
615 });
616
617 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
618 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
619 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
620 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
621
622 android::os::ParcelFileDescriptor fdA;
623 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
624 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700625 ASSERT_TRUE(ReadFdToString(fdA.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000626 EXPECT_EQ(result, "a");
627
628 android::os::ParcelFileDescriptor fdB;
629 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700630 ASSERT_TRUE(ReadFdToString(fdB.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000631 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000632
633 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000634}
635
Andrei Homescua858b0e2022-08-01 23:43:09 +0000636TEST_P(BinderRpc, OnewayCallQueueing) {
637 if (clientOrServerSingleThreaded()) {
638 GTEST_SKIP() << "This test requires multiple threads";
639 }
640
Frederick Mayle96872592023-03-07 14:56:15 -0800641 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000642 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000643
644 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000645 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000646
Frederick Mayle96872592023-03-07 14:56:15 -0800647 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700648 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800649 for (size_t i = 0; i + 1 < kNumQueued; i++) {
650 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000651 }
Frederick Mayle96872592023-03-07 14:56:15 -0800652 for (size_t i = 0; i + 1 < kNumQueued; i++) {
653 int n;
654 proc.rootIface->blockingRecvInt(&n);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700655 EXPECT_EQ(n, static_cast<ssize_t>(i));
Frederick Mayle96872592023-03-07 14:56:15 -0800656 }
Steven Morelandf5174272021-05-25 00:39:28 +0000657
Steven Moreland925ba0a2021-09-17 18:06:32 -0700658 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000659}
660
Andrei Homescua858b0e2022-08-01 23:43:09 +0000661TEST_P(BinderRpc, OnewayCallExhaustion) {
662 if (clientOrServerSingleThreaded()) {
663 GTEST_SKIP() << "This test requires multiple threads";
664 }
665
Steven Morelandd45be622021-06-04 02:19:37 +0000666 constexpr size_t kNumClients = 2;
667 constexpr size_t kTooLongMs = 1000;
668
Steven Moreland4313d7e2021-07-15 23:41:22 +0000669 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000670
671 // Build up oneway calls on the second session to make sure it terminates
672 // and shuts down. The first session should be unaffected (proc destructor
673 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000674 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000675
676 std::vector<std::thread> threads;
677 for (size_t i = 0; i < kNumClients; i++) {
678 // one of these threads will get stuck queueing a transaction once the
679 // socket fills up, the other will be able to fill up transactions on
680 // this object
681 threads.push_back(std::thread([&] {
682 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
683 }
684 }));
685 }
686 for (auto& t : threads) t.join();
687
688 Status status = iface->sleepMsAsync(kTooLongMs);
689 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
690
Steven Moreland798e0d12021-07-14 23:19:25 +0000691 // now that it has died, wait for the remote session to shutdown
692 std::vector<int32_t> remoteCounts;
693 do {
694 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
695 } while (remoteCounts.size() == kNumClients);
696
Steven Morelandd45be622021-06-04 02:19:37 +0000697 // the second session should be shutdown in the other process by the time we
698 // are able to join above (it'll only be hung up once it finishes processing
699 // any pending commands). We need to erase this session from the record
700 // here, so that the destructor for our session won't check that this
701 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000702 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000703}
704
Steven Moreland67f85902023-03-15 01:13:49 +0000705TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
706 if (clientOrServerSingleThreaded()) {
707 GTEST_SKIP() << "This test requires multiple threads";
708 }
709
710 // session 0 - will check for leaks in destrutor of proc
711 // session 1 - we want to make sure it gets deleted when we drop all references to it
712 auto proc = createRpcTestSocketServerProcess(
Tomasz Wasilczyk5da65602023-06-29 10:12:50 -0700713 {.numThreads = 1, .numSessions = 2, .numIncomingConnectionsBySession = {0, 1}});
Steven Moreland67f85902023-03-15 01:13:49 +0000714
715 wp<RpcSession> session = proc.proc->sessions.at(1).session;
716
717 // remove all references to the second session
718 proc.proc->sessions.at(1).root = nullptr;
719 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
720
721 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
722 // to drain commands.
723 for (size_t i = 0; i < 100; i++) {
724 usleep(10 * 1000);
725 if (session.promote() == nullptr) break;
726 }
727
728 EXPECT_EQ(nullptr, session.promote());
Steven Morelandb5d2b642023-05-04 00:31:45 +0000729
Steven Moreland0ebdaad2023-06-14 19:33:37 +0000730 // now that it has died, wait for the remote session to shutdown
731 std::vector<int32_t> remoteCounts;
732 do {
733 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
734 } while (remoteCounts.size() > 1);
Steven Moreland67f85902023-03-15 01:13:49 +0000735}
736
Devin Moore66d5b7a2022-07-07 21:42:10 +0000737TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000738 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000739 GTEST_SKIP() << "This test requires multiple threads";
740 }
741 class MyDeathRec : public IBinder::DeathRecipient {
742 public:
743 void binderDied(const wp<IBinder>& /* who */) override {
744 dead = true;
745 mCv.notify_one();
746 }
747 std::mutex mMtx;
748 std::condition_variable mCv;
749 bool dead = false;
750 };
751
752 // Death recipient needs to have an incoming connection to be called
753 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000754 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000755
756 auto dr = sp<MyDeathRec>::make();
757 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
758
759 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
760 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
761 }
762
763 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000764 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000765
766 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000767 // can't do this before checking the death recipient by calling
768 // forceShutdown earlier, because shutdownAndWait will also trigger
769 // a death recipient, but if we had a way to wait for the service
770 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000771 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000772 proc.expectAlreadyShutdown = true;
773}
774
775TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000776 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000777 GTEST_SKIP() << "This test requires multiple threads";
778 }
779 class MyDeathRec : public IBinder::DeathRecipient {
780 public:
781 void binderDied(const wp<IBinder>& /* who */) override {
782 dead = true;
783 mCv.notify_one();
784 }
785 std::mutex mMtx;
786 std::condition_variable mCv;
787 bool dead = false;
788 };
789
790 // Death recipient needs to have an incoming connection to be called
791 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000792 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000793
794 auto dr = sp<MyDeathRec>::make();
795 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
796
797 // Explicitly calling shutDownAndWait will cause the death recipients
798 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000799 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000800
801 std::unique_lock<std::mutex> lock(dr->mMtx);
802 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000803 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000804 }
805 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
806
Andrei Homescu96834632022-10-14 00:49:49 +0000807 proc.proc->terminate();
808 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000809 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
810 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
811 });
812 proc.expectAlreadyShutdown = true;
813}
814
Steven Moreland5ec743f2023-01-18 01:02:06 +0000815TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000816 if (socketType() == SocketType::TIPC) {
817 // This should work, but Trusty takes too long to restart the service
818 GTEST_SKIP() << "Service death test not supported on Trusty";
819 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000820 class MyDeathRec : public IBinder::DeathRecipient {
821 public:
822 void binderDied(const wp<IBinder>& /* who */) override {}
823 };
824
Steven Moreland67f85902023-03-15 01:13:49 +0000825 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000826
827 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000828 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000829}
830
831TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000832 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000833 GTEST_SKIP() << "This test requires multiple threads";
834 }
835 class MyDeathRec : public IBinder::DeathRecipient {
836 public:
837 void binderDied(const wp<IBinder>& /* who */) override {
838 GTEST_FAIL() << "This should not be called after unlinkToDeath";
839 }
840 };
841
842 // Death recipient needs to have an incoming connection to be called
843 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000844 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000845
846 auto dr = sp<MyDeathRec>::make();
847 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
848 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
849
Steven Moreland67f85902023-03-15 01:13:49 +0000850 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000851}
852
Steven Morelandc1635952021-04-01 16:20:47 +0000853TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000854 if (socketType() == SocketType::TIPC) {
855 // This should work, but Trusty takes too long to restart the service
856 GTEST_SKIP() << "Service death test not supported on Trusty";
857 }
858
Steven Moreland5553ac42020-11-11 02:14:45 +0000859 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000860 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000861
862 // make sure there is some state during crash
863 // 1. we hold their binder
864 sp<IBinderRpcSession> session;
865 EXPECT_OK(proc.rootIface->openSession("happy", &session));
866 // 2. they hold our binder
867 sp<IBinder> binder = new BBinder();
868 EXPECT_OK(proc.rootIface->holdBinder(binder));
869
870 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
871 << "Do death cleanup: " << doDeathCleanup;
872
Andrei Homescu96834632022-10-14 00:49:49 +0000873 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000874 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
875 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
876 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000877 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000878 }
879}
880
Steven Morelandd7302072021-05-15 01:32:04 +0000881TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000882 // This test only works if the current process shared the internal state of
883 // ProcessState with the service across the call to fork(). Both the static
884 // libraries and libbinder.so have their own separate copies of all the
885 // globals, so the test only works when the test client and service both use
886 // libbinder.so (when using static libraries, even a client and service
887 // using the same kind of static library should have separate copies of the
888 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000889 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000890 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
891 "at build time.";
892 }
893
Steven Moreland4313d7e2021-07-15 23:41:22 +0000894 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000895
Andrei Homescu2a298012022-06-15 01:08:54 +0000896 // we can't allocate IPCThreadState so actually the first time should
897 // succeed :(
898 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000899
900 // second time! we catch the error :)
901 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
902
Andrei Homescu96834632022-10-14 00:49:49 +0000903 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000904 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
905 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
906 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000907 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000908}
909
Frederick Mayle69a0c992022-05-26 20:38:39 +0000910TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000911 if (socketType() == SocketType::TIPC) {
912 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
913 }
914
Frederick Mayle69a0c992022-05-26 20:38:39 +0000915 auto proc = createRpcTestSocketServerProcess({
916 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
917 .serverSupportedFileDescriptorTransportModes =
918 {RpcSession::FileDescriptorTransportMode::UNIX},
919 .allowConnectFailure = true,
920 });
Andrei Homescu96834632022-10-14 00:49:49 +0000921 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
922 proc.proc->terminate();
923 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000924 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
925 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
926 });
927 proc.expectAlreadyShutdown = true;
928}
929
930TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000931 if (socketType() == SocketType::TIPC) {
932 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
933 }
934
Frederick Mayle69a0c992022-05-26 20:38:39 +0000935 auto proc = createRpcTestSocketServerProcess({
936 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
937 .serverSupportedFileDescriptorTransportModes =
938 {RpcSession::FileDescriptorTransportMode::NONE},
939 .allowConnectFailure = true,
940 });
Andrei Homescu96834632022-10-14 00:49:49 +0000941 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
942 proc.proc->terminate();
943 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000944 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
945 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
946 });
947 proc.expectAlreadyShutdown = true;
948}
949
950TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000951 if (socketType() == SocketType::TIPC) {
952 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
953 }
954
Frederick Mayle69a0c992022-05-26 20:38:39 +0000955 auto proc = createRpcTestSocketServerProcess({
956 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
957 .serverSupportedFileDescriptorTransportModes =
958 {RpcSession::FileDescriptorTransportMode::NONE,
959 RpcSession::FileDescriptorTransportMode::UNIX},
960 });
961
962 android::os::ParcelFileDescriptor out;
963 auto status = proc.rootIface->echoAsFile("hello", &out);
964 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
965}
966
967TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000968 if (socketType() == SocketType::TIPC) {
969 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
970 }
971
Frederick Mayle69a0c992022-05-26 20:38:39 +0000972 auto proc = createRpcTestSocketServerProcess({
973 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
974 .serverSupportedFileDescriptorTransportModes =
975 {RpcSession::FileDescriptorTransportMode::UNIX},
976 });
977
978 android::os::ParcelFileDescriptor out;
979 auto status = proc.rootIface->echoAsFile("hello", &out);
980 if (!supportsFdTransport()) {
981 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
982 return;
983 }
984 ASSERT_TRUE(status.isOk()) << status;
985
986 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700987 ASSERT_TRUE(ReadFdToString(out.get(), &result));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700988 ASSERT_EQ(result, "hello");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000989}
990
991TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000992 if (socketType() == SocketType::TIPC) {
993 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
994 }
995
Frederick Mayle69a0c992022-05-26 20:38:39 +0000996 auto proc = createRpcTestSocketServerProcess({
997 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
998 .serverSupportedFileDescriptorTransportModes =
999 {RpcSession::FileDescriptorTransportMode::UNIX},
1000 });
1001
1002 std::vector<android::os::ParcelFileDescriptor> files;
1003 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1004 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1005 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1006 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1007
1008 android::os::ParcelFileDescriptor out;
1009 auto status = proc.rootIface->concatFiles(files, &out);
1010 if (!supportsFdTransport()) {
1011 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1012 return;
1013 }
1014 ASSERT_TRUE(status.isOk()) << status;
1015
1016 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -07001017 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001018 EXPECT_EQ(result, "123abcd");
1019}
1020
1021TEST_P(BinderRpc, SendMaxFiles) {
1022 if (!supportsFdTransport()) {
1023 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1024 }
1025
1026 auto proc = createRpcTestSocketServerProcess({
1027 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1028 .serverSupportedFileDescriptorTransportModes =
1029 {RpcSession::FileDescriptorTransportMode::UNIX},
1030 });
1031
1032 std::vector<android::os::ParcelFileDescriptor> files;
1033 for (int i = 0; i < 253; i++) {
1034 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1035 }
1036
1037 android::os::ParcelFileDescriptor out;
1038 auto status = proc.rootIface->concatFiles(files, &out);
1039 ASSERT_TRUE(status.isOk()) << status;
1040
1041 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -07001042 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001043 EXPECT_EQ(result, std::string(253, 'a'));
1044}
1045
1046TEST_P(BinderRpc, SendTooManyFiles) {
1047 if (!supportsFdTransport()) {
1048 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1049 }
1050
1051 auto proc = createRpcTestSocketServerProcess({
1052 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1053 .serverSupportedFileDescriptorTransportModes =
1054 {RpcSession::FileDescriptorTransportMode::UNIX},
1055 });
1056
1057 std::vector<android::os::ParcelFileDescriptor> files;
1058 for (int i = 0; i < 254; i++) {
1059 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1060 }
1061
1062 android::os::ParcelFileDescriptor out;
1063 auto status = proc.rootIface->concatFiles(files, &out);
1064 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1065}
1066
Andrei Homescufc221502022-10-08 03:51:17 +00001067TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001068 if (socketType() == SocketType::TIPC) {
1069 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1070 }
1071
Andrei Homescufc221502022-10-08 03:51:17 +00001072 auto proc = createRpcTestSocketServerProcess({
1073 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1074 .serverSupportedFileDescriptorTransportModes =
1075 {RpcSession::FileDescriptorTransportMode::UNIX},
1076 });
1077
1078 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1079 ASSERT_NE(badFd, -1);
1080
1081 // Close the file descriptor so it becomes invalid for dup
1082 close(badFd);
1083
1084 Parcel p1;
1085 p1.markForBinder(proc.rootBinder);
1086 p1.writeInt32(3);
1087 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1088
1089 Parcel pRaw;
1090 pRaw.markForBinder(proc.rootBinder);
1091 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1092
1093 pRaw.setDataPosition(0);
1094 EXPECT_EQ(3, pRaw.readInt32());
1095 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1096}
1097
Andrei Homescu68a55612022-08-02 01:25:15 +00001098#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001099TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001100 if constexpr (!kEnableSharedLibs) {
1101 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1102 }
1103
Steven Moreland4313d7e2021-07-15 23:41:22 +00001104 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001105
1106 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1107 ASSERT_NE(binder, nullptr);
1108
1109 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1110}
1111
1112TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001113 if constexpr (!kEnableSharedLibs) {
1114 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1115 }
1116
Steven Moreland4313d7e2021-07-15 23:41:22 +00001117 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001118
1119 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1120 ASSERT_NE(binder, nullptr);
1121
1122 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1123 ASSERT_NE(ndkBinder, nullptr);
1124
1125 std::string out;
1126 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1127 ASSERT_TRUE(status.isOk()) << status.getDescription();
1128 ASSERT_EQ("aoeuaoeu", out);
1129}
Andrei Homescu68a55612022-08-02 01:25:15 +00001130#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001131
Steven Moreland5553ac42020-11-11 02:14:45 +00001132ssize_t countFds() {
1133 DIR* dir = opendir("/proc/self/fd/");
1134 if (dir == nullptr) return -1;
1135 ssize_t ret = 0;
1136 dirent* ent;
1137 while ((ent = readdir(dir)) != nullptr) ret++;
1138 closedir(dir);
1139 return ret;
1140}
1141
Andrei Homescua858b0e2022-08-01 23:43:09 +00001142TEST_P(BinderRpc, Fds) {
1143 if (serverSingleThreaded()) {
1144 GTEST_SKIP() << "This test requires multiple threads";
1145 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001146 if (socketType() == SocketType::TIPC) {
1147 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1148 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001149
Steven Moreland5553ac42020-11-11 02:14:45 +00001150 ssize_t beforeFds = countFds();
1151 ASSERT_GE(beforeFds, 0);
1152 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001153 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001154 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1155 }
1156 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1157}
1158
Devin Moore18f63752024-08-08 21:01:24 +00001159// TODO need to add IServiceManager.cpp/.h to libbinder_no_kernel
1160#ifdef BINDER_WITH_KERNEL_IPC
1161
1162class BinderRpcAccessor : public BinderRpc {
1163 void SetUp() override {
1164 if (serverSingleThreaded()) {
1165 // This blocks on android::FdTrigger::triggerablePoll when attempting to set
1166 // up the client RpcSession
1167 GTEST_SKIP() << "Accessors are not supported for single threaded libbinder";
1168 }
1169 if (rpcSecurity() == RpcSecurity::TLS) {
1170 GTEST_SKIP() << "Accessors are not supported with TLS";
1171 // ... for now
1172 }
1173
1174 if (socketType() == SocketType::UNIX_BOOTSTRAP) {
1175 GTEST_SKIP() << "Accessors do not support UNIX_BOOTSTRAP because no connection "
1176 "information is known";
1177 }
1178 if (socketType() == SocketType::TIPC) {
1179 GTEST_SKIP() << "Accessors do not support TIPC because the socket transport is not "
1180 "known in libbinder";
1181 }
1182 BinderRpc::SetUp();
1183 }
1184};
1185
1186inline void waitForExtraSessionCleanup(const BinderRpcTestProcessSession& proc) {
1187 // Need to give the server some time to delete its RpcSession after our last
1188 // reference is dropped, closing the connection. Check for up to 1 second,
1189 // every 10 ms.
1190 for (size_t i = 0; i < 100; i++) {
1191 std::vector<int32_t> remoteCounts;
1192 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1193 // We exect the original binder to still be alive, we just want to wait
1194 // for this extra session to be cleaned up.
1195 if (remoteCounts.size() == proc.proc->sessions.size()) break;
1196 usleep(10000);
1197 }
1198}
1199
1200TEST_P(BinderRpcAccessor, InjectAndGetServiceHappyPath) {
1201 constexpr size_t kNumThreads = 10;
1202 const String16 kInstanceName("super.cool.service/better_than_default");
1203
1204 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1205 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1206
1207 auto receipt = addAccessorProvider([&](const String16& name) -> sp<IBinder> {
1208 return createAccessor(name,
1209 [&](const String16& name, sockaddr* outAddr,
1210 socklen_t addrSize) -> status_t {
1211 if (outAddr == nullptr ||
1212 addrSize < proc.proc->sessions[0].addrLen) {
1213 return BAD_VALUE;
1214 }
1215 if (name == kInstanceName) {
1216 if (proc.proc->sessions[0].addr.ss_family == AF_UNIX) {
1217 sockaddr_un* un = reinterpret_cast<sockaddr_un*>(
1218 &proc.proc->sessions[0].addr);
1219 ALOGE("inside callback: %s", un->sun_path);
1220 }
1221 std::memcpy(outAddr, &proc.proc->sessions[0].addr,
1222 proc.proc->sessions[0].addrLen);
1223 return OK;
1224 }
1225 return NAME_NOT_FOUND;
1226 });
1227 });
1228
1229 EXPECT_FALSE(receipt.expired());
1230
1231 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1232 sp<IBinderRpcTest> service = checked_interface_cast<IBinderRpcTest>(binder);
1233 EXPECT_NE(service, nullptr);
1234
1235 sp<IBinder> out;
1236 EXPECT_OK(service->repeatBinder(binder, &out));
1237 EXPECT_EQ(binder, out);
1238
1239 out.clear();
1240 binder.clear();
1241 service.clear();
1242
1243 status_t status = removeAccessorProvider(receipt);
1244 EXPECT_EQ(status, OK);
1245
1246 waitForExtraSessionCleanup(proc);
1247}
1248
1249TEST_P(BinderRpcAccessor, InjectNoAccessorProvided) {
1250 const String16 kInstanceName("doesnt_matter_nothing_checks");
1251
1252 bool isProviderDeleted = false;
1253
1254 auto receipt = addAccessorProvider([&](const String16&) -> sp<IBinder> { return nullptr; });
1255 EXPECT_FALSE(receipt.expired());
1256
1257 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1258 EXPECT_EQ(binder, nullptr);
1259
1260 status_t status = removeAccessorProvider(receipt);
1261 EXPECT_EQ(status, OK);
1262}
1263
1264TEST_P(BinderRpcAccessor, InjectNoSockaddrProvided) {
1265 constexpr size_t kNumThreads = 10;
1266 const String16 kInstanceName("super.cool.service/better_than_default");
1267
1268 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1269 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1270
1271 bool isProviderDeleted = false;
1272 bool isAccessorDeleted = false;
1273
1274 auto receipt = addAccessorProvider([&](const String16& name) -> sp<IBinder> {
1275 return createAccessor(name, [&](const String16&, sockaddr*, socklen_t) -> status_t {
1276 // don't fill in outAddr
1277 return NAME_NOT_FOUND;
1278 });
1279 });
1280
1281 EXPECT_FALSE(receipt.expired());
1282
1283 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1284 EXPECT_EQ(binder, nullptr);
1285
1286 status_t status = removeAccessorProvider(receipt);
1287 EXPECT_EQ(status, OK);
1288}
1289
1290#endif // BINDER_WITH_KERNEL_IPC
1291
Andrei Homescud65666d2023-03-03 07:28:02 +00001292#ifdef BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandb469f432023-07-28 22:13:47 +00001293
1294static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() {
1295 std::vector<BinderRpc::ParamType> ret;
1296
1297 for (const auto& clientVersion : testVersions()) {
1298 for (const auto& serverVersion : testVersions()) {
1299 ret.push_back(BinderRpc::ParamType{
1300 .type = SocketType::TIPC,
1301 .security = RpcSecurity::RAW,
1302 .clientVersion = clientVersion,
1303 .serverVersion = serverVersion,
1304 .singleThreaded = true,
1305 .noKernel = true,
1306 });
1307 }
1308 }
1309
1310 return ret;
1311}
1312
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001313INSTANTIATE_TEST_SUITE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()),
1314 BinderRpc::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00001315#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Moreland9f250b02023-05-16 23:27:42 +00001316bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001317 // We don't need to enable TLS to know if vsock is supported.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001318 unique_fd serverFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001319 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Morelanda27311b2023-04-11 22:13:35 +00001320
1321 if (errno == EAFNOSUPPORT) {
1322 return false;
1323 }
1324
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -08001325 LOG_ALWAYS_FATAL_IF(!serverFd.ok(), "Could not create socket: %s", strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001326
1327 sockaddr_vm serverAddr{
1328 .svm_family = AF_VSOCK,
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001329 .svm_port = VMADDR_PORT_ANY,
Andrei Homescu992a4052022-06-28 21:26:18 +00001330 .svm_cid = VMADDR_CID_ANY,
1331 };
1332 int ret = TEMP_FAILURE_RETRY(
1333 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001334 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port VMADDR_PORT_ANY: %s",
Andrei Homescu992a4052022-06-28 21:26:18 +00001335 strerror(errno));
1336
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001337 socklen_t len = sizeof(serverAddr);
1338 ret = getsockname(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), &len);
1339 LOG_ALWAYS_FATAL_IF(0 != ret, "Failed to getsockname: %s", strerror(errno));
Hannah.Hsu6b1036f2024-07-09 11:20:20 +08001340 LOG_ALWAYS_FATAL_IF(len < static_cast<socklen_t>(sizeof(serverAddr)),
1341 "getsockname didn't read the full addr struct");
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001342
Andrei Homescu992a4052022-06-28 21:26:18 +00001343 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001344 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", serverAddr.svm_port,
Andrei Homescu992a4052022-06-28 21:26:18 +00001345 strerror(errno));
1346
1347 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1348 // to see if the kernel supports it. It's safe to use a blocking
1349 // connect because vsock sockets have a 2 second connection timeout,
1350 // and they return ETIMEDOUT after that.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001351 unique_fd connectFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001352 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001353 LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s",
1354 serverAddr.svm_port, strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001355
1356 bool success = false;
1357 sockaddr_vm connectAddr{
1358 .svm_family = AF_VSOCK,
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001359 .svm_port = serverAddr.svm_port,
Andrei Homescu992a4052022-06-28 21:26:18 +00001360 .svm_cid = VMADDR_CID_LOCAL,
1361 };
1362 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1363 sizeof(connectAddr)));
1364 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001365 unique_fd acceptFd;
Andrei Homescu992a4052022-06-28 21:26:18 +00001366 while (true) {
1367 pollfd pfd[]{
1368 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1369 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1370 };
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -08001371 ret = TEMP_FAILURE_RETRY(poll(pfd, countof(pfd), -1));
Andrei Homescu992a4052022-06-28 21:26:18 +00001372 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1373
1374 if (pfd[0].revents & POLLIN) {
1375 sockaddr_vm acceptAddr;
1376 socklen_t acceptAddrLen = sizeof(acceptAddr);
1377 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1378 reinterpret_cast<sockaddr*>(&acceptAddr),
1379 &acceptAddrLen, SOCK_CLOEXEC));
1380 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1381 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1382 "Truncated address");
1383
1384 // Store the fd in acceptFd so we keep the connection alive
1385 // while polling connectFd
1386 acceptFd.reset(ret);
1387 }
1388
1389 if (pfd[1].revents & POLLOUT) {
1390 // Connect either succeeded or timed out
1391 int connectErrno;
1392 socklen_t connectErrnoLen = sizeof(connectErrno);
1393 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1394 &connectErrnoLen);
1395 LOG_ALWAYS_FATAL_IF(ret == -1,
1396 "Could not getsockopt() after connect() "
1397 "on non-blocking socket: %s.",
1398 strerror(errno));
1399
1400 // We're done, this is all we wanted
1401 success = connectErrno == 0;
1402 break;
1403 }
1404 }
1405 } else {
1406 success = ret == 0;
1407 }
1408
1409 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1410
1411 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001412}
1413
Yifan Hong1deca4b2021-09-10 16:16:44 -07001414static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001415 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1416 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001417
1418 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001419
Steven Moreland9f250b02023-05-16 23:27:42 +00001420#ifdef __BIONIC__
1421 // Devices may not have vsock support. AVF tests will verify whether they do, but
1422 // we can't require it due to old kernels for the time being.
Steven Morelandda573042021-06-12 01:13:45 +00001423 static bool hasVsockLoopback = testSupportVsockLoopback();
Steven Moreland9f250b02023-05-16 23:27:42 +00001424#else
1425 // On host machines, we always assume we have vsock loopback. If we don't, the
1426 // subsequent failures will be more clear than showing one now.
1427 static bool hasVsockLoopback = true;
1428#endif
Steven Morelandda573042021-06-12 01:13:45 +00001429
1430 if (hasVsockLoopback) {
1431 ret.push_back(SocketType::VSOCK);
1432 }
1433
1434 return ret;
1435}
1436
Steven Morelandb469f432023-07-28 22:13:47 +00001437static std::vector<BinderRpc::ParamType> getBinderRpcParams() {
1438 std::vector<BinderRpc::ParamType> ret;
1439
Steven Morelandf7421432023-07-28 22:41:44 +00001440 constexpr bool full = false;
1441
Steven Morelandb469f432023-07-28 22:13:47 +00001442 for (const auto& type : testSocketTypes()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001443 if (full || type == SocketType::UNIX) {
1444 for (const auto& security : RpcSecurityValues()) {
1445 for (const auto& clientVersion : testVersions()) {
1446 for (const auto& serverVersion : testVersions()) {
1447 for (bool singleThreaded : {false, true}) {
Tomasz Wasilczyk2265ad92024-05-01 12:54:46 -07001448 for (bool noKernel : noKernelValues()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001449 ret.push_back(BinderRpc::ParamType{
1450 .type = type,
1451 .security = security,
1452 .clientVersion = clientVersion,
1453 .serverVersion = serverVersion,
1454 .singleThreaded = singleThreaded,
1455 .noKernel = noKernel,
1456 });
1457 }
Steven Morelandb469f432023-07-28 22:13:47 +00001458 }
1459 }
1460 }
1461 }
Steven Morelandf7421432023-07-28 22:41:44 +00001462 } else {
1463 ret.push_back(BinderRpc::ParamType{
1464 .type = type,
1465 .security = RpcSecurity::RAW,
1466 .clientVersion = RPC_WIRE_PROTOCOL_VERSION,
1467 .serverVersion = RPC_WIRE_PROTOCOL_VERSION,
1468 .singleThreaded = false,
Tomasz Wasilczyk2265ad92024-05-01 12:54:46 -07001469 .noKernel = !kEnableKernelIpcTesting,
Steven Morelandf7421432023-07-28 22:41:44 +00001470 });
Steven Morelandb469f432023-07-28 22:13:47 +00001471 }
1472 }
Steven Morelandf7421432023-07-28 22:41:44 +00001473
Steven Morelandb469f432023-07-28 22:13:47 +00001474 return ret;
1475}
1476
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001477INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()),
1478 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001479
Devin Moore18f63752024-08-08 21:01:24 +00001480#ifdef BINDER_WITH_KERNEL_IPC
1481INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpcAccessor, ::testing::ValuesIn(getBinderRpcParams()),
1482 BinderRpc::PrintParamInfo);
1483#endif // BINDER_WITH_KERNEL_IPC
1484
Yifan Hong702115c2021-06-24 15:39:18 -07001485class BinderRpcServerRootObject
1486 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001487
1488TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1489 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1490 auto setRootObject = [](bool isStrong) -> SetFn {
1491 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1492 };
1493
Yifan Hong702115c2021-06-24 15:39:18 -07001494 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001495 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001496 auto binder1 = sp<BBinder>::make();
1497 IBinder* binderRaw1 = binder1.get();
1498 setRootObject(isStrong1)(server.get(), binder1);
1499 EXPECT_EQ(binderRaw1, server->getRootObject());
1500 binder1.clear();
1501 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1502
1503 auto binder2 = sp<BBinder>::make();
1504 IBinder* binderRaw2 = binder2.get();
1505 setRootObject(isStrong2)(server.get(), binder2);
1506 EXPECT_EQ(binderRaw2, server->getRootObject());
1507 binder2.clear();
1508 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1509}
1510
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001511INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerRootObject,
1512 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1513 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001514
Yifan Hong1a235852021-05-13 16:07:47 -07001515class OneOffSignal {
1516public:
1517 // If notify() was previously called, or is called within |duration|, return true; else false.
1518 template <typename R, typename P>
1519 bool wait(std::chrono::duration<R, P> duration) {
1520 std::unique_lock<std::mutex> lock(mMutex);
1521 return mCv.wait_for(lock, duration, [this] { return mValue; });
1522 }
1523 void notify() {
1524 std::unique_lock<std::mutex> lock(mMutex);
1525 mValue = true;
1526 lock.unlock();
1527 mCv.notify_all();
1528 }
1529
1530private:
1531 std::mutex mMutex;
1532 std::condition_variable mCv;
1533 bool mValue = false;
1534};
1535
Yifan Hong194acf22021-06-29 18:44:56 -07001536TEST(BinderRpc, Java) {
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001537 bool expectDebuggable = false;
1538#if defined(__ANDROID__)
1539 expectDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1540 android::base::GetProperty("ro.build.type", "") != "user";
1541#else
Yifan Hong194acf22021-06-29 18:44:56 -07001542 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1543 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1544 "to binderHostDeviceTest. Hence, just disable this test on host.";
1545#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001546 if constexpr (!kEnableKernelIpc) {
1547 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1548 "at build time.";
1549 }
1550
Yifan Hong194acf22021-06-29 18:44:56 -07001551 sp<IServiceManager> sm = defaultServiceManager();
1552 ASSERT_NE(nullptr, sm);
1553 // Any Java service with non-empty getInterfaceDescriptor() would do.
Devin Moore29db8602024-08-14 22:21:04 +00001554 // Let's pick activity.
1555 auto binder = sm->checkService(String16("activity"));
Yifan Hong194acf22021-06-29 18:44:56 -07001556 ASSERT_NE(nullptr, binder);
1557 auto descriptor = binder->getInterfaceDescriptor();
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001558 ASSERT_GE(descriptor.size(), 0u);
Yifan Hong194acf22021-06-29 18:44:56 -07001559 ASSERT_EQ(OK, binder->pingBinder());
1560
1561 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001562 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001563 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001564 auto socket = rpcServer->releaseServer();
1565
1566 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001567 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1568
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001569 if (!expectDebuggable) {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001570 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001571 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1572 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001573 << statusToString(setRpcClientDebugStatus);
1574 GTEST_SKIP();
1575 }
1576
1577 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001578
1579 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001580 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001581 auto rpcBinder = rpcSession->getRootObject();
1582 ASSERT_NE(nullptr, rpcBinder);
1583
1584 ASSERT_EQ(OK, rpcBinder->pingBinder());
1585
1586 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1587 << "getInterfaceDescriptor should not crash system_server";
1588 ASSERT_EQ(OK, rpcBinder->pingBinder());
1589}
1590
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001591class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1592public:
1593 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001594 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001595 std::to_string(std::get<1>(info.param));
1596 }
1597};
1598
1599TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001600 unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001601 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001602 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001603 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001604 ASSERT_FALSE(server->hasServer());
1605 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1606 ASSERT_TRUE(server->hasServer());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001607 unique_fd retrieved = server->releaseServer();
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001608 ASSERT_FALSE(server->hasServer());
1609 ASSERT_EQ(sinkFd, retrieved.get());
1610}
1611
1612TEST_P(BinderRpcServerOnly, Shutdown) {
1613 if constexpr (!kEnableRpcThreads) {
1614 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1615 }
1616
1617 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001618 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001619 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001620 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1621 auto joinEnds = std::make_shared<OneOffSignal>();
1622
1623 // If things are broken and the thread never stops, don't block other tests. Because the thread
1624 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1625 // shared pointers are passed.
1626 std::thread([server, joinEnds] {
1627 server->join();
1628 joinEnds->notify();
1629 }).detach();
1630
1631 bool shutdown = false;
1632 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001633 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001634 if (server->shutdown()) shutdown = true;
1635 }
1636 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1637
1638 ASSERT_TRUE(joinEnds->wait(2s))
1639 << "After server->shutdown() returns true, join() did not stop after 2s";
1640}
1641
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001642INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerOnly,
1643 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1644 ::testing::ValuesIn(testVersions())),
1645 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001646
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001647class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001648public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001649 // Only parameterized only server version because `RpcSession` is bypassed
1650 // in the client half of the tests.
1651 using Param =
1652 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001653 using ConnectToServer = std::function<unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001654
1655 // A server that handles client socket connections.
1656 class Server {
1657 public:
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001658 using AcceptConnection = std::function<unique_fd(Server*)>;
David Brazdil21c887c2022-09-23 12:25:18 +01001659
Yifan Hong1deca4b2021-09-10 16:16:44 -07001660 explicit Server() {}
1661 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001662 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001663 [[nodiscard]] AssertionResult setUp(
1664 const Param& param,
1665 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001666 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001667 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Steven Morelandca3f6382023-05-11 23:23:26 +00001668 if (!rpcServer->setProtocolVersion(serverVersion)) {
1669 return AssertionFailure() << "Invalid protocol version: " << serverVersion;
1670 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001671 switch (socketType) {
1672 case SocketType::PRECONNECTED: {
1673 return AssertionFailure() << "Not supported by this test";
1674 } break;
1675 case SocketType::UNIX: {
1676 auto addr = allocateSocketAddress();
1677 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1678 if (status != OK) {
1679 return AssertionFailure()
1680 << "setupUnixDomainServer: " << statusToString(status);
1681 }
1682 mConnectToServer = [addr] {
1683 return connectTo(UnixSocketAddress(addr.c_str()));
1684 };
1685 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001686 case SocketType::UNIX_BOOTSTRAP: {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001687 unique_fd bootstrapFdClient, bootstrapFdServer;
1688 if (!binder::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001689 return AssertionFailure() << "Socketpair() failed";
1690 }
1691 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1692 std::move(bootstrapFdServer));
1693 if (status != OK) {
1694 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1695 << statusToString(status);
1696 }
1697 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1698 mAcceptConnection = &Server::recvmsgServerConnection;
1699 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1700 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001701 case SocketType::UNIX_RAW: {
1702 auto addr = allocateSocketAddress();
1703 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1704 if (status != OK) {
1705 return AssertionFailure()
1706 << "setupRawSocketServer: " << statusToString(status);
1707 }
1708 mConnectToServer = [addr] {
1709 return connectTo(UnixSocketAddress(addr.c_str()));
1710 };
1711 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001712 case SocketType::VSOCK: {
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001713 unsigned port;
1714 auto status =
1715 rpcServer->setupVsockServer(VMADDR_CID_LOCAL, VMADDR_PORT_ANY, &port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001716 if (status != OK) {
1717 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1718 }
1719 mConnectToServer = [port] {
1720 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1721 };
1722 } break;
1723 case SocketType::INET: {
1724 unsigned int port;
1725 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1726 if (status != OK) {
1727 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1728 }
1729 mConnectToServer = [port] {
1730 const char* addr = kLocalInetAddress;
1731 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001732 if (aiStart == nullptr) return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001733 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1734 auto fd = connectTo(
1735 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1736 if (fd.ok()) return fd;
1737 }
1738 ALOGE("None of the socket address resolved for %s:%u can be connected",
1739 addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001740 return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001741 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001742 } break;
1743 case SocketType::TIPC: {
1744 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1745 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001746 }
1747 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001748 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00001749 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001750 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1751 mSetup = true;
1752 return AssertionSuccess();
1753 }
1754 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1755 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1756 return mCertVerifier;
1757 }
1758 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1759 void start() {
1760 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1761 mThread = std::make_unique<std::thread>(&Server::run, this);
1762 }
David Brazdil21c887c2022-09-23 12:25:18 +01001763
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001764 unique_fd acceptServerConnection() {
1765 return unique_fd(TEMP_FAILURE_RETRY(
David Brazdil21c887c2022-09-23 12:25:18 +01001766 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1767 }
1768
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001769 unique_fd recvmsgServerConnection() {
1770 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +01001771 int buf;
1772 iovec iov{&buf, sizeof(buf)};
1773
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +00001774 if (binder::os::receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001775 PLOGF("Failed receiveMessage");
David Brazdil21c887c2022-09-23 12:25:18 +01001776 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001777 LOG_ALWAYS_FATAL_IF(fds.size() != 1, "Expected one FD from receiveMessage(), got %zu",
1778 fds.size());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001779 return std::move(std::get<unique_fd>(fds[0]));
David Brazdil21c887c2022-09-23 12:25:18 +01001780 }
1781
Yifan Hong1deca4b2021-09-10 16:16:44 -07001782 void run() {
1783 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1784
1785 std::vector<std::thread> threads;
1786 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001787 unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001788 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1789 }
1790
1791 for (auto& thread : threads) thread.join();
1792 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001793 void handleOne(unique_fd acceptedFd) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001794 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001795 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001796 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001797 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001798 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001799 }
Yifan Honge07d2732021-09-13 21:59:14 -07001800 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001801 shutdown();
1802 join();
1803 }
1804 void shutdown() { mFdTrigger->trigger(); }
1805
1806 void setPostConnect(
1807 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1808 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001809 }
1810
1811 private:
1812 std::unique_ptr<std::thread> mThread;
1813 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001814 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001815 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001816 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001817 std::unique_ptr<RpcTransportCtx> mCtx;
1818 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1819 std::make_shared<RpcCertificateVerifierSimple>();
1820 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001821 // The function invoked after connection and handshake. By default, it is
1822 // |defaultPostConnect| that sends |kMessage| to the client.
1823 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1824 Server::defaultPostConnect;
1825
1826 void join() {
1827 if (mThread != nullptr) {
1828 mThread->join();
1829 mThread = nullptr;
1830 }
1831 }
1832
1833 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1834 FdTrigger* fdTrigger) {
1835 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001836 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001837 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001838 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001839 if (status != OK) return AssertionFailure() << statusToString(status);
1840 return AssertionSuccess();
1841 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001842 };
1843
1844 class Client {
1845 public:
1846 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1847 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001848 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001849 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1850 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001851 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001852 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001853 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1854 return AssertionSuccess();
1855 }
1856 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1857 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1858 return mCertVerifier;
1859 }
Yifan Hong67519322021-09-13 18:51:16 -07001860 // connect() and do handshake
1861 bool setUpTransport() {
1862 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001863 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001864 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1865 return mClientTransport != nullptr;
1866 }
1867 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1868 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1869 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001870 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001871 status_t readStatus =
1872 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001873 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001874 if (readStatus != OK) {
1875 return AssertionFailure() << statusToString(readStatus);
1876 }
1877 if (readMessage != expectedMessage) {
1878 return AssertionFailure()
1879 << "Expected " << expectedMessage << ", actual " << readMessage;
1880 }
1881 return AssertionSuccess();
1882 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001883 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001884 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001885 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1886 return;
1887 }
1888 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001889 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001890 }
1891
Pawan49d74cb2022-08-03 21:19:11 +00001892 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1893
Yifan Hong1deca4b2021-09-10 16:16:44 -07001894 private:
1895 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001896 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001897 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1898 std::unique_ptr<RpcTransportCtx> mCtx;
1899 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1900 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001901 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001902 };
1903
1904 // Make A trust B.
1905 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001906 static status_t trust(RpcSecurity rpcSecurity,
1907 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1908 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001909 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001910 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1911 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1912 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001913 }
1914
1915 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001916};
1917
1918class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1919public:
1920 using Server = RpcTransportTestUtils::Server;
1921 using Client = RpcTransportTestUtils::Client;
1922 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001923 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001924 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001925 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001926 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001927 return ret;
1928 }
1929 static std::vector<ParamType> getRpcTranportTestParams() {
1930 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001931 for (auto serverVersion : testVersions()) {
1932 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1933 for (auto rpcSecurity : RpcSecurityValues()) {
1934 switch (rpcSecurity) {
1935 case RpcSecurity::RAW: {
1936 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1937 } break;
1938 case RpcSecurity::TLS: {
1939 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1940 serverVersion);
1941 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1942 serverVersion);
1943 } break;
1944 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001945 }
1946 }
1947 }
1948 return ret;
1949 }
1950 template <typename A, typename B>
1951 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001952 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1953 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001954 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1955 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001956 void SetUp() override {
1957 if constexpr (!kEnableRpcThreads) {
1958 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1959 }
1960 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001961};
1962
1963TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001964 auto server = std::make_unique<Server>();
1965 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001966
1967 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001968 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001969
1970 ASSERT_EQ(OK, trust(&client, server));
1971 ASSERT_EQ(OK, trust(server, &client));
1972
1973 server->start();
1974 client.run();
1975}
1976
1977TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001978 auto server = std::make_unique<Server>();
1979 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001980
1981 std::vector<Client> clients;
1982 for (int i = 0; i < 2; i++) {
1983 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001984 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001985 ASSERT_EQ(OK, trust(&client, server));
1986 ASSERT_EQ(OK, trust(server, &client));
1987 }
1988
1989 server->start();
1990 for (auto& client : clients) client.run();
1991}
1992
1993TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001994 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1995 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001996
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001997 auto untrustedServer = std::make_unique<Server>();
1998 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001999
2000 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002001 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002002
2003 ASSERT_EQ(OK, trust(untrustedServer, &client));
2004
2005 untrustedServer->start();
2006
2007 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2008 // the client can't verify the server's identity.
2009 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2010 client.run(handshakeOk);
2011}
2012TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002013 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2014 (void)serverVersion;
2015
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002016 auto validServer = std::make_unique<Server>();
2017 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002018
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002019 auto maliciousServer = std::make_unique<Server>();
2020 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002021
2022 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002023 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002024
2025 ASSERT_EQ(OK, trust(&client, validServer));
2026 ASSERT_EQ(OK, trust(validServer, &client));
2027 ASSERT_EQ(OK, trust(maliciousServer, &client));
2028
2029 maliciousServer->start();
2030
2031 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2032 // the client can't verify the server's identity.
2033 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2034 client.run(handshakeOk);
2035}
2036
2037TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002038 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2039 (void)serverVersion;
2040
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002041 auto server = std::make_unique<Server>();
2042 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002043
2044 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002045 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002046
2047 ASSERT_EQ(OK, trust(&client, server));
2048
2049 server->start();
2050
2051 // For TLS, Client should be able to verify server's identity, so client should see
2052 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2053 // identity and should drop the connection, so client shouldn't be able to read anything.
2054 bool readOk = rpcSecurity != RpcSecurity::TLS;
2055 client.run(true, readOk);
2056}
2057
2058TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002059 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2060 (void)serverVersion;
2061
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002062 auto server = std::make_unique<Server>();
2063 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002064
2065 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002066 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002067 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002068 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002069
2070 ASSERT_EQ(OK, trust(&validClient, server));
2071 ASSERT_EQ(OK, trust(&maliciousClient, server));
2072
2073 server->start();
2074
2075 // See UntrustedClient.
2076 bool readOk = rpcSecurity != RpcSecurity::TLS;
2077 maliciousClient.run(true, readOk);
2078}
2079
Yifan Hong67519322021-09-13 18:51:16 -07002080TEST_P(RpcTransportTest, Trigger) {
2081 std::string msg2 = ", world!";
2082 std::mutex writeMutex;
2083 std::condition_variable writeCv;
2084 bool shouldContinueWriting = false;
2085 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002086 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002087 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002088 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2089 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002090 if (status != OK) return AssertionFailure() << statusToString(status);
2091
2092 {
2093 std::unique_lock<std::mutex> lock(writeMutex);
2094 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2095 return AssertionFailure() << "write barrier not cleared in time!";
2096 }
2097 }
2098
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002099 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002100 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2101 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002102 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002103 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002104 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002105 << statusToString(status);
2106 return AssertionSuccess();
2107 };
2108
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002109 auto server = std::make_unique<Server>();
2110 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002111
2112 // Set up client
2113 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002114 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002115
2116 // Exchange keys
2117 ASSERT_EQ(OK, trust(&client, server));
2118 ASSERT_EQ(OK, trust(server, &client));
2119
2120 server->setPostConnect(serverPostConnect);
2121
Yifan Hong67519322021-09-13 18:51:16 -07002122 server->start();
2123 // connect() to server and do handshake
2124 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002125 // read the first message. This ensures that server has finished handshake and start handling
2126 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002127 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002128 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2129 // write is on an FdTrigger that has been shut down.
2130 server->shutdown();
2131 // Continues server thread to write the second message.
2132 {
Yifan Hong22211f82021-09-14 12:32:25 -07002133 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002134 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002135 }
Yifan Hong22211f82021-09-14 12:32:25 -07002136 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002137 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002138 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002139 // On the client side, second read fails with DEAD_OBJECT
2140 ASSERT_FALSE(client.readMessage(msg2));
2141}
2142
Pawan49d74cb2022-08-03 21:19:11 +00002143TEST_P(RpcTransportTest, CheckWaitingForRead) {
2144 std::mutex readMutex;
2145 std::condition_variable readCv;
2146 bool shouldContinueReading = false;
2147 // Server will write data on transport once its started
2148 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
2149 std::string message(RpcTransportTestUtils::kMessage);
2150 iovec messageIov{message.data(), message.size()};
2151 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2152 std::nullopt, nullptr);
2153 if (status != OK) return AssertionFailure() << statusToString(status);
2154
2155 {
2156 std::unique_lock<std::mutex> lock(readMutex);
2157 shouldContinueReading = true;
2158 lock.unlock();
2159 readCv.notify_all();
2160 }
2161 return AssertionSuccess();
2162 };
2163
2164 // Setup Server and client
2165 auto server = std::make_unique<Server>();
2166 ASSERT_TRUE(server->setUp(GetParam()));
2167
2168 Client client(server->getConnectToServerFn());
2169 ASSERT_TRUE(client.setUp(GetParam()));
2170
2171 ASSERT_EQ(OK, trust(&client, server));
2172 ASSERT_EQ(OK, trust(server, &client));
2173 server->setPostConnect(serverPostConnect);
2174
2175 server->start();
2176 ASSERT_TRUE(client.setUpTransport());
2177 {
2178 // Wait till server writes data
2179 std::unique_lock<std::mutex> lock(readMutex);
2180 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2181 }
2182
2183 // Since there is no read polling here, we will get polling count 0
2184 ASSERT_FALSE(client.isTransportWaiting());
2185 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2186 // Thread should increment polling count, read and decrement polling count
2187 // Again, polling count should be zero here
2188 ASSERT_FALSE(client.isTransportWaiting());
2189
2190 server->shutdown();
2191}
2192
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002193INSTANTIATE_TEST_SUITE_P(BinderRpc, RpcTransportTest,
2194 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
2195 RpcTransportTest::PrintParamInfo);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002196
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002197class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002198 : public testing::TestWithParam<
2199 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002200public:
2201 template <typename A, typename B>
2202 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002203 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2204 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002205 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2206 }
2207 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002208 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2209 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2210 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002211 };
2212};
2213
2214TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002215 if constexpr (!kEnableRpcThreads) {
2216 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2217 }
2218
Frederick Mayledc07cf82022-05-26 20:30:12 +00002219 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002220
2221 std::vector<uint8_t> pkeyData, certData;
2222 {
2223 auto pkey = makeKeyPairForSelfSignedCert();
2224 ASSERT_NE(nullptr, pkey);
2225 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2226 ASSERT_NE(nullptr, cert);
2227 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2228 certData = serializeCertificate(cert.get(), certificateFormat);
2229 }
2230
2231 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2232 auto desCert = deserializeCertificate(certData, certificateFormat);
2233 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002234 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2235 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002236
2237 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2238 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2239
2240 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2241 ASSERT_TRUE(client.setUp(utilsParam));
2242
2243 ASSERT_EQ(OK, trust(&client, server));
2244 ASSERT_EQ(OK, trust(server, &client));
2245
2246 server->start();
2247 client.run();
2248}
2249
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002250INSTANTIATE_TEST_SUITE_P(
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002251 BinderRpc, RpcTransportTlsKeyTest,
2252 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2253 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002254 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2255 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002256 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00002257#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002258
Steven Morelandc1635952021-04-01 16:20:47 +00002259} // namespace android
2260
2261int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002262 ::testing::InitGoogleTest(&argc, argv);
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002263 __android_log_set_logger(__android_log_stderr_logger);
Steven Morelanda83191d2021-10-27 10:14:53 -07002264
Steven Moreland5553ac42020-11-11 02:14:45 +00002265 return RUN_ALL_TESTS();
2266}