1 /*
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
17 #ifndef __ANDROID_VENDOR__
18 // only used on NDK tests outside of vendor
19 #include <aidl/IBinderRpcTest.h>
20 #endif
21
22 #include <chrono>
23 #include <cstdlib>
24 #include <iostream>
25 #include <thread>
26 #include <type_traits>
27
28 #include <dirent.h>
29 #include <dlfcn.h>
30 #include <poll.h>
31 #include <sys/prctl.h>
32 #include <sys/socket.h>
33
34 #ifdef BINDER_RPC_TO_TRUSTY_TEST
35 #include <binder/RpcTransportTipcAndroid.h>
36 #include <trusty/tipc.h>
37 #endif // BINDER_RPC_TO_TRUSTY_TEST
38
39 #include "../Utils.h"
40 #include "binderRpcTestCommon.h"
41 #include "binderRpcTestFixture.h"
42
43 using namespace std::chrono_literals;
44 using namespace std::placeholders;
45 using android::binder::borrowed_fd;
46 using android::binder::GetExecutableDirectory;
47 using android::binder::ReadFdToString;
48 using android::binder::unique_fd;
49 using testing::AssertionFailure;
50 using testing::AssertionResult;
51 using testing::AssertionSuccess;
52
53 namespace android {
54
55 #ifdef BINDER_TEST_NO_SHARED_LIBS
56 constexpr bool kEnableSharedLibs = false;
57 #else
58 constexpr bool kEnableSharedLibs = true;
59 #endif
60
61 #ifdef BINDER_RPC_TO_TRUSTY_TEST
62 constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0";
63 #endif
64
WaitStatusToString(int wstatus)65 static std::string WaitStatusToString(int wstatus) {
66 if (WIFEXITED(wstatus)) {
67 return "exit status " + std::to_string(WEXITSTATUS(wstatus));
68 }
69 if (WIFSIGNALED(wstatus)) {
70 return "term signal " + std::to_string(WTERMSIG(wstatus));
71 }
72 return "unexpected state " + std::to_string(wstatus);
73 }
74
debugBacktrace(pid_t pid)75 static void debugBacktrace(pid_t pid) {
76 std::cerr << "TAKING BACKTRACE FOR PID " << pid << std::endl;
77 system((std::string("debuggerd -b ") + std::to_string(pid)).c_str());
78 }
79
80 class Process {
81 public:
Process(Process && other)82 Process(Process&& other)
83 : mCustomExitStatusCheck(std::move(other.mCustomExitStatusCheck)),
84 mReadEnd(std::move(other.mReadEnd)),
85 mWriteEnd(std::move(other.mWriteEnd)) {
86 // The default move constructor doesn't clear mPid after moving it,
87 // which we need to do because the destructor checks for mPid!=0
88 mPid = other.mPid;
89 other.mPid = 0;
90 }
Process(const std::function<void (borrowed_fd,borrowed_fd)> & f)91 Process(const std::function<void(borrowed_fd /* writeEnd */, borrowed_fd /* readEnd */)>& f) {
92 unique_fd childWriteEnd;
93 unique_fd childReadEnd;
94 if (!binder::Pipe(&mReadEnd, &childWriteEnd, 0)) PLOGF("child write pipe failed");
95 if (!binder::Pipe(&childReadEnd, &mWriteEnd, 0)) PLOGF("child read pipe failed");
96 if (0 == (mPid = fork())) {
97 // racey: assume parent doesn't crash before this is set
98 prctl(PR_SET_PDEATHSIG, SIGHUP);
99
100 f(childWriteEnd, childReadEnd);
101
102 exit(0);
103 }
104 }
~Process()105 ~Process() {
106 if (mPid != 0) {
107 int wstatus;
108 waitpid(mPid, &wstatus, 0);
109 if (mCustomExitStatusCheck) {
110 mCustomExitStatusCheck(wstatus);
111 } else {
112 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
113 << "server process failed: " << WaitStatusToString(wstatus);
114 }
115 }
116 }
readEnd()117 borrowed_fd readEnd() { return mReadEnd; }
writeEnd()118 borrowed_fd writeEnd() { return mWriteEnd; }
119
setCustomExitStatusCheck(std::function<void (int wstatus)> f)120 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
121 mCustomExitStatusCheck = std::move(f);
122 }
123
124 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
terminate()125 void terminate() { kill(mPid, SIGTERM); }
126
getPid()127 pid_t getPid() { return mPid; }
128
129 private:
130 std::function<void(int wstatus)> mCustomExitStatusCheck;
131 pid_t mPid = 0;
132 unique_fd mReadEnd;
133 unique_fd mWriteEnd;
134 };
135
allocateSocketAddress()136 static std::string allocateSocketAddress() {
137 static size_t id = 0;
138 std::string temp = getenv("TMPDIR") ?: "/tmp";
139 auto ret = temp + "/binderRpcTest_" + std::to_string(getpid()) + "_" + std::to_string(id++);
140 unlink(ret.c_str());
141 return ret;
142 };
143
allocateVsockPort()144 static unsigned int allocateVsockPort() {
145 static unsigned int vsockPort = 34567;
146 return vsockPort++;
147 }
148
initUnixSocket(std::string addr)149 static unique_fd initUnixSocket(std::string addr) {
150 auto socket_addr = UnixSocketAddress(addr.c_str());
151 unique_fd fd(TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
152 if (!fd.ok()) PLOGF("initUnixSocket failed to create socket");
153 if (0 != TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize()))) {
154 PLOGF("initUnixSocket failed to bind");
155 }
156 return fd;
157 }
158
159 // Destructors need to be defined, even if pure virtual
~ProcessSession()160 ProcessSession::~ProcessSession() {}
161
162 class LinuxProcessSession : public ProcessSession {
163 public:
164 // reference to process hosting a socket server
165 Process host;
166
167 LinuxProcessSession(LinuxProcessSession&&) = default;
LinuxProcessSession(Process && host)168 LinuxProcessSession(Process&& host) : host(std::move(host)) {}
~LinuxProcessSession()169 ~LinuxProcessSession() override {
170 for (auto& session : sessions) {
171 session.root = nullptr;
172 }
173
174 for (size_t sessionNum = 0; sessionNum < sessions.size(); sessionNum++) {
175 auto& info = sessions.at(sessionNum);
176 sp<RpcSession>& session = info.session;
177
178 EXPECT_NE(nullptr, session);
179 EXPECT_NE(nullptr, session->state());
180 EXPECT_EQ(0u, session->state()->countBinders()) << (session->state()->dump(), "dump:");
181
182 wp<RpcSession> weakSession = session;
183 session = nullptr;
184
185 // b/244325464 - 'getStrongCount' is printing '1' on failure here, which indicates the
186 // the object should not actually be promotable. By looping, we distinguish a race here
187 // from a bug causing the object to not be promotable.
188 for (size_t i = 0; i < 3; i++) {
189 sp<RpcSession> strongSession = weakSession.promote();
190 EXPECT_EQ(nullptr, strongSession)
191 << "For session " << sessionNum << ". "
192 << (debugBacktrace(host.getPid()), debugBacktrace(getpid()),
193 "Leaked sess: ")
194 << strongSession->getStrongCount() << " checked time " << i;
195
196 if (strongSession != nullptr) {
197 sleep(1);
198 }
199 }
200 }
201 }
202
setCustomExitStatusCheck(std::function<void (int wstatus)> f)203 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) override {
204 host.setCustomExitStatusCheck(std::move(f));
205 }
206
terminate()207 void terminate() override { host.terminate(); }
208 };
209
connectTo(const RpcSocketAddress & addr)210 static unique_fd connectTo(const RpcSocketAddress& addr) {
211 unique_fd serverFd(
212 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
213 if (!serverFd.ok()) {
214 PLOGF("Could not create socket %s", addr.toString().c_str());
215 }
216
217 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
218 PLOGF("Could not connect to socket %s", addr.toString().c_str());
219 }
220 return serverFd;
221 }
222
223 #ifndef BINDER_RPC_TO_TRUSTY_TEST
connectToUnixBootstrap(const RpcTransportFd & transportFd)224 static unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
225 unique_fd sockClient, sockServer;
226 if (!binder::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
227 PLOGF("Failed socketpair()");
228 }
229
230 int zero = 0;
231 iovec iov{&zero, sizeof(zero)};
232 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
233 fds.emplace_back(std::move(sockServer));
234
235 if (binder::os::sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
236 PLOGF("Failed sendMessageOnSocket");
237 }
238 return sockClient;
239 }
240 #endif // BINDER_RPC_TO_TRUSTY_TEST
241
newFactory(RpcSecurity rpcSecurity)242 std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSecurity) {
243 return newTlsFactory(rpcSecurity);
244 }
245
246 // This creates a new process serving an interface on a certain number of
247 // threads.
createRpcTestSocketServerProcessEtc(const BinderRpcOptions & options)248 std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc(
249 const BinderRpcOptions& options) {
250 LOG_ALWAYS_FATAL_IF(options.numSessions < 1, "Must have at least one session to a server");
251
252 if (options.numIncomingConnectionsBySession.size() != 0) {
253 LOG_ALWAYS_FATAL_IF(options.numIncomingConnectionsBySession.size() != options.numSessions,
254 "%s: %zu != %zu", __func__,
255 options.numIncomingConnectionsBySession.size(), options.numSessions);
256 }
257
258 SocketType socketType = GetParam().type;
259 RpcSecurity rpcSecurity = GetParam().security;
260 uint32_t clientVersion = GetParam().clientVersion;
261 uint32_t serverVersion = GetParam().serverVersion;
262 bool singleThreaded = GetParam().singleThreaded;
263 bool noKernel = GetParam().noKernel;
264
265 std::string path = GetExecutableDirectory();
266 auto servicePath = path + "/binder_rpc_test_service" +
267 (singleThreaded ? "_single_threaded" : "") + (noKernel ? "_no_kernel" : "");
268
269 unique_fd bootstrapClientFd, socketFd;
270
271 auto addr = allocateSocketAddress();
272 // Initializes the socket before the fork/exec.
273 if (socketType == SocketType::UNIX_RAW) {
274 socketFd = initUnixSocket(addr);
275 } else if (socketType == SocketType::UNIX_BOOTSTRAP) {
276 // Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
277 // This is because we cannot pass ParcelFileDescriptor over a pipe.
278 if (!binder::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
279 PLOGF("Failed socketpair()");
280 }
281 }
282
283 auto ret = std::make_unique<LinuxProcessSession>(
284 Process([=](borrowed_fd writeEnd, borrowed_fd readEnd) {
285 if (socketType == SocketType::TIPC) {
286 // Trusty has a single persistent service
287 return;
288 }
289
290 auto writeFd = std::to_string(writeEnd.get());
291 auto readFd = std::to_string(readEnd.get());
292 auto status = execl(servicePath.c_str(), servicePath.c_str(), writeFd.c_str(),
293 readFd.c_str(), NULL);
294 PLOGF("execl('%s', _, %s, %s) should not return at all, but it returned %d",
295 servicePath.c_str(), writeFd.c_str(), readFd.c_str(), status);
296 }));
297
298 BinderRpcTestServerConfig serverConfig;
299 serverConfig.numThreads = options.numThreads;
300 serverConfig.socketType = static_cast<int32_t>(socketType);
301 serverConfig.rpcSecurity = static_cast<int32_t>(rpcSecurity);
302 serverConfig.serverVersion = serverVersion;
303 serverConfig.vsockPort = allocateVsockPort();
304 serverConfig.addr = addr;
305 serverConfig.socketFd = socketFd.get();
306 for (auto mode : options.serverSupportedFileDescriptorTransportModes) {
307 serverConfig.serverSupportedFileDescriptorTransportModes.push_back(
308 static_cast<int32_t>(mode));
309 }
310 if (socketType != SocketType::TIPC) {
311 writeToFd(ret->host.writeEnd(), serverConfig);
312 }
313
314 std::vector<sp<RpcSession>> sessions;
315 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
316 for (size_t i = 0; i < options.numSessions; i++) {
317 std::unique_ptr<RpcTransportCtxFactory> factory;
318 if (socketType == SocketType::TIPC) {
319 #ifdef BINDER_RPC_TO_TRUSTY_TEST
320 factory = RpcTransportCtxFactoryTipcAndroid::make();
321 #else
322 LOG_ALWAYS_FATAL("TIPC socket type only supported on vendor");
323 #endif
324 } else {
325 factory = newTlsFactory(rpcSecurity, certVerifier);
326 }
327 sessions.emplace_back(RpcSession::make(std::move(factory)));
328 }
329
330 BinderRpcTestServerInfo serverInfo;
331 if (socketType != SocketType::TIPC) {
332 serverInfo = readFromFd<BinderRpcTestServerInfo>(ret->host.readEnd());
333 BinderRpcTestClientInfo clientInfo;
334 for (const auto& session : sessions) {
335 auto& parcelableCert = clientInfo.certs.emplace_back();
336 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
337 }
338 writeToFd(ret->host.writeEnd(), clientInfo);
339
340 LOG_ALWAYS_FATAL_IF(serverInfo.port > std::numeric_limits<unsigned int>::max());
341 if (socketType == SocketType::INET) {
342 LOG_ALWAYS_FATAL_IF(0 == serverInfo.port);
343 }
344
345 if (rpcSecurity == RpcSecurity::TLS) {
346 const auto& serverCert = serverInfo.cert.data;
347 LOG_ALWAYS_FATAL_IF(
348 OK !=
349 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM, serverCert));
350 }
351 }
352
353 status_t status;
354
355 for (size_t i = 0; i < sessions.size(); i++) {
356 const auto& session = sessions.at(i);
357
358 size_t numIncoming = options.numIncomingConnectionsBySession.size() > 0
359 ? options.numIncomingConnectionsBySession.at(i)
360 : 0;
361
362 LOG_ALWAYS_FATAL_IF(!session->setProtocolVersion(clientVersion));
363 session->setMaxIncomingThreads(numIncoming);
364 session->setMaxOutgoingConnections(options.numOutgoingConnections);
365 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
366
367 switch (socketType) {
368 case SocketType::PRECONNECTED:
369 status = session->setupPreconnectedClient({}, [=]() {
370 return connectTo(UnixSocketAddress(serverConfig.addr.c_str()));
371 });
372 break;
373 case SocketType::UNIX_RAW:
374 case SocketType::UNIX:
375 status = session->setupUnixDomainClient(serverConfig.addr.c_str());
376 break;
377 case SocketType::UNIX_BOOTSTRAP:
378 status = session->setupUnixDomainSocketBootstrapClient(
379 unique_fd(dup(bootstrapClientFd.get())));
380 break;
381 case SocketType::VSOCK:
382 status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
383 break;
384 case SocketType::INET:
385 status = session->setupInetClient("127.0.0.1", serverInfo.port);
386 break;
387 case SocketType::TIPC:
388 status = session->setupPreconnectedClient({}, [=]() {
389 #ifdef BINDER_RPC_TO_TRUSTY_TEST
390 auto port = trustyIpcPort(serverVersion);
391 for (size_t i = 0; i < 5; i++) {
392 // Try to connect several times,
393 // in case the service is slow to start
394 int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
395 if (tipcFd >= 0) {
396 return unique_fd(tipcFd);
397 }
398 usleep(50000);
399 }
400 return unique_fd();
401 #else
402 LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
403 return unique_fd();
404 #endif
405 });
406 break;
407 default:
408 LOG_ALWAYS_FATAL("Unknown socket type");
409 }
410 if (options.allowConnectFailure && status != OK) {
411 ret->sessions.clear();
412 break;
413 }
414 LOG_ALWAYS_FATAL_IF(status != OK, "Could not connect: %s", statusToString(status).c_str());
415 ret->sessions.push_back({session, session->getRootObject()});
416 }
417 return ret;
418 }
419
TEST_P(BinderRpc,ThreadPoolGreaterThanEqualRequested)420 TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
421 if (clientOrServerSingleThreaded()) {
422 GTEST_SKIP() << "This test requires multiple threads";
423 }
424
425 constexpr size_t kNumThreads = 10;
426
427 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
428
429 EXPECT_OK(proc.rootIface->lock());
430
431 // block all but one thread taking locks
432 std::vector<std::thread> ts;
433 for (size_t i = 0; i < kNumThreads - 1; i++) {
434 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
435 }
436
437 usleep(100000); // give chance for calls on other threads
438
439 // other calls still work
440 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
441
442 constexpr size_t blockTimeMs = 100;
443 size_t epochMsBefore = epochMillis();
444 // after this, we should never see a response within this time
445 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
446
447 // this call should be blocked for blockTimeMs
448 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
449
450 size_t epochMsAfter = epochMillis();
451 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
452
453 for (auto& t : ts) t.join();
454 }
455
testThreadPoolOverSaturated(sp<IBinderRpcTest> iface,size_t numCalls,size_t sleepMs)456 static void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls, size_t sleepMs) {
457 size_t epochMsBefore = epochMillis();
458
459 std::vector<std::thread> ts;
460 for (size_t i = 0; i < numCalls; i++) {
461 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
462 }
463
464 for (auto& t : ts) t.join();
465
466 size_t epochMsAfter = epochMillis();
467
468 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
469
470 // Potential flake, but make sure calls are handled in parallel. Due
471 // to past flakes, this only checks that the amount of time taken has
472 // some parallelism. Other tests such as ThreadPoolGreaterThanEqualRequested
473 // check this more exactly.
474 EXPECT_LE(epochMsAfter, epochMsBefore + (numCalls - 1) * sleepMs);
475 }
476
TEST_P(BinderRpc,ThreadPoolOverSaturated)477 TEST_P(BinderRpc, ThreadPoolOverSaturated) {
478 if (clientOrServerSingleThreaded()) {
479 GTEST_SKIP() << "This test requires multiple threads";
480 }
481
482 constexpr size_t kNumThreads = 10;
483 constexpr size_t kNumCalls = kNumThreads + 3;
484 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
485
486 // b/272429574 - below 500ms, the test fails
487 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
488 }
489
TEST_P(BinderRpc,ThreadPoolLimitOutgoing)490 TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
491 if (clientOrServerSingleThreaded()) {
492 GTEST_SKIP() << "This test requires multiple threads";
493 }
494
495 constexpr size_t kNumThreads = 20;
496 constexpr size_t kNumOutgoingConnections = 10;
497 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
498 auto proc = createRpcTestSocketServerProcess(
499 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
500
501 // b/272429574 - below 500ms, the test fails
502 testThreadPoolOverSaturated(proc.rootIface, kNumCalls, 500 /*ms*/);
503 }
504
TEST_P(BinderRpc,ThreadingStressTest)505 TEST_P(BinderRpc, ThreadingStressTest) {
506 if (clientOrServerSingleThreaded()) {
507 GTEST_SKIP() << "This test requires multiple threads";
508 }
509
510 constexpr size_t kNumClientThreads = 5;
511 constexpr size_t kNumServerThreads = 5;
512 constexpr size_t kNumCalls = 50;
513
514 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
515
516 std::vector<std::thread> threads;
517 for (size_t i = 0; i < kNumClientThreads; i++) {
518 threads.push_back(std::thread([&] {
519 for (size_t j = 0; j < kNumCalls; j++) {
520 sp<IBinder> out;
521 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
522 EXPECT_EQ(proc.rootBinder, out);
523 }
524 }));
525 }
526
527 for (auto& t : threads) t.join();
528 }
529
saturateThreadPool(size_t threadCount,const sp<IBinderRpcTest> & iface)530 static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
531 std::vector<std::thread> threads;
532 for (size_t i = 0; i < threadCount; i++) {
533 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
534 }
535 for (auto& t : threads) t.join();
536 }
537
TEST_P(BinderRpc,OnewayStressTest)538 TEST_P(BinderRpc, OnewayStressTest) {
539 if (clientOrServerSingleThreaded()) {
540 GTEST_SKIP() << "This test requires multiple threads";
541 }
542
543 constexpr size_t kNumClientThreads = 10;
544 constexpr size_t kNumServerThreads = 10;
545 constexpr size_t kNumCalls = 1000;
546
547 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
548
549 std::vector<std::thread> threads;
550 for (size_t i = 0; i < kNumClientThreads; i++) {
551 threads.push_back(std::thread([&] {
552 for (size_t j = 0; j < kNumCalls; j++) {
553 EXPECT_OK(proc.rootIface->sendString("a"));
554 }
555 }));
556 }
557
558 for (auto& t : threads) t.join();
559
560 saturateThreadPool(kNumServerThreads, proc.rootIface);
561 }
562
TEST_P(BinderRpc,OnewayCallQueueingWithFds)563 TEST_P(BinderRpc, OnewayCallQueueingWithFds) {
564 if (!supportsFdTransport()) {
565 GTEST_SKIP() << "Would fail trivially (which is tested elsewhere)";
566 }
567 if (clientOrServerSingleThreaded()) {
568 GTEST_SKIP() << "This test requires multiple threads";
569 }
570
571 constexpr size_t kNumServerThreads = 3;
572
573 // This test forces a oneway transaction to be queued by issuing two
574 // `blockingSendFdOneway` calls, then drains the queue by issuing two
575 // `blockingRecvFd` calls.
576 //
577 // For more details about the queuing semantics see
578 // https://developer.android.com/reference/android/os/IBinder#FLAG_ONEWAY
579
580 auto proc = createRpcTestSocketServerProcess({
581 .numThreads = kNumServerThreads,
582 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
583 .serverSupportedFileDescriptorTransportModes =
584 {RpcSession::FileDescriptorTransportMode::UNIX},
585 });
586
587 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
588 android::os::ParcelFileDescriptor(mockFileDescriptor("a"))));
589 EXPECT_OK(proc.rootIface->blockingSendFdOneway(
590 android::os::ParcelFileDescriptor(mockFileDescriptor("b"))));
591
592 android::os::ParcelFileDescriptor fdA;
593 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
594 std::string result;
595 ASSERT_TRUE(ReadFdToString(fdA.get(), &result));
596 EXPECT_EQ(result, "a");
597
598 android::os::ParcelFileDescriptor fdB;
599 EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
600 ASSERT_TRUE(ReadFdToString(fdB.get(), &result));
601 EXPECT_EQ(result, "b");
602
603 saturateThreadPool(kNumServerThreads, proc.rootIface);
604 }
605
TEST_P(BinderRpc,OnewayCallQueueing)606 TEST_P(BinderRpc, OnewayCallQueueing) {
607 if (clientOrServerSingleThreaded()) {
608 GTEST_SKIP() << "This test requires multiple threads";
609 }
610
611 constexpr size_t kNumQueued = 10;
612 constexpr size_t kNumExtraServerThreads = 4;
613
614 // make sure calls to the same object happen on the same thread
615 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
616
617 // all these *Oneway commands should be queued on the server sequentially,
618 // even though there are multiple threads.
619 for (size_t i = 0; i + 1 < kNumQueued; i++) {
620 proc.rootIface->blockingSendIntOneway(i);
621 }
622 for (size_t i = 0; i + 1 < kNumQueued; i++) {
623 int n;
624 proc.rootIface->blockingRecvInt(&n);
625 EXPECT_EQ(n, static_cast<ssize_t>(i));
626 }
627
628 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
629 }
630
TEST_P(BinderRpc,OnewayCallExhaustion)631 TEST_P(BinderRpc, OnewayCallExhaustion) {
632 if (clientOrServerSingleThreaded()) {
633 GTEST_SKIP() << "This test requires multiple threads";
634 }
635
636 constexpr size_t kNumClients = 2;
637 constexpr size_t kTooLongMs = 1000;
638
639 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
640
641 // Build up oneway calls on the second session to make sure it terminates
642 // and shuts down. The first session should be unaffected (proc destructor
643 // checks the first session).
644 auto iface = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
645
646 std::vector<std::thread> threads;
647 for (size_t i = 0; i < kNumClients; i++) {
648 // one of these threads will get stuck queueing a transaction once the
649 // socket fills up, the other will be able to fill up transactions on
650 // this object
651 threads.push_back(std::thread([&] {
652 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
653 }
654 }));
655 }
656 for (auto& t : threads) t.join();
657
658 Status status = iface->sleepMsAsync(kTooLongMs);
659 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
660
661 // now that it has died, wait for the remote session to shutdown
662 std::vector<int32_t> remoteCounts;
663 do {
664 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
665 } while (remoteCounts.size() == kNumClients);
666
667 // the second session should be shutdown in the other process by the time we
668 // are able to join above (it'll only be hung up once it finishes processing
669 // any pending commands). We need to erase this session from the record
670 // here, so that the destructor for our session won't check that this
671 // session is valid, but we still want it to test the other session.
672 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
673 }
674
TEST_P(BinderRpc,SessionWithIncomingThreadpoolDoesntLeak)675 TEST_P(BinderRpc, SessionWithIncomingThreadpoolDoesntLeak) {
676 if (clientOrServerSingleThreaded()) {
677 GTEST_SKIP() << "This test requires multiple threads";
678 }
679
680 // session 0 - will check for leaks in destrutor of proc
681 // session 1 - we want to make sure it gets deleted when we drop all references to it
682 auto proc = createRpcTestSocketServerProcess(
683 {.numThreads = 1, .numSessions = 2, .numIncomingConnectionsBySession = {0, 1}});
684
685 wp<RpcSession> session = proc.proc->sessions.at(1).session;
686
687 // remove all references to the second session
688 proc.proc->sessions.at(1).root = nullptr;
689 proc.proc->sessions.erase(proc.proc->sessions.begin() + 1);
690
691 // TODO(b/271830568) more efficient way to wait for other incoming threadpool
692 // to drain commands.
693 for (size_t i = 0; i < 100; i++) {
694 usleep(10 * 1000);
695 if (session.promote() == nullptr) break;
696 }
697
698 EXPECT_EQ(nullptr, session.promote());
699
700 // now that it has died, wait for the remote session to shutdown
701 std::vector<int32_t> remoteCounts;
702 do {
703 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
704 } while (remoteCounts.size() > 1);
705 }
706
TEST_P(BinderRpc,SingleDeathRecipient)707 TEST_P(BinderRpc, SingleDeathRecipient) {
708 if (clientOrServerSingleThreaded()) {
709 GTEST_SKIP() << "This test requires multiple threads";
710 }
711 class MyDeathRec : public IBinder::DeathRecipient {
712 public:
713 void binderDied(const wp<IBinder>& /* who */) override {
714 dead = true;
715 mCv.notify_one();
716 }
717 std::mutex mMtx;
718 std::condition_variable mCv;
719 bool dead = false;
720 };
721
722 // Death recipient needs to have an incoming connection to be called
723 auto proc = createRpcTestSocketServerProcess(
724 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
725
726 auto dr = sp<MyDeathRec>::make();
727 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
728
729 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
730 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
731 }
732
733 std::unique_lock<std::mutex> lock(dr->mMtx);
734 ASSERT_TRUE(dr->mCv.wait_for(lock, 100ms, [&]() { return dr->dead; }));
735
736 // need to wait for the session to shutdown so we don't "Leak session"
737 // can't do this before checking the death recipient by calling
738 // forceShutdown earlier, because shutdownAndWait will also trigger
739 // a death recipient, but if we had a way to wait for the service
740 // to gracefully shutdown, we could use that here.
741 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
742 proc.expectAlreadyShutdown = true;
743 }
744
TEST_P(BinderRpc,SingleDeathRecipientOnShutdown)745 TEST_P(BinderRpc, SingleDeathRecipientOnShutdown) {
746 if (clientOrServerSingleThreaded()) {
747 GTEST_SKIP() << "This test requires multiple threads";
748 }
749 class MyDeathRec : public IBinder::DeathRecipient {
750 public:
751 void binderDied(const wp<IBinder>& /* who */) override {
752 dead = true;
753 mCv.notify_one();
754 }
755 std::mutex mMtx;
756 std::condition_variable mCv;
757 bool dead = false;
758 };
759
760 // Death recipient needs to have an incoming connection to be called
761 auto proc = createRpcTestSocketServerProcess(
762 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
763
764 auto dr = sp<MyDeathRec>::make();
765 EXPECT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
766
767 // Explicitly calling shutDownAndWait will cause the death recipients
768 // to be called.
769 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
770
771 std::unique_lock<std::mutex> lock(dr->mMtx);
772 if (!dr->dead) {
773 EXPECT_EQ(std::cv_status::no_timeout, dr->mCv.wait_for(lock, 100ms));
774 }
775 EXPECT_TRUE(dr->dead) << "Failed to receive the death notification.";
776
777 proc.proc->terminate();
778 proc.proc->setCustomExitStatusCheck([](int wstatus) {
779 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
780 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
781 });
782 proc.expectAlreadyShutdown = true;
783 }
784
TEST_P(BinderRpc,DeathRecipientFailsWithoutIncoming)785 TEST_P(BinderRpc, DeathRecipientFailsWithoutIncoming) {
786 if (socketType() == SocketType::TIPC) {
787 // This should work, but Trusty takes too long to restart the service
788 GTEST_SKIP() << "Service death test not supported on Trusty";
789 }
790 class MyDeathRec : public IBinder::DeathRecipient {
791 public:
792 void binderDied(const wp<IBinder>& /* who */) override {}
793 };
794
795 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 1});
796
797 auto dr = sp<MyDeathRec>::make();
798 EXPECT_EQ(INVALID_OPERATION, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
799 }
800
TEST_P(BinderRpc,UnlinkDeathRecipient)801 TEST_P(BinderRpc, UnlinkDeathRecipient) {
802 if (clientOrServerSingleThreaded()) {
803 GTEST_SKIP() << "This test requires multiple threads";
804 }
805 class MyDeathRec : public IBinder::DeathRecipient {
806 public:
807 void binderDied(const wp<IBinder>& /* who */) override {
808 GTEST_FAIL() << "This should not be called after unlinkToDeath";
809 }
810 };
811
812 // Death recipient needs to have an incoming connection to be called
813 auto proc = createRpcTestSocketServerProcess(
814 {.numThreads = 1, .numSessions = 1, .numIncomingConnectionsBySession = {1}});
815
816 auto dr = sp<MyDeathRec>::make();
817 ASSERT_EQ(OK, proc.rootBinder->linkToDeath(dr, (void*)1, 0));
818 ASSERT_EQ(OK, proc.rootBinder->unlinkToDeath(dr, (void*)1, 0, nullptr));
819
820 proc.forceShutdown();
821 }
822
TEST_P(BinderRpc,Die)823 TEST_P(BinderRpc, Die) {
824 if (socketType() == SocketType::TIPC) {
825 // This should work, but Trusty takes too long to restart the service
826 GTEST_SKIP() << "Service death test not supported on Trusty";
827 }
828
829 for (bool doDeathCleanup : {true, false}) {
830 auto proc = createRpcTestSocketServerProcess({});
831
832 // make sure there is some state during crash
833 // 1. we hold their binder
834 sp<IBinderRpcSession> session;
835 EXPECT_OK(proc.rootIface->openSession("happy", &session));
836 // 2. they hold our binder
837 sp<IBinder> binder = new BBinder();
838 EXPECT_OK(proc.rootIface->holdBinder(binder));
839
840 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
841 << "Do death cleanup: " << doDeathCleanup;
842
843 proc.proc->setCustomExitStatusCheck([](int wstatus) {
844 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
845 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
846 });
847 proc.expectAlreadyShutdown = true;
848 }
849 }
850
TEST_P(BinderRpc,UseKernelBinderCallingId)851 TEST_P(BinderRpc, UseKernelBinderCallingId) {
852 // This test only works if the current process shared the internal state of
853 // ProcessState with the service across the call to fork(). Both the static
854 // libraries and libbinder.so have their own separate copies of all the
855 // globals, so the test only works when the test client and service both use
856 // libbinder.so (when using static libraries, even a client and service
857 // using the same kind of static library should have separate copies of the
858 // variables).
859 if (!kEnableSharedLibs || serverSingleThreaded() || noKernel()) {
860 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
861 "at build time.";
862 }
863
864 auto proc = createRpcTestSocketServerProcess({});
865
866 // we can't allocate IPCThreadState so actually the first time should
867 // succeed :(
868 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
869
870 // second time! we catch the error :)
871 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
872
873 proc.proc->setCustomExitStatusCheck([](int wstatus) {
874 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
875 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
876 });
877 proc.expectAlreadyShutdown = true;
878 }
879
TEST_P(BinderRpc,FileDescriptorTransportRejectNone)880 TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
881 if (socketType() == SocketType::TIPC) {
882 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
883 }
884
885 auto proc = createRpcTestSocketServerProcess({
886 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
887 .serverSupportedFileDescriptorTransportModes =
888 {RpcSession::FileDescriptorTransportMode::UNIX},
889 .allowConnectFailure = true,
890 });
891 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
892 proc.proc->terminate();
893 proc.proc->setCustomExitStatusCheck([](int wstatus) {
894 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
895 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
896 });
897 proc.expectAlreadyShutdown = true;
898 }
899
TEST_P(BinderRpc,FileDescriptorTransportRejectUnix)900 TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
901 if (socketType() == SocketType::TIPC) {
902 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
903 }
904
905 auto proc = createRpcTestSocketServerProcess({
906 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
907 .serverSupportedFileDescriptorTransportModes =
908 {RpcSession::FileDescriptorTransportMode::NONE},
909 .allowConnectFailure = true,
910 });
911 EXPECT_TRUE(proc.proc->sessions.empty()) << "session connections should have failed";
912 proc.proc->terminate();
913 proc.proc->setCustomExitStatusCheck([](int wstatus) {
914 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
915 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
916 });
917 proc.expectAlreadyShutdown = true;
918 }
919
TEST_P(BinderRpc,FileDescriptorTransportOptionalUnix)920 TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
921 if (socketType() == SocketType::TIPC) {
922 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
923 }
924
925 auto proc = createRpcTestSocketServerProcess({
926 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
927 .serverSupportedFileDescriptorTransportModes =
928 {RpcSession::FileDescriptorTransportMode::NONE,
929 RpcSession::FileDescriptorTransportMode::UNIX},
930 });
931
932 android::os::ParcelFileDescriptor out;
933 auto status = proc.rootIface->echoAsFile("hello", &out);
934 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
935 }
936
TEST_P(BinderRpc,ReceiveFile)937 TEST_P(BinderRpc, ReceiveFile) {
938 if (socketType() == SocketType::TIPC) {
939 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
940 }
941
942 auto proc = createRpcTestSocketServerProcess({
943 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
944 .serverSupportedFileDescriptorTransportModes =
945 {RpcSession::FileDescriptorTransportMode::UNIX},
946 });
947
948 android::os::ParcelFileDescriptor out;
949 auto status = proc.rootIface->echoAsFile("hello", &out);
950 if (!supportsFdTransport()) {
951 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
952 return;
953 }
954 ASSERT_TRUE(status.isOk()) << status;
955
956 std::string result;
957 ASSERT_TRUE(ReadFdToString(out.get(), &result));
958 ASSERT_EQ(result, "hello");
959 }
960
TEST_P(BinderRpc,SendFiles)961 TEST_P(BinderRpc, SendFiles) {
962 if (socketType() == SocketType::TIPC) {
963 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
964 }
965
966 auto proc = createRpcTestSocketServerProcess({
967 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
968 .serverSupportedFileDescriptorTransportModes =
969 {RpcSession::FileDescriptorTransportMode::UNIX},
970 });
971
972 std::vector<android::os::ParcelFileDescriptor> files;
973 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
974 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
975 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
976 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
977
978 android::os::ParcelFileDescriptor out;
979 auto status = proc.rootIface->concatFiles(files, &out);
980 if (!supportsFdTransport()) {
981 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
982 return;
983 }
984 ASSERT_TRUE(status.isOk()) << status;
985
986 std::string result;
987 EXPECT_TRUE(ReadFdToString(out.get(), &result));
988 EXPECT_EQ(result, "123abcd");
989 }
990
TEST_P(BinderRpc,SendMaxFiles)991 TEST_P(BinderRpc, SendMaxFiles) {
992 if (!supportsFdTransport()) {
993 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
994 }
995
996 auto proc = createRpcTestSocketServerProcess({
997 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
998 .serverSupportedFileDescriptorTransportModes =
999 {RpcSession::FileDescriptorTransportMode::UNIX},
1000 });
1001
1002 std::vector<android::os::ParcelFileDescriptor> files;
1003 for (int i = 0; i < 253; i++) {
1004 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1005 }
1006
1007 android::os::ParcelFileDescriptor out;
1008 auto status = proc.rootIface->concatFiles(files, &out);
1009 ASSERT_TRUE(status.isOk()) << status;
1010
1011 std::string result;
1012 EXPECT_TRUE(ReadFdToString(out.get(), &result));
1013 EXPECT_EQ(result, std::string(253, 'a'));
1014 }
1015
TEST_P(BinderRpc,SendTooManyFiles)1016 TEST_P(BinderRpc, SendTooManyFiles) {
1017 if (!supportsFdTransport()) {
1018 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1019 }
1020
1021 auto proc = createRpcTestSocketServerProcess({
1022 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1023 .serverSupportedFileDescriptorTransportModes =
1024 {RpcSession::FileDescriptorTransportMode::UNIX},
1025 });
1026
1027 std::vector<android::os::ParcelFileDescriptor> files;
1028 for (int i = 0; i < 254; i++) {
1029 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1030 }
1031
1032 android::os::ParcelFileDescriptor out;
1033 auto status = proc.rootIface->concatFiles(files, &out);
1034 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1035 }
1036
TEST_P(BinderRpc,AppendInvalidFd)1037 TEST_P(BinderRpc, AppendInvalidFd) {
1038 if (socketType() == SocketType::TIPC) {
1039 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1040 }
1041
1042 auto proc = createRpcTestSocketServerProcess({
1043 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1044 .serverSupportedFileDescriptorTransportModes =
1045 {RpcSession::FileDescriptorTransportMode::UNIX},
1046 });
1047
1048 int badFd = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 0);
1049 ASSERT_NE(badFd, -1);
1050
1051 // Close the file descriptor so it becomes invalid for dup
1052 close(badFd);
1053
1054 Parcel p1;
1055 p1.markForBinder(proc.rootBinder);
1056 p1.writeInt32(3);
1057 EXPECT_EQ(OK, p1.writeFileDescriptor(badFd, false));
1058
1059 Parcel pRaw;
1060 pRaw.markForBinder(proc.rootBinder);
1061 EXPECT_EQ(OK, pRaw.appendFrom(&p1, 0, p1.dataSize()));
1062
1063 pRaw.setDataPosition(0);
1064 EXPECT_EQ(3, pRaw.readInt32());
1065 ASSERT_EQ(-1, pRaw.readFileDescriptor());
1066 }
1067
1068 #ifndef __ANDROID_VENDOR__ // No AIBinder_fromPlatformBinder on vendor
TEST_P(BinderRpc,WorksWithLibbinderNdkPing)1069 TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
1070 if constexpr (!kEnableSharedLibs) {
1071 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1072 }
1073
1074 auto proc = createRpcTestSocketServerProcess({});
1075
1076 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1077 ASSERT_NE(binder, nullptr);
1078
1079 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1080 }
1081
TEST_P(BinderRpc,WorksWithLibbinderNdkUserTransaction)1082 TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
1083 if constexpr (!kEnableSharedLibs) {
1084 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1085 }
1086
1087 auto proc = createRpcTestSocketServerProcess({});
1088
1089 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1090 ASSERT_NE(binder, nullptr);
1091
1092 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1093 ASSERT_NE(ndkBinder, nullptr);
1094
1095 std::string out;
1096 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1097 ASSERT_TRUE(status.isOk()) << status.getDescription();
1098 ASSERT_EQ("aoeuaoeu", out);
1099 }
1100 #endif // __ANDROID_VENDOR__
1101
countFds()1102 ssize_t countFds() {
1103 DIR* dir = opendir("/proc/self/fd/");
1104 if (dir == nullptr) return -1;
1105 ssize_t ret = 0;
1106 dirent* ent;
1107 while ((ent = readdir(dir)) != nullptr) ret++;
1108 closedir(dir);
1109 return ret;
1110 }
1111
TEST_P(BinderRpc,Fds)1112 TEST_P(BinderRpc, Fds) {
1113 if (serverSingleThreaded()) {
1114 GTEST_SKIP() << "This test requires multiple threads";
1115 }
1116 if (socketType() == SocketType::TIPC) {
1117 GTEST_SKIP() << "File descriptor tests not supported on Trusty (yet)";
1118 }
1119
1120 ssize_t beforeFds = countFds();
1121 ASSERT_GE(beforeFds, 0);
1122 {
1123 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
1124 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1125 }
1126 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1127 }
1128
1129 #ifdef BINDER_RPC_TO_TRUSTY_TEST
1130
getTrustyBinderRpcParams()1131 static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() {
1132 std::vector<BinderRpc::ParamType> ret;
1133
1134 for (const auto& clientVersion : testVersions()) {
1135 for (const auto& serverVersion : testVersions()) {
1136 ret.push_back(BinderRpc::ParamType{
1137 .type = SocketType::TIPC,
1138 .security = RpcSecurity::RAW,
1139 .clientVersion = clientVersion,
1140 .serverVersion = serverVersion,
1141 .singleThreaded = true,
1142 .noKernel = true,
1143 });
1144 }
1145 }
1146
1147 return ret;
1148 }
1149
1150 INSTANTIATE_TEST_SUITE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()),
1151 BinderRpc::PrintParamInfo);
1152 #else // BINDER_RPC_TO_TRUSTY_TEST
testSupportVsockLoopback()1153 bool testSupportVsockLoopback() {
1154 // We don't need to enable TLS to know if vsock is supported.
1155 unsigned int vsockPort = allocateVsockPort();
1156
1157 unique_fd serverFd(
1158 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1159
1160 if (errno == EAFNOSUPPORT) {
1161 return false;
1162 }
1163
1164 LOG_ALWAYS_FATAL_IF(!serverFd.ok(), "Could not create socket: %s", strerror(errno));
1165
1166 sockaddr_vm serverAddr{
1167 .svm_family = AF_VSOCK,
1168 .svm_port = vsockPort,
1169 .svm_cid = VMADDR_CID_ANY,
1170 };
1171 int ret = TEMP_FAILURE_RETRY(
1172 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1173 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1174 strerror(errno));
1175
1176 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1177 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1178 strerror(errno));
1179
1180 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1181 // to see if the kernel supports it. It's safe to use a blocking
1182 // connect because vsock sockets have a 2 second connection timeout,
1183 // and they return ETIMEDOUT after that.
1184 unique_fd connectFd(
1185 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1186 LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s", vsockPort,
1187 strerror(errno));
1188
1189 bool success = false;
1190 sockaddr_vm connectAddr{
1191 .svm_family = AF_VSOCK,
1192 .svm_port = vsockPort,
1193 .svm_cid = VMADDR_CID_LOCAL,
1194 };
1195 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1196 sizeof(connectAddr)));
1197 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1198 unique_fd acceptFd;
1199 while (true) {
1200 pollfd pfd[]{
1201 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1202 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1203 };
1204 ret = TEMP_FAILURE_RETRY(poll(pfd, countof(pfd), -1));
1205 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1206
1207 if (pfd[0].revents & POLLIN) {
1208 sockaddr_vm acceptAddr;
1209 socklen_t acceptAddrLen = sizeof(acceptAddr);
1210 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1211 reinterpret_cast<sockaddr*>(&acceptAddr),
1212 &acceptAddrLen, SOCK_CLOEXEC));
1213 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1214 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1215 "Truncated address");
1216
1217 // Store the fd in acceptFd so we keep the connection alive
1218 // while polling connectFd
1219 acceptFd.reset(ret);
1220 }
1221
1222 if (pfd[1].revents & POLLOUT) {
1223 // Connect either succeeded or timed out
1224 int connectErrno;
1225 socklen_t connectErrnoLen = sizeof(connectErrno);
1226 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1227 &connectErrnoLen);
1228 LOG_ALWAYS_FATAL_IF(ret == -1,
1229 "Could not getsockopt() after connect() "
1230 "on non-blocking socket: %s.",
1231 strerror(errno));
1232
1233 // We're done, this is all we wanted
1234 success = connectErrno == 0;
1235 break;
1236 }
1237 }
1238 } else {
1239 success = ret == 0;
1240 }
1241
1242 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1243
1244 return success;
1245 }
1246
testSocketTypes(bool hasPreconnected=true)1247 static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1248 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::UNIX_BOOTSTRAP, SocketType::INET,
1249 SocketType::UNIX_RAW};
1250
1251 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
1252
1253 #ifdef __BIONIC__
1254 // Devices may not have vsock support. AVF tests will verify whether they do, but
1255 // we can't require it due to old kernels for the time being.
1256 static bool hasVsockLoopback = testSupportVsockLoopback();
1257 #else
1258 // On host machines, we always assume we have vsock loopback. If we don't, the
1259 // subsequent failures will be more clear than showing one now.
1260 static bool hasVsockLoopback = true;
1261 #endif
1262
1263 if (hasVsockLoopback) {
1264 ret.push_back(SocketType::VSOCK);
1265 }
1266
1267 return ret;
1268 }
1269
getBinderRpcParams()1270 static std::vector<BinderRpc::ParamType> getBinderRpcParams() {
1271 std::vector<BinderRpc::ParamType> ret;
1272
1273 constexpr bool full = false;
1274
1275 for (const auto& type : testSocketTypes()) {
1276 if (full || type == SocketType::UNIX) {
1277 for (const auto& security : RpcSecurityValues()) {
1278 for (const auto& clientVersion : testVersions()) {
1279 for (const auto& serverVersion : testVersions()) {
1280 for (bool singleThreaded : {false, true}) {
1281 for (bool noKernel : noKernelValues()) {
1282 ret.push_back(BinderRpc::ParamType{
1283 .type = type,
1284 .security = security,
1285 .clientVersion = clientVersion,
1286 .serverVersion = serverVersion,
1287 .singleThreaded = singleThreaded,
1288 .noKernel = noKernel,
1289 });
1290 }
1291 }
1292 }
1293 }
1294 }
1295 } else {
1296 ret.push_back(BinderRpc::ParamType{
1297 .type = type,
1298 .security = RpcSecurity::RAW,
1299 .clientVersion = RPC_WIRE_PROTOCOL_VERSION,
1300 .serverVersion = RPC_WIRE_PROTOCOL_VERSION,
1301 .singleThreaded = false,
1302 .noKernel = !kEnableKernelIpcTesting,
1303 });
1304 }
1305 }
1306
1307 return ret;
1308 }
1309
1310 INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()),
1311 BinderRpc::PrintParamInfo);
1312
1313 class BinderRpcServerRootObject
1314 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
1315
TEST_P(BinderRpcServerRootObject,WeakRootObject)1316 TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1317 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1318 auto setRootObject = [](bool isStrong) -> SetFn {
1319 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1320 };
1321
1322 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1323 auto server = RpcServer::make(newTlsFactory(rpcSecurity));
1324 auto binder1 = sp<BBinder>::make();
1325 IBinder* binderRaw1 = binder1.get();
1326 setRootObject(isStrong1)(server.get(), binder1);
1327 EXPECT_EQ(binderRaw1, server->getRootObject());
1328 binder1.clear();
1329 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1330
1331 auto binder2 = sp<BBinder>::make();
1332 IBinder* binderRaw2 = binder2.get();
1333 setRootObject(isStrong2)(server.get(), binder2);
1334 EXPECT_EQ(binderRaw2, server->getRootObject());
1335 binder2.clear();
1336 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1337 }
1338
1339 INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerRootObject,
1340 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1341 ::testing::ValuesIn(RpcSecurityValues())));
1342
1343 class OneOffSignal {
1344 public:
1345 // If notify() was previously called, or is called within |duration|, return true; else false.
1346 template <typename R, typename P>
wait(std::chrono::duration<R,P> duration)1347 bool wait(std::chrono::duration<R, P> duration) {
1348 std::unique_lock<std::mutex> lock(mMutex);
1349 return mCv.wait_for(lock, duration, [this] { return mValue; });
1350 }
notify()1351 void notify() {
1352 std::unique_lock<std::mutex> lock(mMutex);
1353 mValue = true;
1354 lock.unlock();
1355 mCv.notify_all();
1356 }
1357
1358 private:
1359 std::mutex mMutex;
1360 std::condition_variable mCv;
1361 bool mValue = false;
1362 };
1363
TEST(BinderRpc,Java)1364 TEST(BinderRpc, Java) {
1365 bool expectDebuggable = false;
1366 #if defined(__ANDROID__)
1367 expectDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1368 android::base::GetProperty("ro.build.type", "") != "user";
1369 #else
1370 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1371 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1372 "to binderHostDeviceTest. Hence, just disable this test on host.";
1373 #endif // !__ANDROID__
1374 if constexpr (!kEnableKernelIpc) {
1375 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1376 "at build time.";
1377 }
1378
1379 sp<IServiceManager> sm = defaultServiceManager();
1380 ASSERT_NE(nullptr, sm);
1381 // Any Java service with non-empty getInterfaceDescriptor() would do.
1382 // Let's pick batteryproperties.
1383 auto binder = sm->checkService(String16("batteryproperties"));
1384 ASSERT_NE(nullptr, binder);
1385 auto descriptor = binder->getInterfaceDescriptor();
1386 ASSERT_GE(descriptor.size(), 0u);
1387 ASSERT_EQ(OK, binder->pingBinder());
1388
1389 auto rpcServer = RpcServer::make();
1390 unsigned int port;
1391 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
1392 auto socket = rpcServer->releaseServer();
1393
1394 auto keepAlive = sp<BBinder>::make();
1395 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1396
1397 if (!expectDebuggable) {
1398 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
1399 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1400 "builds, but get "
1401 << statusToString(setRpcClientDebugStatus);
1402 GTEST_SKIP();
1403 }
1404
1405 ASSERT_EQ(OK, setRpcClientDebugStatus);
1406
1407 auto rpcSession = RpcSession::make();
1408 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
1409 auto rpcBinder = rpcSession->getRootObject();
1410 ASSERT_NE(nullptr, rpcBinder);
1411
1412 ASSERT_EQ(OK, rpcBinder->pingBinder());
1413
1414 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1415 << "getInterfaceDescriptor should not crash system_server";
1416 ASSERT_EQ(OK, rpcBinder->pingBinder());
1417 }
1418
1419 class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
1420 public:
PrintTestParam(const::testing::TestParamInfo<ParamType> & info)1421 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
1422 return std::string(newTlsFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
1423 std::to_string(std::get<1>(info.param));
1424 }
1425 };
1426
TEST_P(BinderRpcServerOnly,SetExternalServerTest)1427 TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
1428 unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
1429 int sinkFd = sink.get();
1430 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
1431 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
1432 ASSERT_FALSE(server->hasServer());
1433 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
1434 ASSERT_TRUE(server->hasServer());
1435 unique_fd retrieved = server->releaseServer();
1436 ASSERT_FALSE(server->hasServer());
1437 ASSERT_EQ(sinkFd, retrieved.get());
1438 }
1439
TEST_P(BinderRpcServerOnly,Shutdown)1440 TEST_P(BinderRpcServerOnly, Shutdown) {
1441 if constexpr (!kEnableRpcThreads) {
1442 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1443 }
1444
1445 auto addr = allocateSocketAddress();
1446 auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
1447 ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
1448 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
1449 auto joinEnds = std::make_shared<OneOffSignal>();
1450
1451 // If things are broken and the thread never stops, don't block other tests. Because the thread
1452 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1453 // shared pointers are passed.
1454 std::thread([server, joinEnds] {
1455 server->join();
1456 joinEnds->notify();
1457 }).detach();
1458
1459 bool shutdown = false;
1460 for (int i = 0; i < 10 && !shutdown; i++) {
1461 usleep(30 * 1000); // 30ms; total 300ms
1462 if (server->shutdown()) shutdown = true;
1463 }
1464 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1465
1466 ASSERT_TRUE(joinEnds->wait(2s))
1467 << "After server->shutdown() returns true, join() did not stop after 2s";
1468 }
1469
1470 INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerOnly,
1471 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1472 ::testing::ValuesIn(testVersions())),
1473 BinderRpcServerOnly::PrintTestParam);
1474
1475 class RpcTransportTestUtils {
1476 public:
1477 // Only parameterized only server version because `RpcSession` is bypassed
1478 // in the client half of the tests.
1479 using Param =
1480 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
1481 using ConnectToServer = std::function<unique_fd()>;
1482
1483 // A server that handles client socket connections.
1484 class Server {
1485 public:
1486 using AcceptConnection = std::function<unique_fd(Server*)>;
1487
Server()1488 explicit Server() {}
1489 Server(Server&&) = default;
~Server()1490 ~Server() { shutdownAndWait(); }
setUp(const Param & param,std::unique_ptr<RpcAuth> auth=std::make_unique<RpcAuthSelfSigned> ())1491 [[nodiscard]] AssertionResult setUp(
1492 const Param& param,
1493 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
1494 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1495 auto rpcServer = RpcServer::make(newTlsFactory(rpcSecurity));
1496 if (!rpcServer->setProtocolVersion(serverVersion)) {
1497 return AssertionFailure() << "Invalid protocol version: " << serverVersion;
1498 }
1499 switch (socketType) {
1500 case SocketType::PRECONNECTED: {
1501 return AssertionFailure() << "Not supported by this test";
1502 } break;
1503 case SocketType::UNIX: {
1504 auto addr = allocateSocketAddress();
1505 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1506 if (status != OK) {
1507 return AssertionFailure()
1508 << "setupUnixDomainServer: " << statusToString(status);
1509 }
1510 mConnectToServer = [addr] {
1511 return connectTo(UnixSocketAddress(addr.c_str()));
1512 };
1513 } break;
1514 case SocketType::UNIX_BOOTSTRAP: {
1515 unique_fd bootstrapFdClient, bootstrapFdServer;
1516 if (!binder::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
1517 return AssertionFailure() << "Socketpair() failed";
1518 }
1519 auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
1520 std::move(bootstrapFdServer));
1521 if (status != OK) {
1522 return AssertionFailure() << "setupUnixDomainSocketBootstrapServer: "
1523 << statusToString(status);
1524 }
1525 mBootstrapSocket = RpcTransportFd(std::move(bootstrapFdClient));
1526 mAcceptConnection = &Server::recvmsgServerConnection;
1527 mConnectToServer = [this] { return connectToUnixBootstrap(mBootstrapSocket); };
1528 } break;
1529 case SocketType::UNIX_RAW: {
1530 auto addr = allocateSocketAddress();
1531 auto status = rpcServer->setupRawSocketServer(initUnixSocket(addr));
1532 if (status != OK) {
1533 return AssertionFailure()
1534 << "setupRawSocketServer: " << statusToString(status);
1535 }
1536 mConnectToServer = [addr] {
1537 return connectTo(UnixSocketAddress(addr.c_str()));
1538 };
1539 } break;
1540 case SocketType::VSOCK: {
1541 auto port = allocateVsockPort();
1542 auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
1543 if (status != OK) {
1544 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1545 }
1546 mConnectToServer = [port] {
1547 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1548 };
1549 } break;
1550 case SocketType::INET: {
1551 unsigned int port;
1552 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1553 if (status != OK) {
1554 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1555 }
1556 mConnectToServer = [port] {
1557 const char* addr = kLocalInetAddress;
1558 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1559 if (aiStart == nullptr) return unique_fd{};
1560 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1561 auto fd = connectTo(
1562 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1563 if (fd.ok()) return fd;
1564 }
1565 ALOGE("None of the socket address resolved for %s:%u can be connected",
1566 addr, port);
1567 return unique_fd{};
1568 };
1569 } break;
1570 case SocketType::TIPC: {
1571 LOG_ALWAYS_FATAL("RpcTransportTest should not be enabled for TIPC");
1572 } break;
1573 }
1574 mFd = rpcServer->releaseServer();
1575 if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
1576 mCtx = newTlsFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
1577 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1578 mSetup = true;
1579 return AssertionSuccess();
1580 }
getCtx() const1581 RpcTransportCtx* getCtx() const { return mCtx.get(); }
getCertVerifier() const1582 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1583 return mCertVerifier;
1584 }
getConnectToServerFn()1585 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
start()1586 void start() {
1587 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1588 mThread = std::make_unique<std::thread>(&Server::run, this);
1589 }
1590
acceptServerConnection()1591 unique_fd acceptServerConnection() {
1592 return unique_fd(TEMP_FAILURE_RETRY(
1593 accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
1594 }
1595
recvmsgServerConnection()1596 unique_fd recvmsgServerConnection() {
1597 std::vector<std::variant<unique_fd, borrowed_fd>> fds;
1598 int buf;
1599 iovec iov{&buf, sizeof(buf)};
1600
1601 if (binder::os::receiveMessageFromSocket(mFd, &iov, 1, &fds) < 0) {
1602 PLOGF("Failed receiveMessage");
1603 }
1604 LOG_ALWAYS_FATAL_IF(fds.size() != 1, "Expected one FD from receiveMessage(), got %zu",
1605 fds.size());
1606 return std::move(std::get<unique_fd>(fds[0]));
1607 }
1608
run()1609 void run() {
1610 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1611
1612 std::vector<std::thread> threads;
1613 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1614 unique_fd acceptedFd = mAcceptConnection(this);
1615 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1616 }
1617
1618 for (auto& thread : threads) thread.join();
1619 }
handleOne(unique_fd acceptedFd)1620 void handleOne(unique_fd acceptedFd) {
1621 ASSERT_TRUE(acceptedFd.ok());
1622 RpcTransportFd transportFd(std::move(acceptedFd));
1623 auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
1624 if (serverTransport == nullptr) return; // handshake failed
1625 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
1626 }
shutdownAndWait()1627 void shutdownAndWait() {
1628 shutdown();
1629 join();
1630 }
shutdown()1631 void shutdown() { mFdTrigger->trigger(); }
1632
setPostConnect(std::function<AssertionResult (RpcTransport *,FdTrigger * fdTrigger)> fn)1633 void setPostConnect(
1634 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1635 mPostConnect = std::move(fn);
1636 }
1637
1638 private:
1639 std::unique_ptr<std::thread> mThread;
1640 ConnectToServer mConnectToServer;
1641 AcceptConnection mAcceptConnection = &Server::acceptServerConnection;
1642 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1643 RpcTransportFd mFd, mBootstrapSocket;
1644 std::unique_ptr<RpcTransportCtx> mCtx;
1645 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1646 std::make_shared<RpcCertificateVerifierSimple>();
1647 bool mSetup = false;
1648 // The function invoked after connection and handshake. By default, it is
1649 // |defaultPostConnect| that sends |kMessage| to the client.
1650 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1651 Server::defaultPostConnect;
1652
join()1653 void join() {
1654 if (mThread != nullptr) {
1655 mThread->join();
1656 mThread = nullptr;
1657 }
1658 }
1659
defaultPostConnect(RpcTransport * serverTransport,FdTrigger * fdTrigger)1660 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1661 FdTrigger* fdTrigger) {
1662 std::string message(kMessage);
1663 iovec messageIov{message.data(), message.size()};
1664 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1665 std::nullopt, nullptr);
1666 if (status != OK) return AssertionFailure() << statusToString(status);
1667 return AssertionSuccess();
1668 }
1669 };
1670
1671 class Client {
1672 public:
Client(ConnectToServer connectToServer)1673 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1674 Client(Client&&) = default;
setUp(const Param & param)1675 [[nodiscard]] AssertionResult setUp(const Param& param) {
1676 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1677 (void)serverVersion;
1678 mFdTrigger = FdTrigger::make();
1679 mCtx = newTlsFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1680 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1681 return AssertionSuccess();
1682 }
getCtx() const1683 RpcTransportCtx* getCtx() const { return mCtx.get(); }
getCertVerifier() const1684 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1685 return mCertVerifier;
1686 }
1687 // connect() and do handshake
setUpTransport()1688 bool setUpTransport() {
1689 mFd = mConnectToServer();
1690 if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
1691 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1692 return mClientTransport != nullptr;
1693 }
readMessage(const std::string & expectedMessage=kMessage)1694 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1695 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1696 std::string readMessage(expectedMessage.size(), '\0');
1697 iovec readMessageIov{readMessage.data(), readMessage.size()};
1698 status_t readStatus =
1699 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
1700 std::nullopt, nullptr);
1701 if (readStatus != OK) {
1702 return AssertionFailure() << statusToString(readStatus);
1703 }
1704 if (readMessage != expectedMessage) {
1705 return AssertionFailure()
1706 << "Expected " << expectedMessage << ", actual " << readMessage;
1707 }
1708 return AssertionSuccess();
1709 }
run(bool handshakeOk=true,bool readOk=true)1710 void run(bool handshakeOk = true, bool readOk = true) {
1711 if (!setUpTransport()) {
1712 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1713 return;
1714 }
1715 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
1716 ASSERT_EQ(readOk, readMessage());
1717 }
1718
isTransportWaiting()1719 bool isTransportWaiting() { return mClientTransport->isWaiting(); }
1720
1721 private:
1722 ConnectToServer mConnectToServer;
1723 RpcTransportFd mFd;
1724 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1725 std::unique_ptr<RpcTransportCtx> mCtx;
1726 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1727 std::make_shared<RpcCertificateVerifierSimple>();
1728 std::unique_ptr<RpcTransport> mClientTransport;
1729 };
1730
1731 // Make A trust B.
1732 template <typename A, typename B>
trust(RpcSecurity rpcSecurity,std::optional<RpcCertificateFormat> certificateFormat,const A & a,const B & b)1733 static status_t trust(RpcSecurity rpcSecurity,
1734 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1735 const B& b) {
1736 if (rpcSecurity != RpcSecurity::TLS) return OK;
1737 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1738 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1739 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
1740 }
1741
1742 static constexpr const char* kMessage = "hello";
1743 };
1744
1745 class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1746 public:
1747 using Server = RpcTransportTestUtils::Server;
1748 using Client = RpcTransportTestUtils::Client;
PrintParamInfo(const testing::TestParamInfo<ParamType> & info)1749 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1750 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
1751 auto ret = PrintToString(socketType) + "_" + newTlsFactory(rpcSecurity)->toCString();
1752 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
1753 ret += "_serverV" + std::to_string(serverVersion);
1754 return ret;
1755 }
getRpcTranportTestParams()1756 static std::vector<ParamType> getRpcTranportTestParams() {
1757 std::vector<ParamType> ret;
1758 for (auto serverVersion : testVersions()) {
1759 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1760 for (auto rpcSecurity : RpcSecurityValues()) {
1761 switch (rpcSecurity) {
1762 case RpcSecurity::RAW: {
1763 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
1764 } break;
1765 case RpcSecurity::TLS: {
1766 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
1767 serverVersion);
1768 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
1769 serverVersion);
1770 } break;
1771 }
1772 }
1773 }
1774 }
1775 return ret;
1776 }
1777 template <typename A, typename B>
trust(const A & a,const B & b)1778 status_t trust(const A& a, const B& b) {
1779 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1780 (void)serverVersion;
1781 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1782 }
SetUp()1783 void SetUp() override {
1784 if constexpr (!kEnableRpcThreads) {
1785 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1786 }
1787 }
1788 };
1789
TEST_P(RpcTransportTest,GoodCertificate)1790 TEST_P(RpcTransportTest, GoodCertificate) {
1791 auto server = std::make_unique<Server>();
1792 ASSERT_TRUE(server->setUp(GetParam()));
1793
1794 Client client(server->getConnectToServerFn());
1795 ASSERT_TRUE(client.setUp(GetParam()));
1796
1797 ASSERT_EQ(OK, trust(&client, server));
1798 ASSERT_EQ(OK, trust(server, &client));
1799
1800 server->start();
1801 client.run();
1802 }
1803
TEST_P(RpcTransportTest,MultipleClients)1804 TEST_P(RpcTransportTest, MultipleClients) {
1805 auto server = std::make_unique<Server>();
1806 ASSERT_TRUE(server->setUp(GetParam()));
1807
1808 std::vector<Client> clients;
1809 for (int i = 0; i < 2; i++) {
1810 auto& client = clients.emplace_back(server->getConnectToServerFn());
1811 ASSERT_TRUE(client.setUp(GetParam()));
1812 ASSERT_EQ(OK, trust(&client, server));
1813 ASSERT_EQ(OK, trust(server, &client));
1814 }
1815
1816 server->start();
1817 for (auto& client : clients) client.run();
1818 }
1819
TEST_P(RpcTransportTest,UntrustedServer)1820 TEST_P(RpcTransportTest, UntrustedServer) {
1821 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1822 (void)serverVersion;
1823
1824 auto untrustedServer = std::make_unique<Server>();
1825 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
1826
1827 Client client(untrustedServer->getConnectToServerFn());
1828 ASSERT_TRUE(client.setUp(GetParam()));
1829
1830 ASSERT_EQ(OK, trust(untrustedServer, &client));
1831
1832 untrustedServer->start();
1833
1834 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1835 // the client can't verify the server's identity.
1836 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1837 client.run(handshakeOk);
1838 }
TEST_P(RpcTransportTest,MaliciousServer)1839 TEST_P(RpcTransportTest, MaliciousServer) {
1840 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1841 (void)serverVersion;
1842
1843 auto validServer = std::make_unique<Server>();
1844 ASSERT_TRUE(validServer->setUp(GetParam()));
1845
1846 auto maliciousServer = std::make_unique<Server>();
1847 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
1848
1849 Client client(maliciousServer->getConnectToServerFn());
1850 ASSERT_TRUE(client.setUp(GetParam()));
1851
1852 ASSERT_EQ(OK, trust(&client, validServer));
1853 ASSERT_EQ(OK, trust(validServer, &client));
1854 ASSERT_EQ(OK, trust(maliciousServer, &client));
1855
1856 maliciousServer->start();
1857
1858 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1859 // the client can't verify the server's identity.
1860 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1861 client.run(handshakeOk);
1862 }
1863
TEST_P(RpcTransportTest,UntrustedClient)1864 TEST_P(RpcTransportTest, UntrustedClient) {
1865 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1866 (void)serverVersion;
1867
1868 auto server = std::make_unique<Server>();
1869 ASSERT_TRUE(server->setUp(GetParam()));
1870
1871 Client client(server->getConnectToServerFn());
1872 ASSERT_TRUE(client.setUp(GetParam()));
1873
1874 ASSERT_EQ(OK, trust(&client, server));
1875
1876 server->start();
1877
1878 // For TLS, Client should be able to verify server's identity, so client should see
1879 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1880 // identity and should drop the connection, so client shouldn't be able to read anything.
1881 bool readOk = rpcSecurity != RpcSecurity::TLS;
1882 client.run(true, readOk);
1883 }
1884
TEST_P(RpcTransportTest,MaliciousClient)1885 TEST_P(RpcTransportTest, MaliciousClient) {
1886 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
1887 (void)serverVersion;
1888
1889 auto server = std::make_unique<Server>();
1890 ASSERT_TRUE(server->setUp(GetParam()));
1891
1892 Client validClient(server->getConnectToServerFn());
1893 ASSERT_TRUE(validClient.setUp(GetParam()));
1894 Client maliciousClient(server->getConnectToServerFn());
1895 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
1896
1897 ASSERT_EQ(OK, trust(&validClient, server));
1898 ASSERT_EQ(OK, trust(&maliciousClient, server));
1899
1900 server->start();
1901
1902 // See UntrustedClient.
1903 bool readOk = rpcSecurity != RpcSecurity::TLS;
1904 maliciousClient.run(true, readOk);
1905 }
1906
TEST_P(RpcTransportTest,Trigger)1907 TEST_P(RpcTransportTest, Trigger) {
1908 std::string msg2 = ", world!";
1909 std::mutex writeMutex;
1910 std::condition_variable writeCv;
1911 bool shouldContinueWriting = false;
1912 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1913 std::string message(RpcTransportTestUtils::kMessage);
1914 iovec messageIov{message.data(), message.size()};
1915 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1916 std::nullopt, nullptr);
1917 if (status != OK) return AssertionFailure() << statusToString(status);
1918
1919 {
1920 std::unique_lock<std::mutex> lock(writeMutex);
1921 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1922 return AssertionFailure() << "write barrier not cleared in time!";
1923 }
1924 }
1925
1926 iovec msg2Iov{msg2.data(), msg2.size()};
1927 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
1928 nullptr);
1929 if (status != DEAD_OBJECT)
1930 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
1931 "should return DEAD_OBJECT, but it is "
1932 << statusToString(status);
1933 return AssertionSuccess();
1934 };
1935
1936 auto server = std::make_unique<Server>();
1937 ASSERT_TRUE(server->setUp(GetParam()));
1938
1939 // Set up client
1940 Client client(server->getConnectToServerFn());
1941 ASSERT_TRUE(client.setUp(GetParam()));
1942
1943 // Exchange keys
1944 ASSERT_EQ(OK, trust(&client, server));
1945 ASSERT_EQ(OK, trust(server, &client));
1946
1947 server->setPostConnect(serverPostConnect);
1948
1949 server->start();
1950 // connect() to server and do handshake
1951 ASSERT_TRUE(client.setUpTransport());
1952 // read the first message. This ensures that server has finished handshake and start handling
1953 // client fd. Server thread should pause at writeCv.wait_for().
1954 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
1955 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1956 // write is on an FdTrigger that has been shut down.
1957 server->shutdown();
1958 // Continues server thread to write the second message.
1959 {
1960 std::lock_guard<std::mutex> lock(writeMutex);
1961 shouldContinueWriting = true;
1962 }
1963 writeCv.notify_all();
1964 // After this line, server thread unblocks and attempts to write the second message, but
1965 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
1966 // On the client side, second read fails with DEAD_OBJECT
1967 ASSERT_FALSE(client.readMessage(msg2));
1968 }
1969
TEST_P(RpcTransportTest,CheckWaitingForRead)1970 TEST_P(RpcTransportTest, CheckWaitingForRead) {
1971 std::mutex readMutex;
1972 std::condition_variable readCv;
1973 bool shouldContinueReading = false;
1974 // Server will write data on transport once its started
1975 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
1976 std::string message(RpcTransportTestUtils::kMessage);
1977 iovec messageIov{message.data(), message.size()};
1978 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1979 std::nullopt, nullptr);
1980 if (status != OK) return AssertionFailure() << statusToString(status);
1981
1982 {
1983 std::unique_lock<std::mutex> lock(readMutex);
1984 shouldContinueReading = true;
1985 lock.unlock();
1986 readCv.notify_all();
1987 }
1988 return AssertionSuccess();
1989 };
1990
1991 // Setup Server and client
1992 auto server = std::make_unique<Server>();
1993 ASSERT_TRUE(server->setUp(GetParam()));
1994
1995 Client client(server->getConnectToServerFn());
1996 ASSERT_TRUE(client.setUp(GetParam()));
1997
1998 ASSERT_EQ(OK, trust(&client, server));
1999 ASSERT_EQ(OK, trust(server, &client));
2000 server->setPostConnect(serverPostConnect);
2001
2002 server->start();
2003 ASSERT_TRUE(client.setUpTransport());
2004 {
2005 // Wait till server writes data
2006 std::unique_lock<std::mutex> lock(readMutex);
2007 ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
2008 }
2009
2010 // Since there is no read polling here, we will get polling count 0
2011 ASSERT_FALSE(client.isTransportWaiting());
2012 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
2013 // Thread should increment polling count, read and decrement polling count
2014 // Again, polling count should be zero here
2015 ASSERT_FALSE(client.isTransportWaiting());
2016
2017 server->shutdown();
2018 }
2019
2020 INSTANTIATE_TEST_SUITE_P(BinderRpc, RpcTransportTest,
2021 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
2022 RpcTransportTest::PrintParamInfo);
2023
2024 class RpcTransportTlsKeyTest
2025 : public testing::TestWithParam<
2026 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
2027 public:
2028 template <typename A, typename B>
trust(const A & a,const B & b)2029 status_t trust(const A& a, const B& b) {
2030 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2031 (void)serverVersion;
2032 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2033 }
PrintParamInfo(const testing::TestParamInfo<ParamType> & info)2034 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
2035 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2036 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2037 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
2038 };
2039 };
2040
TEST_P(RpcTransportTlsKeyTest,PreSignedCertificate)2041 TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
2042 if constexpr (!kEnableRpcThreads) {
2043 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2044 }
2045
2046 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2047
2048 std::vector<uint8_t> pkeyData, certData;
2049 {
2050 auto pkey = makeKeyPairForSelfSignedCert();
2051 ASSERT_NE(nullptr, pkey);
2052 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2053 ASSERT_NE(nullptr, cert);
2054 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2055 certData = serializeCertificate(cert.get(), certificateFormat);
2056 }
2057
2058 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2059 auto desCert = deserializeCertificate(certData, certificateFormat);
2060 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
2061 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2062 std::make_optional(certificateFormat), serverVersion);
2063
2064 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2065 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2066
2067 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2068 ASSERT_TRUE(client.setUp(utilsParam));
2069
2070 ASSERT_EQ(OK, trust(&client, server));
2071 ASSERT_EQ(OK, trust(server, &client));
2072
2073 server->start();
2074 client.run();
2075 }
2076
2077 INSTANTIATE_TEST_SUITE_P(
2078 BinderRpc, RpcTransportTlsKeyTest,
2079 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2080 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
2081 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2082 testing::ValuesIn(testVersions())),
2083 RpcTransportTlsKeyTest::PrintParamInfo);
2084 #endif // BINDER_RPC_TO_TRUSTY_TEST
2085
2086 } // namespace android
2087
main(int argc,char ** argv)2088 int main(int argc, char** argv) {
2089 ::testing::InitGoogleTest(&argc, argv);
2090 __android_log_set_logger(__android_log_stderr_logger);
2091
2092 return RUN_ALL_TESTS();
2093 }
2094