• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <BnBinderRpcSession.h>
18 #include <BnBinderRpcTest.h>
19 #include <aidl/IBinderRpcTest.h>
20 #include <android-base/file.h>
21 #include <android-base/logging.h>
22 #include <android/binder_auto_utils.h>
23 #include <android/binder_libbinder.h>
24 #include <binder/Binder.h>
25 #include <binder/BpBinder.h>
26 #include <binder/IServiceManager.h>
27 #include <binder/ProcessState.h>
28 #include <binder/RpcServer.h>
29 #include <binder/RpcSession.h>
30 #include <gtest/gtest.h>
31 
32 #include <chrono>
33 #include <cstdlib>
34 #include <iostream>
35 #include <thread>
36 
37 #include <sys/prctl.h>
38 #include <unistd.h>
39 
40 #include "../RpcState.h"   // for debugging
41 #include "../vm_sockets.h" // for VMADDR_*
42 
43 namespace android {
44 
TEST(BinderRpcParcel,EntireParcelFormatted)45 TEST(BinderRpcParcel, EntireParcelFormatted) {
46     Parcel p;
47     p.writeInt32(3);
48 
49     EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
50 }
51 
TEST(BinderRpc,SetExternalServer)52 TEST(BinderRpc, SetExternalServer) {
53     base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
54     int sinkFd = sink.get();
55     auto server = RpcServer::make();
56     server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
57     ASSERT_FALSE(server->hasServer());
58     ASSERT_TRUE(server->setupExternalServer(std::move(sink)));
59     ASSERT_TRUE(server->hasServer());
60     base::unique_fd retrieved = server->releaseServer();
61     ASSERT_FALSE(server->hasServer());
62     ASSERT_EQ(sinkFd, retrieved.get());
63 }
64 
65 using android::binder::Status;
66 
67 #define EXPECT_OK(status)                 \
68     do {                                  \
69         Status stat = (status);           \
70         EXPECT_TRUE(stat.isOk()) << stat; \
71     } while (false)
72 
73 class MyBinderRpcSession : public BnBinderRpcSession {
74 public:
75     static std::atomic<int32_t> gNum;
76 
MyBinderRpcSession(const std::string & name)77     MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
getName(std::string * name)78     Status getName(std::string* name) override {
79         *name = mName;
80         return Status::ok();
81     }
~MyBinderRpcSession()82     ~MyBinderRpcSession() { gNum--; }
83 
84 private:
85     std::string mName;
86 };
87 std::atomic<int32_t> MyBinderRpcSession::gNum;
88 
89 class MyBinderRpcTest : public BnBinderRpcTest {
90 public:
91     wp<RpcServer> server;
92 
sendString(const std::string & str)93     Status sendString(const std::string& str) override {
94         (void)str;
95         return Status::ok();
96     }
doubleString(const std::string & str,std::string * strstr)97     Status doubleString(const std::string& str, std::string* strstr) override {
98         *strstr = str + str;
99         return Status::ok();
100     }
countBinders(std::vector<int32_t> * out)101     Status countBinders(std::vector<int32_t>* out) override {
102         sp<RpcServer> spServer = server.promote();
103         if (spServer == nullptr) {
104             return Status::fromExceptionCode(Status::EX_NULL_POINTER);
105         }
106         out->clear();
107         for (auto session : spServer->listSessions()) {
108             size_t count = session->state()->countBinders();
109             if (count != 1) {
110                 // this is called when there is only one binder held remaining,
111                 // so to aid debugging
112                 session->state()->dump();
113             }
114             out->push_back(count);
115         }
116         return Status::ok();
117     }
pingMe(const sp<IBinder> & binder,int32_t * out)118     Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
119         if (binder == nullptr) {
120             std::cout << "Received null binder!" << std::endl;
121             return Status::fromExceptionCode(Status::EX_NULL_POINTER);
122         }
123         *out = binder->pingBinder();
124         return Status::ok();
125     }
repeatBinder(const sp<IBinder> & binder,sp<IBinder> * out)126     Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
127         *out = binder;
128         return Status::ok();
129     }
130     static sp<IBinder> mHeldBinder;
holdBinder(const sp<IBinder> & binder)131     Status holdBinder(const sp<IBinder>& binder) override {
132         mHeldBinder = binder;
133         return Status::ok();
134     }
getHeldBinder(sp<IBinder> * held)135     Status getHeldBinder(sp<IBinder>* held) override {
136         *held = mHeldBinder;
137         return Status::ok();
138     }
nestMe(const sp<IBinderRpcTest> & binder,int count)139     Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
140         if (count <= 0) return Status::ok();
141         return binder->nestMe(this, count - 1);
142     }
alwaysGiveMeTheSameBinder(sp<IBinder> * out)143     Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
144         static sp<IBinder> binder = new BBinder;
145         *out = binder;
146         return Status::ok();
147     }
openSession(const std::string & name,sp<IBinderRpcSession> * out)148     Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
149         *out = new MyBinderRpcSession(name);
150         return Status::ok();
151     }
getNumOpenSessions(int32_t * out)152     Status getNumOpenSessions(int32_t* out) override {
153         *out = MyBinderRpcSession::gNum;
154         return Status::ok();
155     }
156 
157     std::mutex blockMutex;
lock()158     Status lock() override {
159         blockMutex.lock();
160         return Status::ok();
161     }
unlockInMsAsync(int32_t ms)162     Status unlockInMsAsync(int32_t ms) override {
163         usleep(ms * 1000);
164         blockMutex.unlock();
165         return Status::ok();
166     }
lockUnlock()167     Status lockUnlock() override {
168         std::lock_guard<std::mutex> _l(blockMutex);
169         return Status::ok();
170     }
171 
sleepMs(int32_t ms)172     Status sleepMs(int32_t ms) override {
173         usleep(ms * 1000);
174         return Status::ok();
175     }
176 
sleepMsAsync(int32_t ms)177     Status sleepMsAsync(int32_t ms) override {
178         // In-process binder calls are asynchronous, but the call to this method
179         // is synchronous wrt its client. This in/out-process threading model
180         // diffentiation is a classic binder leaky abstraction (for better or
181         // worse) and is preserved here the way binder sockets plugs itself
182         // into BpBinder, as nothing is changed at the higher levels
183         // (IInterface) which result in this behavior.
184         return sleepMs(ms);
185     }
186 
die(bool cleanup)187     Status die(bool cleanup) override {
188         if (cleanup) {
189             exit(1);
190         } else {
191             _exit(1);
192         }
193     }
194 };
195 sp<IBinder> MyBinderRpcTest::mHeldBinder;
196 
197 class Pipe {
198 public:
Pipe()199     Pipe() { CHECK(android::base::Pipe(&mRead, &mWrite)); }
200     Pipe(Pipe&&) = default;
readEnd()201     android::base::borrowed_fd readEnd() { return mRead; }
writeEnd()202     android::base::borrowed_fd writeEnd() { return mWrite; }
203 
204 private:
205     android::base::unique_fd mRead;
206     android::base::unique_fd mWrite;
207 };
208 
209 class Process {
210 public:
211     Process(Process&&) = default;
Process(const std::function<void (Pipe *)> & f)212     Process(const std::function<void(Pipe*)>& f) {
213         if (0 == (mPid = fork())) {
214             // racey: assume parent doesn't crash before this is set
215             prctl(PR_SET_PDEATHSIG, SIGHUP);
216 
217             f(&mPipe);
218         }
219     }
~Process()220     ~Process() {
221         if (mPid != 0) {
222             kill(mPid, SIGKILL);
223         }
224     }
getPipe()225     Pipe* getPipe() { return &mPipe; }
226 
227 private:
228     pid_t mPid = 0;
229     Pipe mPipe;
230 };
231 
allocateSocketAddress()232 static std::string allocateSocketAddress() {
233     static size_t id = 0;
234     std::string temp = getenv("TMPDIR") ?: "/tmp";
235     return temp + "/binderRpcTest_" + std::to_string(id++);
236 };
237 
238 struct ProcessSession {
239     // reference to process hosting a socket server
240     Process host;
241 
242     struct SessionInfo {
243         sp<RpcSession> session;
244         sp<IBinder> root;
245     };
246 
247     // client session objects associated with other process
248     // each one represents a separate session
249     std::vector<SessionInfo> sessions;
250 
251     ProcessSession(ProcessSession&&) = default;
~ProcessSessionandroid::ProcessSession252     ~ProcessSession() {
253         for (auto& session : sessions) {
254             session.root = nullptr;
255         }
256 
257         for (auto& info : sessions) {
258             sp<RpcSession>& session = info.session;
259 
260             EXPECT_NE(nullptr, session);
261             EXPECT_NE(nullptr, session->state());
262             EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
263 
264             wp<RpcSession> weakSession = session;
265             session = nullptr;
266             EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
267         }
268     }
269 };
270 
271 // Process session where the process hosts IBinderRpcTest, the server used
272 // for most testing here
273 struct BinderRpcTestProcessSession {
274     ProcessSession proc;
275 
276     // pre-fetched root object (for first session)
277     sp<IBinder> rootBinder;
278 
279     // pre-casted root object (for first session)
280     sp<IBinderRpcTest> rootIface;
281 
282     // whether session should be invalidated by end of run
283     bool expectInvalid = false;
284 
285     BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
~BinderRpcTestProcessSessionandroid::BinderRpcTestProcessSession286     ~BinderRpcTestProcessSession() {
287         if (!expectInvalid) {
288             std::vector<int32_t> remoteCounts;
289             // calling over any sessions counts across all sessions
290             EXPECT_OK(rootIface->countBinders(&remoteCounts));
291             EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
292             for (auto remoteCount : remoteCounts) {
293                 EXPECT_EQ(remoteCount, 1);
294             }
295         }
296 
297         rootIface = nullptr;
298         rootBinder = nullptr;
299     }
300 };
301 
302 enum class SocketType {
303     UNIX,
304     VSOCK,
305     INET,
306 };
PrintSocketType(const testing::TestParamInfo<SocketType> & info)307 static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
308     switch (info.param) {
309         case SocketType::UNIX:
310             return "unix_domain_socket";
311         case SocketType::VSOCK:
312             return "vm_socket";
313         case SocketType::INET:
314             return "inet_socket";
315         default:
316             LOG_ALWAYS_FATAL("Unknown socket type");
317             return "";
318     }
319 }
320 class BinderRpc : public ::testing::TestWithParam<SocketType> {
321 public:
322     // This creates a new process serving an interface on a certain number of
323     // threads.
createRpcTestSocketServerProcess(size_t numThreads,size_t numSessions,const std::function<void (const sp<RpcServer> &)> & configure)324     ProcessSession createRpcTestSocketServerProcess(
325             size_t numThreads, size_t numSessions,
326             const std::function<void(const sp<RpcServer>&)>& configure) {
327         CHECK_GE(numSessions, 1) << "Must have at least one session to a server";
328 
329         SocketType socketType = GetParam();
330 
331         std::string addr = allocateSocketAddress();
332         unlink(addr.c_str());
333         static unsigned int vsockPort = 3456;
334         vsockPort++;
335 
336         auto ret = ProcessSession{
337                 .host = Process([&](Pipe* pipe) {
338                     sp<RpcServer> server = RpcServer::make();
339 
340                     server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
341                     server->setMaxThreads(numThreads);
342 
343                     unsigned int outPort = 0;
344 
345                     switch (socketType) {
346                         case SocketType::UNIX:
347                             CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
348                             break;
349                         case SocketType::VSOCK:
350                             CHECK(server->setupVsockServer(vsockPort));
351                             break;
352                         case SocketType::INET: {
353                             CHECK(server->setupInetServer(0, &outPort));
354                             CHECK_NE(0, outPort);
355                             break;
356                         }
357                         default:
358                             LOG_ALWAYS_FATAL("Unknown socket type");
359                     }
360 
361                     CHECK(android::base::WriteFully(pipe->writeEnd(), &outPort, sizeof(outPort)));
362 
363                     configure(server);
364 
365                     server->join();
366                 }),
367         };
368 
369         // always read socket, so that we have waited for the server to start
370         unsigned int outPort = 0;
371         CHECK(android::base::ReadFully(ret.host.getPipe()->readEnd(), &outPort, sizeof(outPort)));
372         if (socketType == SocketType::INET) {
373             CHECK_NE(0, outPort);
374         }
375 
376         for (size_t i = 0; i < numSessions; i++) {
377             sp<RpcSession> session = RpcSession::make();
378             switch (socketType) {
379                 case SocketType::UNIX:
380                     if (session->setupUnixDomainClient(addr.c_str())) goto success;
381                     break;
382                 case SocketType::VSOCK:
383                     if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
384                     break;
385                 case SocketType::INET:
386                     if (session->setupInetClient("127.0.0.1", outPort)) goto success;
387                     break;
388                 default:
389                     LOG_ALWAYS_FATAL("Unknown socket type");
390             }
391             LOG_ALWAYS_FATAL("Could not connect");
392         success:
393             ret.sessions.push_back({session, session->getRootObject()});
394         }
395         return ret;
396     }
397 
createRpcTestSocketServerProcess(size_t numThreads,size_t numSessions=1)398     BinderRpcTestProcessSession createRpcTestSocketServerProcess(size_t numThreads,
399                                                                  size_t numSessions = 1) {
400         BinderRpcTestProcessSession ret{
401                 .proc = createRpcTestSocketServerProcess(numThreads, numSessions,
402                                                          [&](const sp<RpcServer>& server) {
403                                                              sp<MyBinderRpcTest> service =
404                                                                      new MyBinderRpcTest;
405                                                              server->setRootObject(service);
406                                                              service->server = server;
407                                                          }),
408         };
409 
410         ret.rootBinder = ret.proc.sessions.at(0).root;
411         ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
412 
413         return ret;
414     }
415 };
416 
TEST_P(BinderRpc,RootObjectIsNull)417 TEST_P(BinderRpc, RootObjectIsNull) {
418     auto proc = createRpcTestSocketServerProcess(1, 1, [](const sp<RpcServer>& server) {
419         // this is the default, but to be explicit
420         server->setRootObject(nullptr);
421     });
422 
423     EXPECT_EQ(nullptr, proc.sessions.at(0).root);
424 }
425 
TEST_P(BinderRpc,Ping)426 TEST_P(BinderRpc, Ping) {
427     auto proc = createRpcTestSocketServerProcess(1);
428     ASSERT_NE(proc.rootBinder, nullptr);
429     EXPECT_EQ(OK, proc.rootBinder->pingBinder());
430 }
431 
TEST_P(BinderRpc,GetInterfaceDescriptor)432 TEST_P(BinderRpc, GetInterfaceDescriptor) {
433     auto proc = createRpcTestSocketServerProcess(1);
434     ASSERT_NE(proc.rootBinder, nullptr);
435     EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
436 }
437 
TEST_P(BinderRpc,MultipleSessions)438 TEST_P(BinderRpc, MultipleSessions) {
439     auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 5 /*sessions*/);
440     for (auto session : proc.proc.sessions) {
441         ASSERT_NE(nullptr, session.root);
442         EXPECT_EQ(OK, session.root->pingBinder());
443     }
444 }
445 
TEST_P(BinderRpc,TransactionsMustBeMarkedRpc)446 TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
447     auto proc = createRpcTestSocketServerProcess(1);
448     Parcel data;
449     Parcel reply;
450     EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
451 }
452 
TEST_P(BinderRpc,AppendSeparateFormats)453 TEST_P(BinderRpc, AppendSeparateFormats) {
454     auto proc = createRpcTestSocketServerProcess(1);
455 
456     Parcel p1;
457     p1.markForBinder(proc.rootBinder);
458     p1.writeInt32(3);
459 
460     Parcel p2;
461 
462     EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
463     EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
464 }
465 
TEST_P(BinderRpc,UnknownTransaction)466 TEST_P(BinderRpc, UnknownTransaction) {
467     auto proc = createRpcTestSocketServerProcess(1);
468     Parcel data;
469     data.markForBinder(proc.rootBinder);
470     Parcel reply;
471     EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
472 }
473 
TEST_P(BinderRpc,SendSomethingOneway)474 TEST_P(BinderRpc, SendSomethingOneway) {
475     auto proc = createRpcTestSocketServerProcess(1);
476     EXPECT_OK(proc.rootIface->sendString("asdf"));
477 }
478 
TEST_P(BinderRpc,SendAndGetResultBack)479 TEST_P(BinderRpc, SendAndGetResultBack) {
480     auto proc = createRpcTestSocketServerProcess(1);
481     std::string doubled;
482     EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
483     EXPECT_EQ("cool cool ", doubled);
484 }
485 
TEST_P(BinderRpc,SendAndGetResultBackBig)486 TEST_P(BinderRpc, SendAndGetResultBackBig) {
487     auto proc = createRpcTestSocketServerProcess(1);
488     std::string single = std::string(1024, 'a');
489     std::string doubled;
490     EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
491     EXPECT_EQ(single + single, doubled);
492 }
493 
TEST_P(BinderRpc,CallMeBack)494 TEST_P(BinderRpc, CallMeBack) {
495     auto proc = createRpcTestSocketServerProcess(1);
496 
497     int32_t pingResult;
498     EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
499     EXPECT_EQ(OK, pingResult);
500 
501     EXPECT_EQ(0, MyBinderRpcSession::gNum);
502 }
503 
TEST_P(BinderRpc,RepeatBinder)504 TEST_P(BinderRpc, RepeatBinder) {
505     auto proc = createRpcTestSocketServerProcess(1);
506 
507     sp<IBinder> inBinder = new MyBinderRpcSession("foo");
508     sp<IBinder> outBinder;
509     EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
510     EXPECT_EQ(inBinder, outBinder);
511 
512     wp<IBinder> weak = inBinder;
513     inBinder = nullptr;
514     outBinder = nullptr;
515 
516     // Force reading a reply, to process any pending dec refs from the other
517     // process (the other process will process dec refs there before processing
518     // the ping here).
519     EXPECT_EQ(OK, proc.rootBinder->pingBinder());
520 
521     EXPECT_EQ(nullptr, weak.promote());
522 
523     EXPECT_EQ(0, MyBinderRpcSession::gNum);
524 }
525 
TEST_P(BinderRpc,RepeatTheirBinder)526 TEST_P(BinderRpc, RepeatTheirBinder) {
527     auto proc = createRpcTestSocketServerProcess(1);
528 
529     sp<IBinderRpcSession> session;
530     EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
531 
532     sp<IBinder> inBinder = IInterface::asBinder(session);
533     sp<IBinder> outBinder;
534     EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
535     EXPECT_EQ(inBinder, outBinder);
536 
537     wp<IBinder> weak = inBinder;
538     session = nullptr;
539     inBinder = nullptr;
540     outBinder = nullptr;
541 
542     // Force reading a reply, to process any pending dec refs from the other
543     // process (the other process will process dec refs there before processing
544     // the ping here).
545     EXPECT_EQ(OK, proc.rootBinder->pingBinder());
546 
547     EXPECT_EQ(nullptr, weak.promote());
548 }
549 
TEST_P(BinderRpc,RepeatBinderNull)550 TEST_P(BinderRpc, RepeatBinderNull) {
551     auto proc = createRpcTestSocketServerProcess(1);
552 
553     sp<IBinder> outBinder;
554     EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
555     EXPECT_EQ(nullptr, outBinder);
556 }
557 
TEST_P(BinderRpc,HoldBinder)558 TEST_P(BinderRpc, HoldBinder) {
559     auto proc = createRpcTestSocketServerProcess(1);
560 
561     IBinder* ptr = nullptr;
562     {
563         sp<IBinder> binder = new BBinder();
564         ptr = binder.get();
565         EXPECT_OK(proc.rootIface->holdBinder(binder));
566     }
567 
568     sp<IBinder> held;
569     EXPECT_OK(proc.rootIface->getHeldBinder(&held));
570 
571     EXPECT_EQ(held.get(), ptr);
572 
573     // stop holding binder, because we test to make sure references are cleaned
574     // up
575     EXPECT_OK(proc.rootIface->holdBinder(nullptr));
576     // and flush ref counts
577     EXPECT_EQ(OK, proc.rootBinder->pingBinder());
578 }
579 
580 // START TESTS FOR LIMITATIONS OF SOCKET BINDER
581 // These are behavioral differences form regular binder, where certain usecases
582 // aren't supported.
583 
TEST_P(BinderRpc,CannotMixBindersBetweenUnrelatedSocketSessions)584 TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
585     auto proc1 = createRpcTestSocketServerProcess(1);
586     auto proc2 = createRpcTestSocketServerProcess(1);
587 
588     sp<IBinder> outBinder;
589     EXPECT_EQ(INVALID_OPERATION,
590               proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
591 }
592 
TEST_P(BinderRpc,CannotMixBindersBetweenTwoSessionsToTheSameServer)593 TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
594     auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 2 /*sessions*/);
595 
596     sp<IBinder> outBinder;
597     EXPECT_EQ(INVALID_OPERATION,
598               proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
599                       .transactionError());
600 }
601 
TEST_P(BinderRpc,CannotSendRegularBinderOverSocketBinder)602 TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
603     auto proc = createRpcTestSocketServerProcess(1);
604 
605     sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
606     sp<IBinder> outBinder;
607     EXPECT_EQ(INVALID_OPERATION,
608               proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
609 }
610 
TEST_P(BinderRpc,CannotSendSocketBinderOverRegularBinder)611 TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
612     auto proc = createRpcTestSocketServerProcess(1);
613 
614     // for historical reasons, IServiceManager interface only returns the
615     // exception code
616     EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
617               defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
618 }
619 
620 // END TESTS FOR LIMITATIONS OF SOCKET BINDER
621 
TEST_P(BinderRpc,RepeatRootObject)622 TEST_P(BinderRpc, RepeatRootObject) {
623     auto proc = createRpcTestSocketServerProcess(1);
624 
625     sp<IBinder> outBinder;
626     EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
627     EXPECT_EQ(proc.rootBinder, outBinder);
628 }
629 
TEST_P(BinderRpc,NestedTransactions)630 TEST_P(BinderRpc, NestedTransactions) {
631     auto proc = createRpcTestSocketServerProcess(1);
632 
633     auto nastyNester = sp<MyBinderRpcTest>::make();
634     EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
635 
636     wp<IBinder> weak = nastyNester;
637     nastyNester = nullptr;
638     EXPECT_EQ(nullptr, weak.promote());
639 }
640 
TEST_P(BinderRpc,SameBinderEquality)641 TEST_P(BinderRpc, SameBinderEquality) {
642     auto proc = createRpcTestSocketServerProcess(1);
643 
644     sp<IBinder> a;
645     EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
646 
647     sp<IBinder> b;
648     EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
649 
650     EXPECT_EQ(a, b);
651 }
652 
TEST_P(BinderRpc,SameBinderEqualityWeak)653 TEST_P(BinderRpc, SameBinderEqualityWeak) {
654     auto proc = createRpcTestSocketServerProcess(1);
655 
656     sp<IBinder> a;
657     EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
658     wp<IBinder> weak = a;
659     a = nullptr;
660 
661     sp<IBinder> b;
662     EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
663 
664     // this is the wrong behavior, since BpBinder
665     // doesn't implement onIncStrongAttempted
666     // but make sure there is no crash
667     EXPECT_EQ(nullptr, weak.promote());
668 
669     GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
670 
671     // In order to fix this:
672     // - need to have incStrongAttempted reflected across IPC boundary (wait for
673     //   response to promote - round trip...)
674     // - sendOnLastWeakRef, to delete entries out of RpcState table
675     EXPECT_EQ(b, weak.promote());
676 }
677 
678 #define expectSessions(expected, iface)                   \
679     do {                                                  \
680         int session;                                      \
681         EXPECT_OK((iface)->getNumOpenSessions(&session)); \
682         EXPECT_EQ(expected, session);                     \
683     } while (false)
684 
TEST_P(BinderRpc,SingleSession)685 TEST_P(BinderRpc, SingleSession) {
686     auto proc = createRpcTestSocketServerProcess(1);
687 
688     sp<IBinderRpcSession> session;
689     EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
690     std::string out;
691     EXPECT_OK(session->getName(&out));
692     EXPECT_EQ("aoeu", out);
693 
694     expectSessions(1, proc.rootIface);
695     session = nullptr;
696     expectSessions(0, proc.rootIface);
697 }
698 
TEST_P(BinderRpc,ManySessions)699 TEST_P(BinderRpc, ManySessions) {
700     auto proc = createRpcTestSocketServerProcess(1);
701 
702     std::vector<sp<IBinderRpcSession>> sessions;
703 
704     for (size_t i = 0; i < 15; i++) {
705         expectSessions(i, proc.rootIface);
706         sp<IBinderRpcSession> session;
707         EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
708         sessions.push_back(session);
709     }
710     expectSessions(sessions.size(), proc.rootIface);
711     for (size_t i = 0; i < sessions.size(); i++) {
712         std::string out;
713         EXPECT_OK(sessions.at(i)->getName(&out));
714         EXPECT_EQ(std::to_string(i), out);
715     }
716     expectSessions(sessions.size(), proc.rootIface);
717 
718     while (!sessions.empty()) {
719         sessions.pop_back();
720         expectSessions(sessions.size(), proc.rootIface);
721     }
722     expectSessions(0, proc.rootIface);
723 }
724 
epochMillis()725 size_t epochMillis() {
726     using std::chrono::duration_cast;
727     using std::chrono::milliseconds;
728     using std::chrono::seconds;
729     using std::chrono::system_clock;
730     return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
731 }
732 
TEST_P(BinderRpc,ThreadPoolGreaterThanEqualRequested)733 TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
734     constexpr size_t kNumThreads = 10;
735 
736     auto proc = createRpcTestSocketServerProcess(kNumThreads);
737 
738     EXPECT_OK(proc.rootIface->lock());
739 
740     // block all but one thread taking locks
741     std::vector<std::thread> ts;
742     for (size_t i = 0; i < kNumThreads - 1; i++) {
743         ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
744     }
745 
746     usleep(100000); // give chance for calls on other threads
747 
748     // other calls still work
749     EXPECT_EQ(OK, proc.rootBinder->pingBinder());
750 
751     constexpr size_t blockTimeMs = 500;
752     size_t epochMsBefore = epochMillis();
753     // after this, we should never see a response within this time
754     EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
755 
756     // this call should be blocked for blockTimeMs
757     EXPECT_EQ(OK, proc.rootBinder->pingBinder());
758 
759     size_t epochMsAfter = epochMillis();
760     EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
761 
762     for (auto& t : ts) t.join();
763 }
764 
TEST_P(BinderRpc,ThreadPoolOverSaturated)765 TEST_P(BinderRpc, ThreadPoolOverSaturated) {
766     constexpr size_t kNumThreads = 10;
767     constexpr size_t kNumCalls = kNumThreads + 3;
768     constexpr size_t kSleepMs = 500;
769 
770     auto proc = createRpcTestSocketServerProcess(kNumThreads);
771 
772     size_t epochMsBefore = epochMillis();
773 
774     std::vector<std::thread> ts;
775     for (size_t i = 0; i < kNumCalls; i++) {
776         ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
777     }
778 
779     for (auto& t : ts) t.join();
780 
781     size_t epochMsAfter = epochMillis();
782 
783     EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
784 
785     // Potential flake, but make sure calls are handled in parallel.
786     EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
787 }
788 
TEST_P(BinderRpc,ThreadingStressTest)789 TEST_P(BinderRpc, ThreadingStressTest) {
790     constexpr size_t kNumClientThreads = 10;
791     constexpr size_t kNumServerThreads = 10;
792     constexpr size_t kNumCalls = 100;
793 
794     auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
795 
796     std::vector<std::thread> threads;
797     for (size_t i = 0; i < kNumClientThreads; i++) {
798         threads.push_back(std::thread([&] {
799             for (size_t j = 0; j < kNumCalls; j++) {
800                 sp<IBinder> out;
801                 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
802                 EXPECT_EQ(proc.rootBinder, out);
803             }
804         }));
805     }
806 
807     for (auto& t : threads) t.join();
808 }
809 
TEST_P(BinderRpc,OnewayStressTest)810 TEST_P(BinderRpc, OnewayStressTest) {
811     constexpr size_t kNumClientThreads = 10;
812     constexpr size_t kNumServerThreads = 10;
813     constexpr size_t kNumCalls = 100;
814 
815     auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
816 
817     std::vector<std::thread> threads;
818     for (size_t i = 0; i < kNumClientThreads; i++) {
819         threads.push_back(std::thread([&] {
820             for (size_t j = 0; j < kNumCalls; j++) {
821                 EXPECT_OK(proc.rootIface->sendString("a"));
822             }
823 
824             // check threads are not stuck
825             EXPECT_OK(proc.rootIface->sleepMs(250));
826         }));
827     }
828 
829     for (auto& t : threads) t.join();
830 }
831 
TEST_P(BinderRpc,OnewayCallDoesNotWait)832 TEST_P(BinderRpc, OnewayCallDoesNotWait) {
833     constexpr size_t kReallyLongTimeMs = 100;
834     constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
835 
836     // more than one thread, just so this doesn't deadlock
837     auto proc = createRpcTestSocketServerProcess(2);
838 
839     size_t epochMsBefore = epochMillis();
840 
841     EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
842 
843     size_t epochMsAfter = epochMillis();
844     EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
845 }
846 
TEST_P(BinderRpc,OnewayCallQueueing)847 TEST_P(BinderRpc, OnewayCallQueueing) {
848     constexpr size_t kNumSleeps = 10;
849     constexpr size_t kNumExtraServerThreads = 4;
850     constexpr size_t kSleepMs = 50;
851 
852     // make sure calls to the same object happen on the same thread
853     auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
854 
855     EXPECT_OK(proc.rootIface->lock());
856 
857     for (size_t i = 0; i < kNumSleeps; i++) {
858         // these should be processed serially
859         proc.rootIface->sleepMsAsync(kSleepMs);
860     }
861     // should also be processesed serially
862     EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
863 
864     size_t epochMsBefore = epochMillis();
865     EXPECT_OK(proc.rootIface->lockUnlock());
866     size_t epochMsAfter = epochMillis();
867 
868     EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
869 }
870 
TEST_P(BinderRpc,Die)871 TEST_P(BinderRpc, Die) {
872     for (bool doDeathCleanup : {true, false}) {
873         auto proc = createRpcTestSocketServerProcess(1);
874 
875         // make sure there is some state during crash
876         // 1. we hold their binder
877         sp<IBinderRpcSession> session;
878         EXPECT_OK(proc.rootIface->openSession("happy", &session));
879         // 2. they hold our binder
880         sp<IBinder> binder = new BBinder();
881         EXPECT_OK(proc.rootIface->holdBinder(binder));
882 
883         EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
884                 << "Do death cleanup: " << doDeathCleanup;
885 
886         proc.expectInvalid = true;
887     }
888 }
889 
TEST_P(BinderRpc,WorksWithLibbinderNdkPing)890 TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
891     auto proc = createRpcTestSocketServerProcess(1);
892 
893     ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
894     ASSERT_NE(binder, nullptr);
895 
896     ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
897 }
898 
TEST_P(BinderRpc,WorksWithLibbinderNdkUserTransaction)899 TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
900     auto proc = createRpcTestSocketServerProcess(1);
901 
902     ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
903     ASSERT_NE(binder, nullptr);
904 
905     auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
906     ASSERT_NE(ndkBinder, nullptr);
907 
908     std::string out;
909     ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
910     ASSERT_TRUE(status.isOk()) << status.getDescription();
911     ASSERT_EQ("aoeuaoeu", out);
912 }
913 
countFds()914 ssize_t countFds() {
915     DIR* dir = opendir("/proc/self/fd/");
916     if (dir == nullptr) return -1;
917     ssize_t ret = 0;
918     dirent* ent;
919     while ((ent = readdir(dir)) != nullptr) ret++;
920     closedir(dir);
921     return ret;
922 }
923 
TEST_P(BinderRpc,Fds)924 TEST_P(BinderRpc, Fds) {
925     ssize_t beforeFds = countFds();
926     ASSERT_GE(beforeFds, 0);
927     {
928         auto proc = createRpcTestSocketServerProcess(10);
929         ASSERT_EQ(OK, proc.rootBinder->pingBinder());
930     }
931     ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
932 }
933 
934 INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
935                         ::testing::ValuesIn({
936                                 SocketType::UNIX,
937 // TODO(b/185269356): working on host
938 #ifdef __BIONIC__
939                                 SocketType::VSOCK,
940 #endif
941                                 SocketType::INET,
942                         }),
943                         PrintSocketType);
944 
945 class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
946 
TEST_P(BinderRpcServerRootObject,WeakRootObject)947 TEST_P(BinderRpcServerRootObject, WeakRootObject) {
948     using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
949     auto setRootObject = [](bool isStrong) -> SetFn {
950         return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
951     };
952 
953     auto server = RpcServer::make();
954     auto [isStrong1, isStrong2] = GetParam();
955     auto binder1 = sp<BBinder>::make();
956     IBinder* binderRaw1 = binder1.get();
957     setRootObject(isStrong1)(server.get(), binder1);
958     EXPECT_EQ(binderRaw1, server->getRootObject());
959     binder1.clear();
960     EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
961 
962     auto binder2 = sp<BBinder>::make();
963     IBinder* binderRaw2 = binder2.get();
964     setRootObject(isStrong2)(server.get(), binder2);
965     EXPECT_EQ(binderRaw2, server->getRootObject());
966     binder2.clear();
967     EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
968 }
969 
970 INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
971                         ::testing::Combine(::testing::Bool(), ::testing::Bool()));
972 
973 } // namespace android
974 
main(int argc,char ** argv)975 int main(int argc, char** argv) {
976     ::testing::InitGoogleTest(&argc, argv);
977     android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
978     return RUN_ALL_TESTS();
979 }
980