blob: a1e53c5ebc09375cef3882048d487309b14bd782 [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 Moreland9c203222023-05-31 21:26:41 +0000502 // Potential flake, but make sure calls are handled in parallel. Due
503 // to past flakes, this only checks that the amount of time taken has
504 // some parallelism. Other tests such as ThreadPoolGreaterThanEqualRequested
505 // check this more exactly.
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
518 // b/272429574 - below 500ms, the test fails
519 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Yifan Hong1f44f982021-10-08 17:16:47 -0700520}
521
Andrei Homescua858b0e2022-08-01 23:43:09 +0000522TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
523 if (clientOrServerSingleThreaded()) {
524 GTEST_SKIP() << "This test requires multiple threads";
525 }
526
Yifan Hong1f44f982021-10-08 17:16:47 -0700527 constexpr size_t kNumThreads = 20;
528 constexpr size_t kNumOutgoingConnections = 10;
529 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
530 auto proc = createRpcTestSocketServerProcess(
531 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
Steven Moreland73aa6f82023-03-15 21:49:07 +0000532
533 // b/272429574 - below 500ms, the test fails
534 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
Steven Moreland5553ac42020-11-11 02:14:45 +0000535}
536
Andrei Homescua858b0e2022-08-01 23:43:09 +0000537TEST_P(BinderRpc, ThreadingStressTest) {
538 if (clientOrServerSingleThreaded()) {
539 GTEST_SKIP() << "This test requires multiple threads";
540 }
541
Steven Moreland27f620a2023-03-06 19:44:36 +0000542 constexpr size_t kNumClientThreads = 5;
543 constexpr size_t kNumServerThreads = 5;
544 constexpr size_t kNumCalls = 50;
Steven Moreland5553ac42020-11-11 02:14:45 +0000545
Steven Moreland4313d7e2021-07-15 23:41:22 +0000546 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000547
548 std::vector<std::thread> threads;
549 for (size_t i = 0; i < kNumClientThreads; i++) {
550 threads.push_back(std::thread([&] {
551 for (size_t j = 0; j < kNumCalls; j++) {
552 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000553 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000554 EXPECT_EQ(proc.rootBinder, out);
555 }
556 }));
557 }
558
559 for (auto& t : threads) t.join();
560}
561
Steven Moreland925ba0a2021-09-17 18:06:32 -0700562static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
563 std::vector<std::thread> threads;
564 for (size_t i = 0; i < threadCount; i++) {
565 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
566 }
567 for (auto& t : threads) t.join();
568}
569
Andrei Homescua858b0e2022-08-01 23:43:09 +0000570TEST_P(BinderRpc, OnewayStressTest) {
571 if (clientOrServerSingleThreaded()) {
572 GTEST_SKIP() << "This test requires multiple threads";
573 }
574
Steven Morelandc6046982021-04-20 00:49:42 +0000575 constexpr size_t kNumClientThreads = 10;
576 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -0700577 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +0000578
Steven Moreland4313d7e2021-07-15 23:41:22 +0000579 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000580
581 std::vector<std::thread> threads;
582 for (size_t i = 0; i < kNumClientThreads; i++) {
583 threads.push_back(std::thread([&] {
584 for (size_t j = 0; j < kNumCalls; j++) {
585 EXPECT_OK(proc.rootIface->sendString("a"));
586 }
Steven Morelandc6046982021-04-20 00:49:42 +0000587 }));
588 }
589
590 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -0700591
592 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +0000593}
594
Frederick Mayleb0221d12022-10-03 23:10:53 +0000595TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
596 if (!supportsFdTransport()) {
597 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
598 }
599 if (clientOrServerSingleThreaded()) {
600 GTEST_SKIP() << "This test requires multiple threads";
601 }
602
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000603 constexpr size_t kNumServerThreads = 3;
604
Frederick Mayleb0221d12022-10-03 23:10:53 +0000605 // This test forces a oneway transaction to be queued by issuing two
606 // `blockingSendFdOneway` calls, then drains the queue by issuing two
607 // `blockingRecvFd` calls.
608 //
609 // For more details about the queuing semantics see
610 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
611
612 auto proc = createRpcTestSocketServerProcess({
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000613 .numThreads = kNumServerThreads,
Frederick Mayleb0221d12022-10-03 23:10:53 +0000614 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
615 .serverSupportedFileDescriptorTransportModes =
616 {RpcSession::FileDescriptorTransportMode::UNIX},
617 });
618
619 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
620 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
621 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
622 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
623
624 android::os::ParcelFileDescriptor fdA;
625 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
626 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700627 ASSERT_TRUE(ReadFdToString(fdA.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000628 EXPECT_EQ(result, "a");
629
630 android::os::ParcelFileDescriptor fdB;
631 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700632 ASSERT_TRUE(ReadFdToString(fdB.get(), &result));
Frederick Mayleb0221d12022-10-03 23:10:53 +0000633 EXPECT_EQ(result, "b");
Andrei Homescu5f2bc562023-02-25 04:59:43 +0000634
635 saturateThreadPool(kNumServerThreads, proc.rootIface);
Frederick Mayleb0221d12022-10-03 23:10:53 +0000636}
637
Andrei Homescua858b0e2022-08-01 23:43:09 +0000638TEST_P(BinderRpc, OnewayCallQueueing) {
639 if (clientOrServerSingleThreaded()) {
640 GTEST_SKIP() << "This test requires multiple threads";
641 }
642
Frederick Mayle96872592023-03-07 14:56:15 -0800643 constexpr size_t kNumQueued = 10;
Steven Moreland5553ac42020-11-11 02:14:45 +0000644 constexpr size_t kNumExtraServerThreads = 4;
Steven Moreland5553ac42020-11-11 02:14:45 +0000645
646 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000647 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000648
Frederick Mayle96872592023-03-07 14:56:15 -0800649 // all these *Oneway commands should be queued on the server sequentially,
Steven Moreland1c678802021-09-17 16:48:47 -0700650 // even though there are multiple threads.
Frederick Mayle96872592023-03-07 14:56:15 -0800651 for (size_t i = 0; i + 1 < kNumQueued; i++) {
652 proc.rootIface->blockingSendIntOneway(i);
Steven Moreland5553ac42020-11-11 02:14:45 +0000653 }
Frederick Mayle96872592023-03-07 14:56:15 -0800654 for (size_t i = 0; i + 1 < kNumQueued; i++) {
655 int n;
656 proc.rootIface->blockingRecvInt(&n);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700657 EXPECT_EQ(n, static_cast<ssize_t>(i));
Frederick Mayle96872592023-03-07 14:56:15 -0800658 }
Steven Morelandf5174272021-05-25 00:39:28 +0000659
Steven Moreland925ba0a2021-09-17 18:06:32 -0700660 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +0000661}
662
Andrei Homescua858b0e2022-08-01 23:43:09 +0000663TEST_P(BinderRpc, OnewayCallExhaustion) {
664 if (clientOrServerSingleThreaded()) {
665 GTEST_SKIP() << "This test requires multiple threads";
666 }
667
Steven Morelandd45be622021-06-04 02:19:37 +0000668 constexpr size_t kNumClients = 2;
669 constexpr size_t kTooLongMs = 1000;
670
Steven Moreland4313d7e2021-07-15 23:41:22 +0000671 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000672
673 // Build up oneway calls on the second session to make sure it terminates
674 // and shuts down. The first session should be unaffected (proc destructor
675 // checks the first session).
Andrei Homescu96834632022-10-14 00:49:49 +0000676 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
Steven Morelandd45be622021-06-04 02:19:37 +0000677
678 std::vector<std::thread> threads;
679 for (size_t i = 0; i < kNumClients; i++) {
680 // one of these threads will get stuck queueing a transaction once the
681 // socket fills up, the other will be able to fill up transactions on
682 // this object
683 threads.push_back(std::thread([&] {
684 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
685 }
686 }));
687 }
688 for (auto& t : threads) t.join();
689
690 Status status = iface->sleepMsAsync(kTooLongMs);
691 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
692
Steven Moreland798e0d12021-07-14 23:19:25 +0000693 // now that it has died, wait for the remote session to shutdown
694 std::vector<int32_t> remoteCounts;
695 do {
696 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
697 } while (remoteCounts.size() == kNumClients);
698
Steven Morelandd45be622021-06-04 02:19:37 +0000699 // the second session should be shutdown in the other process by the time we
700 // are able to join above (it'll only be hung up once it finishes processing
701 // any pending commands). We need to erase this session from the record
702 // here, so that the destructor for our session won't check that this
703 // session is valid, but we still want it to test the other session.
Andrei Homescu96834632022-10-14 00:49:49 +0000704 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
Steven Morelandd45be622021-06-04 02:19:37 +0000705}
706
Steven Moreland67f85902023-03-15 01:13:49 +0000707TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
708 if (clientOrServerSingleThreaded()) {
709 GTEST_SKIP() << "This test requires multiple threads";
710 }
711
712 // session 0 - will check for leaks in destrutor of proc
713 // session 1 - we want to make sure it gets deleted when we drop all references to it
714 auto proc = createRpcTestSocketServerProcess(
Tomasz Wasilczyk5da65602023-06-29 10:12:50 -0700715 {.numThreads = 1, .numSessions = 2, .numIncomingConnectionsBySession = {0, 1}});
Steven Moreland67f85902023-03-15 01:13:49 +0000716
717 wp<RpcSession> session = proc.proc->sessions.at(1).session;
718
719 // remove all references to the second session
720 proc.proc->sessions.at(1).root = nullptr;
721 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
722
723 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
724 // to drain commands.
725 for (size_t i = 0; i < 100; i++) {
726 usleep(10 * 1000);
727 if (session.promote() == nullptr) break;
728 }
729
730 EXPECT_EQ(nullptr, session.promote());
Steven Morelandb5d2b642023-05-04 00:31:45 +0000731
Steven Moreland0ebdaad2023-06-14 19:33:37 +0000732 // now that it has died, wait for the remote session to shutdown
733 std::vector<int32_t> remoteCounts;
734 do {
735 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
736 } while (remoteCounts.size() > 1);
Steven Moreland67f85902023-03-15 01:13:49 +0000737}
738
Devin Moore66d5b7a2022-07-07 21:42:10 +0000739TEST_P(BinderRpc, SingleDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000740 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000741 GTEST_SKIP() << "This test requires multiple threads";
742 }
743 class MyDeathRec : public IBinder::DeathRecipient {
744 public:
745 void binderDied(const wp<IBinder>& /* who */) override {
746 dead = true;
747 mCv.notify_one();
748 }
749 std::mutex mMtx;
750 std::condition_variable mCv;
751 bool dead = false;
752 };
753
754 // Death recipient needs to have an incoming connection to be called
755 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000756 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000757
758 auto dr = sp<MyDeathRec>::make();
759 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
760
761 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
762 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
763 }
764
765 std::unique_lock<std::mutex> lock(dr->mMtx);
Steven Morelanddd231e22022-09-08 19:47:49 +0000766 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000767
768 // need to wait for the session to shutdown so we don't "Leak session"
Steven Moreland67f85902023-03-15 01:13:49 +0000769 // can't do this before checking the death recipient by calling
770 // forceShutdown earlier, because shutdownAndWait will also trigger
771 // a death recipient, but if we had a way to wait for the service
772 // to gracefully shutdown, we could use that here.
Andrei Homescu96834632022-10-14 00:49:49 +0000773 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000774 proc.expectAlreadyShutdown = true;
775}
776
777TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000778 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000779 GTEST_SKIP() << "This test requires multiple threads";
780 }
781 class MyDeathRec : public IBinder::DeathRecipient {
782 public:
783 void binderDied(const wp<IBinder>& /* who */) override {
784 dead = true;
785 mCv.notify_one();
786 }
787 std::mutex mMtx;
788 std::condition_variable mCv;
789 bool dead = false;
790 };
791
792 // Death recipient needs to have an incoming connection to be called
793 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000794 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000795
796 auto dr = sp<MyDeathRec>::make();
797 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
798
799 // Explicitly calling shutDownAndWait will cause the death recipients
800 // to be called.
Andrei Homescu96834632022-10-14 00:49:49 +0000801 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000802
803 std::unique_lock<std::mutex> lock(dr->mMtx);
804 if (!dr->dead) {
Steven Morelanddd231e22022-09-08 19:47:49 +0000805 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000806 }
807 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
808
Andrei Homescu96834632022-10-14 00:49:49 +0000809 proc.proc->terminate();
810 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000811 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
812 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
813 });
814 proc.expectAlreadyShutdown = true;
815}
816
Steven Moreland5ec743f2023-01-18 01:02:06 +0000817TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000818 if (socketType() == SocketType::TIPC) {
819 // This should work, but Trusty takes too long to restart the service
820 GTEST_SKIP() << "Service death test not supported on Trusty";
821 }
Devin Moore66d5b7a2022-07-07 21:42:10 +0000822 class MyDeathRec : public IBinder::DeathRecipient {
823 public:
824 void binderDied(const wp<IBinder>& /* who */) override {}
825 };
826
Steven Moreland67f85902023-03-15 01:13:49 +0000827 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000828
829 auto dr = sp<MyDeathRec>::make();
Steven Moreland5ec743f2023-01-18 01:02:06 +0000830 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
Devin Moore66d5b7a2022-07-07 21:42:10 +0000831}
832
833TEST_P(BinderRpc, UnlinkDeathRecipient) {
Andrei Homescua858b0e2022-08-01 23:43:09 +0000834 if (clientOrServerSingleThreaded()) {
Devin Moore66d5b7a2022-07-07 21:42:10 +0000835 GTEST_SKIP() << "This test requires multiple threads";
836 }
837 class MyDeathRec : public IBinder::DeathRecipient {
838 public:
839 void binderDied(const wp<IBinder>& /* who */) override {
840 GTEST_FAIL() << "This should not be called after unlinkToDeath";
841 }
842 };
843
844 // Death recipient needs to have an incoming connection to be called
845 auto proc = createRpcTestSocketServerProcess(
Steven Moreland67f85902023-03-15 01:13:49 +0000846 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
Devin Moore66d5b7a2022-07-07 21:42:10 +0000847
848 auto dr = sp<MyDeathRec>::make();
849 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
850 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
851
Steven Moreland67f85902023-03-15 01:13:49 +0000852 proc.forceShutdown();
Devin Moore66d5b7a2022-07-07 21:42:10 +0000853}
854
Steven Morelandc1635952021-04-01 16:20:47 +0000855TEST_P(BinderRpc, Die) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000856 if (socketType() == SocketType::TIPC) {
857 // This should work, but Trusty takes too long to restart the service
858 GTEST_SKIP() << "Service death test not supported on Trusty";
859 }
860
Steven Moreland5553ac42020-11-11 02:14:45 +0000861 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000862 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000863
864 // make sure there is some state during crash
865 // 1. we hold their binder
866 sp<IBinderRpcSession> session;
867 EXPECT_OK(proc.rootIface->openSession("happy", &session));
868 // 2. they hold our binder
869 sp<IBinder> binder = new BBinder();
870 EXPECT_OK(proc.rootIface->holdBinder(binder));
871
872 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
873 << "Do death cleanup: " << doDeathCleanup;
874
Andrei Homescu96834632022-10-14 00:49:49 +0000875 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000876 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
877 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
878 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000879 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000880 }
881}
882
Steven Morelandd7302072021-05-15 01:32:04 +0000883TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu2a298012022-06-15 01:08:54 +0000884 // This test only works if the current process shared the internal state of
885 // ProcessState with the service across the call to fork(). Both the static
886 // libraries and libbinder.so have their own separate copies of all the
887 // globals, so the test only works when the test client and service both use
888 // libbinder.so (when using static libraries, even a client and service
889 // using the same kind of static library should have separate copies of the
890 // variables).
Andrei Homescua858b0e2022-08-01 23:43:09 +0000891 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000892 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
893 "at build time.";
894 }
895
Steven Moreland4313d7e2021-07-15 23:41:22 +0000896 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +0000897
Andrei Homescu2a298012022-06-15 01:08:54 +0000898 // we can't allocate IPCThreadState so actually the first time should
899 // succeed :(
900 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
Steven Morelandd7302072021-05-15 01:32:04 +0000901
902 // second time! we catch the error :)
903 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
904
Andrei Homescu96834632022-10-14 00:49:49 +0000905 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000906 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
907 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
908 });
Steven Morelandaf4ca712021-05-24 23:22:08 +0000909 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000910}
911
Frederick Mayle69a0c992022-05-26 20:38:39 +0000912TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000913 if (socketType() == SocketType::TIPC) {
914 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
915 }
916
Frederick Mayle69a0c992022-05-26 20:38:39 +0000917 auto proc = createRpcTestSocketServerProcess({
918 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
919 .serverSupportedFileDescriptorTransportModes =
920 {RpcSession::FileDescriptorTransportMode::UNIX},
921 .allowConnectFailure = true,
922 });
Andrei Homescu96834632022-10-14 00:49:49 +0000923 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
924 proc.proc->terminate();
925 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000926 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
927 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
928 });
929 proc.expectAlreadyShutdown = true;
930}
931
932TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000933 if (socketType() == SocketType::TIPC) {
934 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
935 }
936
Frederick Mayle69a0c992022-05-26 20:38:39 +0000937 auto proc = createRpcTestSocketServerProcess({
938 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
939 .serverSupportedFileDescriptorTransportModes =
940 {RpcSession::FileDescriptorTransportMode::NONE},
941 .allowConnectFailure = true,
942 });
Andrei Homescu96834632022-10-14 00:49:49 +0000943 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
944 proc.proc->terminate();
945 proc.proc->setCustomExitStatusCheck([](int wstatus) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000946 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
947 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
948 });
949 proc.expectAlreadyShutdown = true;
950}
951
952TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000953 if (socketType() == SocketType::TIPC) {
954 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
955 }
956
Frederick Mayle69a0c992022-05-26 20:38:39 +0000957 auto proc = createRpcTestSocketServerProcess({
958 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
959 .serverSupportedFileDescriptorTransportModes =
960 {RpcSession::FileDescriptorTransportMode::NONE,
961 RpcSession::FileDescriptorTransportMode::UNIX},
962 });
963
964 android::os::ParcelFileDescriptor out;
965 auto status = proc.rootIface->echoAsFile("hello", &out);
966 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
967}
968
969TEST_P(BinderRpc, ReceiveFile) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000970 if (socketType() == SocketType::TIPC) {
971 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
972 }
973
Frederick Mayle69a0c992022-05-26 20:38:39 +0000974 auto proc = createRpcTestSocketServerProcess({
975 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
976 .serverSupportedFileDescriptorTransportModes =
977 {RpcSession::FileDescriptorTransportMode::UNIX},
978 });
979
980 android::os::ParcelFileDescriptor out;
981 auto status = proc.rootIface->echoAsFile("hello", &out);
982 if (!supportsFdTransport()) {
983 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
984 return;
985 }
986 ASSERT_TRUE(status.isOk()) << status;
987
988 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -0700989 ASSERT_TRUE(ReadFdToString(out.get(), &result));
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -0700990 ASSERT_EQ(result, "hello");
Frederick Mayle69a0c992022-05-26 20:38:39 +0000991}
992
993TEST_P(BinderRpc, SendFiles) {
Andrei Homescu68a55612022-08-02 01:25:15 +0000994 if (socketType() == SocketType::TIPC) {
995 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
996 }
997
Frederick Mayle69a0c992022-05-26 20:38:39 +0000998 auto proc = createRpcTestSocketServerProcess({
999 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1000 .serverSupportedFileDescriptorTransportModes =
1001 {RpcSession::FileDescriptorTransportMode::UNIX},
1002 });
1003
1004 std::vector<android::os::ParcelFileDescriptor> files;
1005 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1006 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1007 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1008 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1009
1010 android::os::ParcelFileDescriptor out;
1011 auto status = proc.rootIface->concatFiles(files, &out);
1012 if (!supportsFdTransport()) {
1013 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1014 return;
1015 }
1016 ASSERT_TRUE(status.isOk()) << status;
1017
1018 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -07001019 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001020 EXPECT_EQ(result, "123abcd");
1021}
1022
1023TEST_P(BinderRpc, SendMaxFiles) {
1024 if (!supportsFdTransport()) {
1025 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1026 }
1027
1028 auto proc = createRpcTestSocketServerProcess({
1029 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1030 .serverSupportedFileDescriptorTransportModes =
1031 {RpcSession::FileDescriptorTransportMode::UNIX},
1032 });
1033
1034 std::vector<android::os::ParcelFileDescriptor> files;
1035 for (int i = 0; i < 253; i++) {
1036 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1037 }
1038
1039 android::os::ParcelFileDescriptor out;
1040 auto status = proc.rootIface->concatFiles(files, &out);
1041 ASSERT_TRUE(status.isOk()) << status;
1042
1043 std::string result;
Tomasz Wasilczyk26db5e42023-11-02 11:45:11 -07001044 EXPECT_TRUE(ReadFdToString(out.get(), &result));
Frederick Mayle69a0c992022-05-26 20:38:39 +00001045 EXPECT_EQ(result, std::string(253, 'a'));
1046}
1047
1048TEST_P(BinderRpc, SendTooManyFiles) {
1049 if (!supportsFdTransport()) {
1050 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1051 }
1052
1053 auto proc = createRpcTestSocketServerProcess({
1054 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1055 .serverSupportedFileDescriptorTransportModes =
1056 {RpcSession::FileDescriptorTransportMode::UNIX},
1057 });
1058
1059 std::vector<android::os::ParcelFileDescriptor> files;
1060 for (int i = 0; i < 254; i++) {
1061 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1062 }
1063
1064 android::os::ParcelFileDescriptor out;
1065 auto status = proc.rootIface->concatFiles(files, &out);
1066 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1067}
1068
Andrei Homescufc221502022-10-08 03:51:17 +00001069TEST_P(BinderRpc, AppendInvalidFd) {
Andrei Homescu68a55612022-08-02 01:25:15 +00001070 if (socketType() == SocketType::TIPC) {
1071 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1072 }
1073
Andrei Homescufc221502022-10-08 03:51:17 +00001074 auto proc = createRpcTestSocketServerProcess({
1075 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1076 .serverSupportedFileDescriptorTransportModes =
1077 {RpcSession::FileDescriptorTransportMode::UNIX},
1078 });
1079
1080 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1081 ASSERT_NE(badFd, -1);
1082
1083 // Close the file descriptor so it becomes invalid for dup
1084 close(badFd);
1085
1086 Parcel p1;
1087 p1.markForBinder(proc.rootBinder);
1088 p1.writeInt32(3);
1089 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1090
1091 Parcel pRaw;
1092 pRaw.markForBinder(proc.rootBinder);
1093 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1094
1095 pRaw.setDataPosition(0);
1096 EXPECT_EQ(3, pRaw.readInt32());
1097 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1098}
1099
Andrei Homescu68a55612022-08-02 01:25:15 +00001100#ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
Steven Moreland37aff182021-03-26 02:04:16 +00001101TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001102 if constexpr (!kEnableSharedLibs) {
1103 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1104 }
1105
Steven Moreland4313d7e2021-07-15 23:41:22 +00001106 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001107
1108 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1109 ASSERT_NE(binder, nullptr);
1110
1111 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1112}
1113
1114TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001115 if constexpr (!kEnableSharedLibs) {
1116 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1117 }
1118
Steven Moreland4313d7e2021-07-15 23:41:22 +00001119 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001120
1121 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1122 ASSERT_NE(binder, nullptr);
1123
1124 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1125 ASSERT_NE(ndkBinder, nullptr);
1126
1127 std::string out;
1128 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1129 ASSERT_TRUE(status.isOk()) << status.getDescription();
1130 ASSERT_EQ("aoeuaoeu", out);
1131}
Andrei Homescu68a55612022-08-02 01:25:15 +00001132#endif // __ANDROID_VENDOR__
Steven Moreland37aff182021-03-26 02:04:16 +00001133
Steven Moreland5553ac42020-11-11 02:14:45 +00001134ssize_t countFds() {
1135 DIR* dir = opendir("/proc/self/fd/");
1136 if (dir == nullptr) return -1;
1137 ssize_t ret = 0;
1138 dirent* ent;
1139 while ((ent = readdir(dir)) != nullptr) ret++;
1140 closedir(dir);
1141 return ret;
1142}
1143
Andrei Homescua858b0e2022-08-01 23:43:09 +00001144TEST_P(BinderRpc, Fds) {
1145 if (serverSingleThreaded()) {
1146 GTEST_SKIP() << "This test requires multiple threads";
1147 }
Andrei Homescu68a55612022-08-02 01:25:15 +00001148 if (socketType() == SocketType::TIPC) {
1149 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1150 }
Andrei Homescua858b0e2022-08-01 23:43:09 +00001151
Steven Moreland5553ac42020-11-11 02:14:45 +00001152 ssize_t beforeFds = countFds();
1153 ASSERT_GE(beforeFds, 0);
1154 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001155 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001156 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1157 }
1158 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1159}
1160
Devin Moore18f63752024-08-08 21:01:24 +00001161// TODO need to add IServiceManager.cpp/.h to libbinder_no_kernel
1162#ifdef BINDER_WITH_KERNEL_IPC
1163
1164class BinderRpcAccessor : public BinderRpc {
1165 void SetUp() override {
1166 if (serverSingleThreaded()) {
1167 // This blocks on android::FdTrigger::triggerablePoll when attempting to set
1168 // up the client RpcSession
1169 GTEST_SKIP() << "Accessors are not supported for single threaded libbinder";
1170 }
1171 if (rpcSecurity() == RpcSecurity::TLS) {
1172 GTEST_SKIP() << "Accessors are not supported with TLS";
1173 // ... for now
1174 }
1175
1176 if (socketType() == SocketType::UNIX_BOOTSTRAP) {
1177 GTEST_SKIP() << "Accessors do not support UNIX_BOOTSTRAP because no connection "
1178 "information is known";
1179 }
1180 if (socketType() == SocketType::TIPC) {
1181 GTEST_SKIP() << "Accessors do not support TIPC because the socket transport is not "
1182 "known in libbinder";
1183 }
1184 BinderRpc::SetUp();
1185 }
1186};
1187
1188inline void waitForExtraSessionCleanup(const BinderRpcTestProcessSession& proc) {
1189 // Need to give the server some time to delete its RpcSession after our last
1190 // reference is dropped, closing the connection. Check for up to 1 second,
1191 // every 10 ms.
1192 for (size_t i = 0; i < 100; i++) {
1193 std::vector<int32_t> remoteCounts;
1194 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1195 // We exect the original binder to still be alive, we just want to wait
1196 // for this extra session to be cleaned up.
1197 if (remoteCounts.size() == proc.proc->sessions.size()) break;
1198 usleep(10000);
1199 }
1200}
1201
1202TEST_P(BinderRpcAccessor, InjectAndGetServiceHappyPath) {
1203 constexpr size_t kNumThreads = 10;
1204 const String16 kInstanceName("super.cool.service/better_than_default");
1205
1206 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1207 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1208
1209 auto receipt = addAccessorProvider([&](const String16& name) -> sp<IBinder> {
1210 return createAccessor(name,
1211 [&](const String16& name, sockaddr* outAddr,
1212 socklen_t addrSize) -> status_t {
1213 if (outAddr == nullptr ||
1214 addrSize < proc.proc->sessions[0].addrLen) {
1215 return BAD_VALUE;
1216 }
1217 if (name == kInstanceName) {
1218 if (proc.proc->sessions[0].addr.ss_family == AF_UNIX) {
1219 sockaddr_un* un = reinterpret_cast<sockaddr_un*>(
1220 &proc.proc->sessions[0].addr);
1221 ALOGE("inside callback: %s", un->sun_path);
1222 }
1223 std::memcpy(outAddr, &proc.proc->sessions[0].addr,
1224 proc.proc->sessions[0].addrLen);
1225 return OK;
1226 }
1227 return NAME_NOT_FOUND;
1228 });
1229 });
1230
1231 EXPECT_FALSE(receipt.expired());
1232
1233 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1234 sp<IBinderRpcTest> service = checked_interface_cast<IBinderRpcTest>(binder);
1235 EXPECT_NE(service, nullptr);
1236
1237 sp<IBinder> out;
1238 EXPECT_OK(service->repeatBinder(binder, &out));
1239 EXPECT_EQ(binder, out);
1240
1241 out.clear();
1242 binder.clear();
1243 service.clear();
1244
1245 status_t status = removeAccessorProvider(receipt);
1246 EXPECT_EQ(status, OK);
1247
1248 waitForExtraSessionCleanup(proc);
1249}
1250
1251TEST_P(BinderRpcAccessor, InjectNoAccessorProvided) {
1252 const String16 kInstanceName("doesnt_matter_nothing_checks");
1253
1254 bool isProviderDeleted = false;
1255
1256 auto receipt = addAccessorProvider([&](const String16&) -> sp<IBinder> { return nullptr; });
1257 EXPECT_FALSE(receipt.expired());
1258
1259 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1260 EXPECT_EQ(binder, nullptr);
1261
1262 status_t status = removeAccessorProvider(receipt);
1263 EXPECT_EQ(status, OK);
1264}
1265
1266TEST_P(BinderRpcAccessor, InjectNoSockaddrProvided) {
1267 constexpr size_t kNumThreads = 10;
1268 const String16 kInstanceName("super.cool.service/better_than_default");
1269
1270 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1271 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1272
1273 bool isProviderDeleted = false;
1274 bool isAccessorDeleted = false;
1275
1276 auto receipt = addAccessorProvider([&](const String16& name) -> sp<IBinder> {
1277 return createAccessor(name, [&](const String16&, sockaddr*, socklen_t) -> status_t {
1278 // don't fill in outAddr
1279 return NAME_NOT_FOUND;
1280 });
1281 });
1282
1283 EXPECT_FALSE(receipt.expired());
1284
1285 sp<IBinder> binder = defaultServiceManager()->checkService(kInstanceName);
1286 EXPECT_EQ(binder, nullptr);
1287
1288 status_t status = removeAccessorProvider(receipt);
1289 EXPECT_EQ(status, OK);
1290}
1291
1292#endif // BINDER_WITH_KERNEL_IPC
1293
Andrei Homescud65666d2023-03-03 07:28:02 +00001294#ifdef BINDER_RPC_TO_TRUSTY_TEST
Steven Morelandb469f432023-07-28 22:13:47 +00001295
1296static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() {
1297 std::vector<BinderRpc::ParamType> ret;
1298
1299 for (const auto& clientVersion : testVersions()) {
1300 for (const auto& serverVersion : testVersions()) {
1301 ret.push_back(BinderRpc::ParamType{
1302 .type = SocketType::TIPC,
1303 .security = RpcSecurity::RAW,
1304 .clientVersion = clientVersion,
1305 .serverVersion = serverVersion,
1306 .singleThreaded = true,
1307 .noKernel = true,
1308 });
1309 }
1310 }
1311
1312 return ret;
1313}
1314
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001315INSTANTIATE_TEST_SUITE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()),
1316 BinderRpc::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00001317#else // BINDER_RPC_TO_TRUSTY_TEST
Steven Moreland9f250b02023-05-16 23:27:42 +00001318bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001319 // We don't need to enable TLS to know if vsock is supported.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001320 unique_fd serverFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001321 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Steven Morelanda27311b2023-04-11 22:13:35 +00001322
1323 if (errno == EAFNOSUPPORT) {
1324 return false;
1325 }
1326
Tomasz Wasilczykbfb13a82023-11-14 11:33:10 -08001327 LOG_ALWAYS_FATAL_IF(!serverFd.ok(), "Could not create socket: %s", strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001328
1329 sockaddr_vm serverAddr{
1330 .svm_family = AF_VSOCK,
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001331 .svm_port = VMADDR_PORT_ANY,
Andrei Homescu992a4052022-06-28 21:26:18 +00001332 .svm_cid = VMADDR_CID_ANY,
1333 };
1334 int ret = TEMP_FAILURE_RETRY(
1335 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001336 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port VMADDR_PORT_ANY: %s",
Andrei Homescu992a4052022-06-28 21:26:18 +00001337 strerror(errno));
1338
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001339 socklen_t len = sizeof(serverAddr);
1340 ret = getsockname(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), &len);
1341 LOG_ALWAYS_FATAL_IF(0 != ret, "Failed to getsockname: %s", strerror(errno));
Hannah.Hsu6b1036f2024-07-09 11:20:20 +08001342 LOG_ALWAYS_FATAL_IF(len < static_cast<socklen_t>(sizeof(serverAddr)),
1343 "getsockname didn't read the full addr struct");
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001344
Andrei Homescu992a4052022-06-28 21:26:18 +00001345 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001346 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", serverAddr.svm_port,
Andrei Homescu992a4052022-06-28 21:26:18 +00001347 strerror(errno));
1348
1349 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1350 // to see if the kernel supports it. It's safe to use a blocking
1351 // connect because vsock sockets have a 2 second connection timeout,
1352 // and they return ETIMEDOUT after that.
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001353 unique_fd connectFd(
Andrei Homescu992a4052022-06-28 21:26:18 +00001354 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001355 LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s",
1356 serverAddr.svm_port, strerror(errno));
Andrei Homescu992a4052022-06-28 21:26:18 +00001357
1358 bool success = false;
1359 sockaddr_vm connectAddr{
1360 .svm_family = AF_VSOCK,
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001361 .svm_port = serverAddr.svm_port,
Andrei Homescu992a4052022-06-28 21:26:18 +00001362 .svm_cid = VMADDR_CID_LOCAL,
1363 };
1364 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1365 sizeof(connectAddr)));
1366 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001367 unique_fd acceptFd;
Andrei Homescu992a4052022-06-28 21:26:18 +00001368 while (true) {
1369 pollfd pfd[]{
1370 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1371 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1372 };
Tomasz Wasilczyk657c2bc2023-11-07 06:57:42 -08001373 ret = TEMP_FAILURE_RETRY(poll(pfd, countof(pfd), -1));
Andrei Homescu992a4052022-06-28 21:26:18 +00001374 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1375
1376 if (pfd[0].revents & POLLIN) {
1377 sockaddr_vm acceptAddr;
1378 socklen_t acceptAddrLen = sizeof(acceptAddr);
1379 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1380 reinterpret_cast<sockaddr*>(&acceptAddr),
1381 &acceptAddrLen, SOCK_CLOEXEC));
1382 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1383 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1384 "Truncated address");
1385
1386 // Store the fd in acceptFd so we keep the connection alive
1387 // while polling connectFd
1388 acceptFd.reset(ret);
1389 }
1390
1391 if (pfd[1].revents & POLLOUT) {
1392 // Connect either succeeded or timed out
1393 int connectErrno;
1394 socklen_t connectErrnoLen = sizeof(connectErrno);
1395 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1396 &connectErrnoLen);
1397 LOG_ALWAYS_FATAL_IF(ret == -1,
1398 "Could not getsockopt() after connect() "
1399 "on non-blocking socket: %s.",
1400 strerror(errno));
1401
1402 // We're done, this is all we wanted
1403 success = connectErrno == 0;
1404 break;
1405 }
1406 }
1407 } else {
1408 success = ret == 0;
1409 }
1410
1411 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1412
1413 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001414}
1415
Yifan Hong1deca4b2021-09-10 16:16:44 -07001416static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
Alice Wang893a9912022-10-24 10:44:09 +00001417 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1418 SocketType::UNIX_RAW};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001419
1420 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001421
Steven Moreland9f250b02023-05-16 23:27:42 +00001422#ifdef __BIONIC__
1423 // Devices may not have vsock support. AVF tests will verify whether they do, but
1424 // we can't require it due to old kernels for the time being.
Steven Morelandda573042021-06-12 01:13:45 +00001425 static bool hasVsockLoopback = testSupportVsockLoopback();
Steven Moreland9f250b02023-05-16 23:27:42 +00001426#else
1427 // On host machines, we always assume we have vsock loopback. If we don't, the
1428 // subsequent failures will be more clear than showing one now.
1429 static bool hasVsockLoopback = true;
1430#endif
Steven Morelandda573042021-06-12 01:13:45 +00001431
1432 if (hasVsockLoopback) {
1433 ret.push_back(SocketType::VSOCK);
1434 }
1435
1436 return ret;
1437}
1438
Steven Morelandb469f432023-07-28 22:13:47 +00001439static std::vector<BinderRpc::ParamType> getBinderRpcParams() {
1440 std::vector<BinderRpc::ParamType> ret;
1441
Steven Morelandf7421432023-07-28 22:41:44 +00001442 constexpr bool full = false;
1443
Steven Morelandb469f432023-07-28 22:13:47 +00001444 for (const auto& type : testSocketTypes()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001445 if (full || type == SocketType::UNIX) {
1446 for (const auto& security : RpcSecurityValues()) {
1447 for (const auto& clientVersion : testVersions()) {
1448 for (const auto& serverVersion : testVersions()) {
1449 for (bool singleThreaded : {false, true}) {
Tomasz Wasilczyk2265ad92024-05-01 12:54:46 -07001450 for (bool noKernel : noKernelValues()) {
Steven Morelandf7421432023-07-28 22:41:44 +00001451 ret.push_back(BinderRpc::ParamType{
1452 .type = type,
1453 .security = security,
1454 .clientVersion = clientVersion,
1455 .serverVersion = serverVersion,
1456 .singleThreaded = singleThreaded,
1457 .noKernel = noKernel,
1458 });
1459 }
Steven Morelandb469f432023-07-28 22:13:47 +00001460 }
1461 }
1462 }
1463 }
Steven Morelandf7421432023-07-28 22:41:44 +00001464 } else {
1465 ret.push_back(BinderRpc::ParamType{
1466 .type = type,
1467 .security = RpcSecurity::RAW,
1468 .clientVersion = RPC_WIRE_PROTOCOL_VERSION,
1469 .serverVersion = RPC_WIRE_PROTOCOL_VERSION,
1470 .singleThreaded = false,
Tomasz Wasilczyk2265ad92024-05-01 12:54:46 -07001471 .noKernel = !kEnableKernelIpcTesting,
Steven Morelandf7421432023-07-28 22:41:44 +00001472 });
Steven Morelandb469f432023-07-28 22:13:47 +00001473 }
1474 }
Steven Morelandf7421432023-07-28 22:41:44 +00001475
Steven Morelandb469f432023-07-28 22:13:47 +00001476 return ret;
1477}
1478
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001479INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()),
1480 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001481
Devin Moore18f63752024-08-08 21:01:24 +00001482#ifdef BINDER_WITH_KERNEL_IPC
1483INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpcAccessor, ::testing::ValuesIn(getBinderRpcParams()),
1484 BinderRpc::PrintParamInfo);
1485#endif // BINDER_WITH_KERNEL_IPC
1486
Yifan Hong702115c2021-06-24 15:39:18 -07001487class BinderRpcServerRootObject
1488 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001489
1490TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1491 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1492 auto setRootObject = [](bool isStrong) -> SetFn {
1493 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1494 };
1495
Yifan Hong702115c2021-06-24 15:39:18 -07001496 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001497 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001498 auto binder1 = sp<BBinder>::make();
1499 IBinder* binderRaw1 = binder1.get();
1500 setRootObject(isStrong1)(server.get(), binder1);
1501 EXPECT_EQ(binderRaw1, server->getRootObject());
1502 binder1.clear();
1503 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1504
1505 auto binder2 = sp<BBinder>::make();
1506 IBinder* binderRaw2 = binder2.get();
1507 setRootObject(isStrong2)(server.get(), binder2);
1508 EXPECT_EQ(binderRaw2, server->getRootObject());
1509 binder2.clear();
1510 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1511}
1512
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001513INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerRootObject,
1514 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1515 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001516
Yifan Hong1a235852021-05-13 16:07:47 -07001517class OneOffSignal {
1518public:
1519 // If notify() was previously called, or is called within |duration|, return true; else false.
1520 template <typename R, typename P>
1521 bool wait(std::chrono::duration<R, P> duration) {
1522 std::unique_lock<std::mutex> lock(mMutex);
1523 return mCv.wait_for(lock, duration, [this] { return mValue; });
1524 }
1525 void notify() {
1526 std::unique_lock<std::mutex> lock(mMutex);
1527 mValue = true;
1528 lock.unlock();
1529 mCv.notify_all();
1530 }
1531
1532private:
1533 std::mutex mMutex;
1534 std::condition_variable mCv;
1535 bool mValue = false;
1536};
1537
Yifan Hong194acf22021-06-29 18:44:56 -07001538TEST(BinderRpc, Java) {
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001539 bool expectDebuggable = false;
1540#if defined(__ANDROID__)
1541 expectDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1542 android::base::GetProperty("ro.build.type", "") != "user";
1543#else
Yifan Hong194acf22021-06-29 18:44:56 -07001544 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1545 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1546 "to binderHostDeviceTest. Hence, just disable this test on host.";
1547#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001548 if constexpr (!kEnableKernelIpc) {
1549 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1550 "at build time.";
1551 }
1552
Yifan Hong194acf22021-06-29 18:44:56 -07001553 sp<IServiceManager> sm = defaultServiceManager();
1554 ASSERT_NE(nullptr, sm);
1555 // Any Java service with non-empty getInterfaceDescriptor() would do.
Devin Moore29db8602024-08-14 22:21:04 +00001556 // Let's pick activity.
1557 auto binder = sm->checkService(String16("activity"));
Yifan Hong194acf22021-06-29 18:44:56 -07001558 ASSERT_NE(nullptr, binder);
1559 auto descriptor = binder->getInterfaceDescriptor();
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001560 ASSERT_GE(descriptor.size(), 0u);
Yifan Hong194acf22021-06-29 18:44:56 -07001561 ASSERT_EQ(OK, binder->pingBinder());
1562
1563 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001564 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001565 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001566 auto socket = rpcServer->releaseServer();
1567
1568 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001569 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1570
Tomasz Wasilczykc2b71d52023-11-06 16:32:12 -08001571 if (!expectDebuggable) {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001572 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001573 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1574 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001575 << statusToString(setRpcClientDebugStatus);
1576 GTEST_SKIP();
1577 }
1578
1579 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001580
1581 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001582 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001583 auto rpcBinder = rpcSession->getRootObject();
1584 ASSERT_NE(nullptr, rpcBinder);
1585
1586 ASSERT_EQ(OK, rpcBinder->pingBinder());
1587
1588 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1589 << "getInterfaceDescriptor should not crash system_server";
1590 ASSERT_EQ(OK, rpcBinder->pingBinder());
1591}
1592
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001593class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1594public:
1595 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Andrei Homescuf30148c2023-03-10 00:31:45 +00001596 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001597 std::to_string(std::get<1>(info.param));
1598 }
1599};
1600
1601TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001602 unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001603 int sinkFd = sink.get();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001604 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001605 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001606 ASSERT_FALSE(server->hasServer());
1607 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1608 ASSERT_TRUE(server->hasServer());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001609 unique_fd retrieved = server->releaseServer();
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001610 ASSERT_FALSE(server->hasServer());
1611 ASSERT_EQ(sinkFd, retrieved.get());
1612}
1613
1614TEST_P(BinderRpcServerOnly, Shutdown) {
1615 if constexpr (!kEnableRpcThreads) {
1616 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1617 }
1618
1619 auto addr = allocateSocketAddress();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001620 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
Steven Morelandca3f6382023-05-11 23:23:26 +00001621 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001622 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1623 auto joinEnds = std::make_shared<OneOffSignal>();
1624
1625 // If things are broken and the thread never stops, don't block other tests. Because the thread
1626 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1627 // shared pointers are passed.
1628 std::thread([server, joinEnds] {
1629 server->join();
1630 joinEnds->notify();
1631 }).detach();
1632
1633 bool shutdown = false;
1634 for (int i = 0; i < 10 && !shutdown; i++) {
Steven Morelanddd231e22022-09-08 19:47:49 +00001635 usleep(30 * 1000); // 30ms; total 300ms
Andrei Homescu8d7f4bd2022-08-03 05:46:17 +00001636 if (server->shutdown()) shutdown = true;
1637 }
1638 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1639
1640 ASSERT_TRUE(joinEnds->wait(2s))
1641 << "After server->shutdown() returns true, join() did not stop after 2s";
1642}
1643
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001644INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerOnly,
1645 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1646 ::testing::ValuesIn(testVersions())),
1647 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001648
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001649class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001650public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001651 // Only parameterized only server version because `RpcSession` is bypassed
1652 // in the client half of the tests.
1653 using Param =
1654 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001655 using ConnectToServer = std::function<unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001656
1657 // A server that handles client socket connections.
1658 class Server {
1659 public:
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001660 using AcceptConnection = std::function<unique_fd(Server*)>;
David Brazdil21c887c2022-09-23 12:25:18 +01001661
Yifan Hong1deca4b2021-09-10 16:16:44 -07001662 explicit Server() {}
1663 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001664 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001665 [[nodiscard]] AssertionResult setUp(
1666 const Param& param,
1667 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001668 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001669 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
Steven Morelandca3f6382023-05-11 23:23:26 +00001670 if (!rpcServer->setProtocolVersion(serverVersion)) {
1671 return AssertionFailure() << "Invalid protocol version: " << serverVersion;
1672 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001673 switch (socketType) {
1674 case SocketType::PRECONNECTED: {
1675 return AssertionFailure() << "Not supported by this test";
1676 } break;
1677 case SocketType::UNIX: {
1678 auto addr = allocateSocketAddress();
1679 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1680 if (status != OK) {
1681 return AssertionFailure()
1682 << "setupUnixDomainServer: " << statusToString(status);
1683 }
1684 mConnectToServer = [addr] {
1685 return connectTo(UnixSocketAddress(addr.c_str()));
1686 };
1687 } break;
David Brazdil21c887c2022-09-23 12:25:18 +01001688 case SocketType::UNIX_BOOTSTRAP: {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001689 unique_fd bootstrapFdClient, bootstrapFdServer;
1690 if (!binder::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
David Brazdil21c887c2022-09-23 12:25:18 +01001691 return AssertionFailure() << "Socketpair() failed";
1692 }
1693 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1694 std::move(bootstrapFdServer));
1695 if (status != OK) {
1696 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1697 << statusToString(status);
1698 }
1699 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1700 mAcceptConnection = &Server::recvmsgServerConnection;
1701 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1702 } break;
Alice Wang893a9912022-10-24 10:44:09 +00001703 case SocketType::UNIX_RAW: {
1704 auto addr = allocateSocketAddress();
1705 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1706 if (status != OK) {
1707 return AssertionFailure()
1708 << "setupRawSocketServer: " << statusToString(status);
1709 }
1710 mConnectToServer = [addr] {
1711 return connectTo(UnixSocketAddress(addr.c_str()));
1712 };
1713 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001714 case SocketType::VSOCK: {
Tomasz Wasilczyk022db682024-06-17 13:55:51 -07001715 unsigned port;
1716 auto status =
1717 rpcServer->setupVsockServer(VMADDR_CID_LOCAL, VMADDR_PORT_ANY, &port);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001718 if (status != OK) {
1719 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1720 }
1721 mConnectToServer = [port] {
1722 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1723 };
1724 } break;
1725 case SocketType::INET: {
1726 unsigned int port;
1727 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1728 if (status != OK) {
1729 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1730 }
1731 mConnectToServer = [port] {
1732 const char* addr = kLocalInetAddress;
1733 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001734 if (aiStart == nullptr) return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001735 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1736 auto fd = connectTo(
1737 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1738 if (fd.ok()) return fd;
1739 }
1740 ALOGE("None of the socket address resolved for %s:%u can be connected",
1741 addr, port);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001742 return unique_fd{};
Yifan Hong1deca4b2021-09-10 16:16:44 -07001743 };
Andrei Homescu68a55612022-08-02 01:25:15 +00001744 } break;
1745 case SocketType::TIPC: {
1746 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1747 } break;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001748 }
1749 mFd = rpcServer->releaseServer();
Pawan49d74cb2022-08-03 21:19:11 +00001750 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Andrei Homescuf30148c2023-03-10 00:31:45 +00001751 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001752 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1753 mSetup = true;
1754 return AssertionSuccess();
1755 }
1756 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1757 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1758 return mCertVerifier;
1759 }
1760 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1761 void start() {
1762 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1763 mThread = std::make_unique<std::thread>(&Server::run, this);
1764 }
David Brazdil21c887c2022-09-23 12:25:18 +01001765
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001766 unique_fd acceptServerConnection() {
1767 return unique_fd(TEMP_FAILURE_RETRY(
David Brazdil21c887c2022-09-23 12:25:18 +01001768 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1769 }
1770
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001771 unique_fd recvmsgServerConnection() {
1772 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
David Brazdil21c887c2022-09-23 12:25:18 +01001773 int buf;
1774 iovec iov{&buf, sizeof(buf)};
1775
Tomasz Wasilczyk0d9dec22023-10-06 20:28:49 +00001776 if (binder::os::receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001777 PLOGF("Failed receiveMessage");
David Brazdil21c887c2022-09-23 12:25:18 +01001778 }
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07001779 LOG_ALWAYS_FATAL_IF(fds.size() != 1, "Expected one FD from receiveMessage(), got %zu",
1780 fds.size());
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001781 return std::move(std::get<unique_fd>(fds[0]));
David Brazdil21c887c2022-09-23 12:25:18 +01001782 }
1783
Yifan Hong1deca4b2021-09-10 16:16:44 -07001784 void run() {
1785 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1786
1787 std::vector<std::thread> threads;
1788 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001789 unique_fd acceptedFd = mAcceptConnection(this);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001790 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1791 }
1792
1793 for (auto& thread : threads) thread.join();
1794 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001795 void handleOne(unique_fd acceptedFd) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001796 ASSERT_TRUE(acceptedFd.ok());
Pawan3e0061c2022-08-26 21:08:34 +00001797 RpcTransportFd transportFd(std::move(acceptedFd));
Pawan49d74cb2022-08-03 21:19:11 +00001798 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001799 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001800 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001801 }
Yifan Honge07d2732021-09-13 21:59:14 -07001802 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001803 shutdown();
1804 join();
1805 }
1806 void shutdown() { mFdTrigger->trigger(); }
1807
1808 void setPostConnect(
1809 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1810 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001811 }
1812
1813 private:
1814 std::unique_ptr<std::thread> mThread;
1815 ConnectToServer mConnectToServer;
David Brazdil21c887c2022-09-23 12:25:18 +01001816 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001817 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
David Brazdil21c887c2022-09-23 12:25:18 +01001818 RpcTransportFd mFd, mBootstrapSocket;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001819 std::unique_ptr<RpcTransportCtx> mCtx;
1820 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1821 std::make_shared<RpcCertificateVerifierSimple>();
1822 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001823 // The function invoked after connection and handshake. By default, it is
1824 // |defaultPostConnect| that sends |kMessage| to the client.
1825 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1826 Server::defaultPostConnect;
1827
1828 void join() {
1829 if (mThread != nullptr) {
1830 mThread->join();
1831 mThread = nullptr;
1832 }
1833 }
1834
1835 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1836 FdTrigger* fdTrigger) {
1837 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001838 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001839 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001840 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001841 if (status != OK) return AssertionFailure() << statusToString(status);
1842 return AssertionSuccess();
1843 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001844 };
1845
1846 class Client {
1847 public:
1848 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1849 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001850 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001851 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1852 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001853 mFdTrigger = FdTrigger::make();
Andrei Homescuf30148c2023-03-10 00:31:45 +00001854 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001855 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1856 return AssertionSuccess();
1857 }
1858 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1859 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1860 return mCertVerifier;
1861 }
Yifan Hong67519322021-09-13 18:51:16 -07001862 // connect() and do handshake
1863 bool setUpTransport() {
1864 mFd = mConnectToServer();
Pawan49d74cb2022-08-03 21:19:11 +00001865 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
Yifan Hong67519322021-09-13 18:51:16 -07001866 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1867 return mClientTransport != nullptr;
1868 }
1869 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1870 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1871 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001872 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001873 status_t readStatus =
1874 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00001875 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001876 if (readStatus != OK) {
1877 return AssertionFailure() << statusToString(readStatus);
1878 }
1879 if (readMessage != expectedMessage) {
1880 return AssertionFailure()
1881 << "Expected " << expectedMessage << ", actual " << readMessage;
1882 }
1883 return AssertionSuccess();
1884 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001885 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001886 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001887 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1888 return;
1889 }
1890 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001891 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001892 }
1893
Pawan49d74cb2022-08-03 21:19:11 +00001894 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1895
Yifan Hong1deca4b2021-09-10 16:16:44 -07001896 private:
1897 ConnectToServer mConnectToServer;
Pawan3e0061c2022-08-26 21:08:34 +00001898 RpcTransportFd mFd;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001899 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1900 std::unique_ptr<RpcTransportCtx> mCtx;
1901 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1902 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001903 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001904 };
1905
1906 // Make A trust B.
1907 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001908 static status_t trust(RpcSecurity rpcSecurity,
1909 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1910 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001911 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001912 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1913 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1914 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001915 }
1916
1917 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001918};
1919
1920class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1921public:
1922 using Server = RpcTransportTestUtils::Server;
1923 using Client = RpcTransportTestUtils::Client;
1924 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001925 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Andrei Homescuf30148c2023-03-10 00:31:45 +00001926 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001927 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00001928 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001929 return ret;
1930 }
1931 static std::vector<ParamType> getRpcTranportTestParams() {
1932 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00001933 for (auto serverVersion : testVersions()) {
1934 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1935 for (auto rpcSecurity : RpcSecurityValues()) {
1936 switch (rpcSecurity) {
1937 case RpcSecurity::RAW: {
1938 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1939 } break;
1940 case RpcSecurity::TLS: {
1941 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1942 serverVersion);
1943 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1944 serverVersion);
1945 } break;
1946 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001947 }
1948 }
1949 }
1950 return ret;
1951 }
1952 template <typename A, typename B>
1953 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001954 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1955 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001956 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1957 }
Andrei Homescu12106de2022-04-27 04:42:21 +00001958 void SetUp() override {
1959 if constexpr (!kEnableRpcThreads) {
1960 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1961 }
1962 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001963};
1964
1965TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001966 auto server = std::make_unique<Server>();
1967 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001968
1969 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001970 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001971
1972 ASSERT_EQ(OK, trust(&client, server));
1973 ASSERT_EQ(OK, trust(server, &client));
1974
1975 server->start();
1976 client.run();
1977}
1978
1979TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001980 auto server = std::make_unique<Server>();
1981 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001982
1983 std::vector<Client> clients;
1984 for (int i = 0; i < 2; i++) {
1985 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001986 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001987 ASSERT_EQ(OK, trust(&client, server));
1988 ASSERT_EQ(OK, trust(server, &client));
1989 }
1990
1991 server->start();
1992 for (auto& client : clients) client.run();
1993}
1994
1995TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001996 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1997 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001998
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001999 auto untrustedServer = std::make_unique<Server>();
2000 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002001
2002 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002003 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002004
2005 ASSERT_EQ(OK, trust(untrustedServer, &client));
2006
2007 untrustedServer->start();
2008
2009 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2010 // the client can't verify the server's identity.
2011 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2012 client.run(handshakeOk);
2013}
2014TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002015 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2016 (void)serverVersion;
2017
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002018 auto validServer = std::make_unique<Server>();
2019 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002020
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002021 auto maliciousServer = std::make_unique<Server>();
2022 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002023
2024 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002025 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002026
2027 ASSERT_EQ(OK, trust(&client, validServer));
2028 ASSERT_EQ(OK, trust(validServer, &client));
2029 ASSERT_EQ(OK, trust(maliciousServer, &client));
2030
2031 maliciousServer->start();
2032
2033 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2034 // the client can't verify the server's identity.
2035 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2036 client.run(handshakeOk);
2037}
2038
2039TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002040 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2041 (void)serverVersion;
2042
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002043 auto server = std::make_unique<Server>();
2044 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002045
2046 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002047 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002048
2049 ASSERT_EQ(OK, trust(&client, server));
2050
2051 server->start();
2052
2053 // For TLS, Client should be able to verify server's identity, so client should see
2054 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2055 // identity and should drop the connection, so client shouldn't be able to read anything.
2056 bool readOk = rpcSecurity != RpcSecurity::TLS;
2057 client.run(true, readOk);
2058}
2059
2060TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002061 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2062 (void)serverVersion;
2063
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002064 auto server = std::make_unique<Server>();
2065 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002066
2067 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002068 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002069 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002070 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002071
2072 ASSERT_EQ(OK, trust(&validClient, server));
2073 ASSERT_EQ(OK, trust(&maliciousClient, server));
2074
2075 server->start();
2076
2077 // See UntrustedClient.
2078 bool readOk = rpcSecurity != RpcSecurity::TLS;
2079 maliciousClient.run(true, readOk);
2080}
2081
Yifan Hong67519322021-09-13 18:51:16 -07002082TEST_P(RpcTransportTest, Trigger) {
2083 std::string msg2 = ", world!";
2084 std::mutex writeMutex;
2085 std::condition_variable writeCv;
2086 bool shouldContinueWriting = false;
2087 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002088 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002089 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002090 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2091 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002092 if (status != OK) return AssertionFailure() << statusToString(status);
2093
2094 {
2095 std::unique_lock<std::mutex> lock(writeMutex);
2096 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2097 return AssertionFailure() << "write barrier not cleared in time!";
2098 }
2099 }
2100
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002101 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002102 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2103 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002104 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002105 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002106 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002107 << statusToString(status);
2108 return AssertionSuccess();
2109 };
2110
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002111 auto server = std::make_unique<Server>();
2112 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002113
2114 // Set up client
2115 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002116 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002117
2118 // Exchange keys
2119 ASSERT_EQ(OK, trust(&client, server));
2120 ASSERT_EQ(OK, trust(server, &client));
2121
2122 server->setPostConnect(serverPostConnect);
2123
Yifan Hong67519322021-09-13 18:51:16 -07002124 server->start();
2125 // connect() to server and do handshake
2126 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002127 // read the first message. This ensures that server has finished handshake and start handling
2128 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002129 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002130 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2131 // write is on an FdTrigger that has been shut down.
2132 server->shutdown();
2133 // Continues server thread to write the second message.
2134 {
Yifan Hong22211f82021-09-14 12:32:25 -07002135 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002136 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002137 }
Yifan Hong22211f82021-09-14 12:32:25 -07002138 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002139 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002140 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002141 // On the client side, second read fails with DEAD_OBJECT
2142 ASSERT_FALSE(client.readMessage(msg2));
2143}
2144
Pawan49d74cb2022-08-03 21:19:11 +00002145TEST_P(RpcTransportTest, CheckWaitingForRead) {
2146 std::mutex readMutex;
2147 std::condition_variable readCv;
2148 bool shouldContinueReading = false;
2149 // Server will write data on transport once its started
2150 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
2151 std::string message(RpcTransportTestUtils::kMessage);
2152 iovec messageIov{message.data(), message.size()};
2153 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2154 std::nullopt, nullptr);
2155 if (status != OK) return AssertionFailure() << statusToString(status);
2156
2157 {
2158 std::unique_lock<std::mutex> lock(readMutex);
2159 shouldContinueReading = true;
2160 lock.unlock();
2161 readCv.notify_all();
2162 }
2163 return AssertionSuccess();
2164 };
2165
2166 // Setup Server and client
2167 auto server = std::make_unique<Server>();
2168 ASSERT_TRUE(server->setUp(GetParam()));
2169
2170 Client client(server->getConnectToServerFn());
2171 ASSERT_TRUE(client.setUp(GetParam()));
2172
2173 ASSERT_EQ(OK, trust(&client, server));
2174 ASSERT_EQ(OK, trust(server, &client));
2175 server->setPostConnect(serverPostConnect);
2176
2177 server->start();
2178 ASSERT_TRUE(client.setUpTransport());
2179 {
2180 // Wait till server writes data
2181 std::unique_lock<std::mutex> lock(readMutex);
2182 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2183 }
2184
2185 // Since there is no read polling here, we will get polling count 0
2186 ASSERT_FALSE(client.isTransportWaiting());
2187 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2188 // Thread should increment polling count, read and decrement polling count
2189 // Again, polling count should be zero here
2190 ASSERT_FALSE(client.isTransportWaiting());
2191
2192 server->shutdown();
2193}
2194
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002195INSTANTIATE_TEST_SUITE_P(BinderRpc, RpcTransportTest,
2196 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
2197 RpcTransportTest::PrintParamInfo);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002198
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002199class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002200 : public testing::TestWithParam<
2201 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002202public:
2203 template <typename A, typename B>
2204 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002205 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2206 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002207 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2208 }
2209 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002210 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2211 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2212 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002213 };
2214};
2215
2216TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002217 if constexpr (!kEnableRpcThreads) {
2218 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2219 }
2220
Frederick Mayledc07cf82022-05-26 20:30:12 +00002221 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002222
2223 std::vector<uint8_t> pkeyData, certData;
2224 {
2225 auto pkey = makeKeyPairForSelfSignedCert();
2226 ASSERT_NE(nullptr, pkey);
2227 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2228 ASSERT_NE(nullptr, cert);
2229 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2230 certData = serializeCertificate(cert.get(), certificateFormat);
2231 }
2232
2233 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2234 auto desCert = deserializeCertificate(certData, certificateFormat);
2235 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002236 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2237 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002238
2239 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2240 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2241
2242 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2243 ASSERT_TRUE(client.setUp(utilsParam));
2244
2245 ASSERT_EQ(OK, trust(&client, server));
2246 ASSERT_EQ(OK, trust(server, &client));
2247
2248 server->start();
2249 client.run();
2250}
2251
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002252INSTANTIATE_TEST_SUITE_P(
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002253 BinderRpc, RpcTransportTlsKeyTest,
2254 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2255 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002256 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2257 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002258 RpcTransportTlsKeyTest::PrintParamInfo);
Andrei Homescud65666d2023-03-03 07:28:02 +00002259#endif // BINDER_RPC_TO_TRUSTY_TEST
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002260
Steven Morelandc1635952021-04-01 16:20:47 +00002261} // namespace android
2262
2263int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002264 ::testing::InitGoogleTest(&argc, argv);
Tomasz Wasilczyke3de8802023-11-01 11:05:27 -07002265 __android_log_set_logger(__android_log_stderr_logger);
Steven Morelanda83191d2021-10-27 10:14:53 -07002266
Steven Moreland5553ac42020-11-11 02:14:45 +00002267 return RUN_ALL_TESTS();
2268}