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