blob: 985a3014d489cdf73e78c40730339cad7c0891cd [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Steven Moreland5553ac42020-11-11 02:14:45 +000017#include <BnBinderRpcSession.h>
18#include <BnBinderRpcTest.h>
19#include <android-base/logging.h>
20#include <binder/Binder.h>
21#include <binder/BpBinder.h>
22#include <binder/IServiceManager.h>
23#include <binder/ProcessState.h>
24#include <binder/RpcConnection.h>
25#include <binder/RpcServer.h>
26#include <gtest/gtest.h>
27
Steven Morelandc1635952021-04-01 16:20:47 +000028#include <chrono>
29#include <cstdlib>
30#include <iostream>
31#include <thread>
32
33#include <linux/vm_sockets.h>
34#include <sys/prctl.h>
35#include <unistd.h>
36
Steven Moreland5553ac42020-11-11 02:14:45 +000037#include "../RpcState.h" // for debugging
38
39namespace android {
40
41using android::binder::Status;
42
43#define EXPECT_OK(status) \
44 do { \
45 Status stat = (status); \
46 EXPECT_TRUE(stat.isOk()) << stat; \
47 } while (false)
48
49class MyBinderRpcSession : public BnBinderRpcSession {
50public:
51 static std::atomic<int32_t> gNum;
52
53 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
54 Status getName(std::string* name) override {
55 *name = mName;
56 return Status::ok();
57 }
58 ~MyBinderRpcSession() { gNum--; }
59
60private:
61 std::string mName;
62};
63std::atomic<int32_t> MyBinderRpcSession::gNum;
64
65class MyBinderRpcTest : public BnBinderRpcTest {
66public:
67 sp<RpcConnection> connection;
68
69 Status sendString(const std::string& str) override {
70 std::cout << "Child received string: " << str << std::endl;
71 return Status::ok();
72 }
73 Status doubleString(const std::string& str, std::string* strstr) override {
74 std::cout << "Child received string to double: " << str << std::endl;
75 *strstr = str + str;
76 return Status::ok();
77 }
78 Status countBinders(int32_t* out) override {
79 if (connection == nullptr) {
80 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
81 }
82 *out = connection->state()->countBinders();
83 if (*out != 1) {
84 connection->state()->dump();
85 }
86 return Status::ok();
87 }
88 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
89 if (binder == nullptr) {
90 std::cout << "Received null binder!" << std::endl;
91 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
92 }
93 *out = binder->pingBinder();
94 return Status::ok();
95 }
96 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
97 *out = binder;
98 return Status::ok();
99 }
100 static sp<IBinder> mHeldBinder;
101 Status holdBinder(const sp<IBinder>& binder) override {
102 mHeldBinder = binder;
103 return Status::ok();
104 }
105 Status getHeldBinder(sp<IBinder>* held) override {
106 *held = mHeldBinder;
107 return Status::ok();
108 }
109 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
110 if (count <= 0) return Status::ok();
111 return binder->nestMe(this, count - 1);
112 }
113 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
114 static sp<IBinder> binder = new BBinder;
115 *out = binder;
116 return Status::ok();
117 }
118 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
119 *out = new MyBinderRpcSession(name);
120 return Status::ok();
121 }
122 Status getNumOpenSessions(int32_t* out) override {
123 *out = MyBinderRpcSession::gNum;
124 return Status::ok();
125 }
126
127 std::mutex blockMutex;
128 Status lock() override {
129 blockMutex.lock();
130 return Status::ok();
131 }
132 Status unlockInMsAsync(int32_t ms) override {
133 usleep(ms * 1000);
134 blockMutex.unlock();
135 return Status::ok();
136 }
137 Status lockUnlock() override {
138 std::lock_guard<std::mutex> _l(blockMutex);
139 return Status::ok();
140 }
141
142 Status sleepMs(int32_t ms) override {
143 usleep(ms * 1000);
144 return Status::ok();
145 }
146
147 Status sleepMsAsync(int32_t ms) override {
148 // In-process binder calls are asynchronous, but the call to this method
149 // is synchronous wrt its client. This in/out-process threading model
150 // diffentiation is a classic binder leaky abstraction (for better or
151 // worse) and is preserved here the way binder sockets plugs itself
152 // into BpBinder, as nothing is changed at the higher levels
153 // (IInterface) which result in this behavior.
154 return sleepMs(ms);
155 }
156
157 Status die(bool cleanup) override {
158 if (cleanup) {
159 exit(1);
160 } else {
161 _exit(1);
162 }
163 }
164};
165sp<IBinder> MyBinderRpcTest::mHeldBinder;
166
167class Process {
168public:
169 Process(const std::function<void()>& f) {
170 if (0 == (mPid = fork())) {
171 // racey: assume parent doesn't crash before this is set
172 prctl(PR_SET_PDEATHSIG, SIGHUP);
173
174 f();
175 }
176 }
177 ~Process() {
178 if (mPid != 0) {
179 kill(mPid, SIGKILL);
180 }
181 }
182
183private:
184 pid_t mPid = 0;
185};
186
187static std::string allocateSocketAddress() {
188 static size_t id = 0;
189
Nikita Ioffe92a9c782021-04-01 11:06:40 +0000190 return "/dev/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000191};
192
193struct ProcessConnection {
194 // reference to process hosting a socket server
195 Process host;
196
197 // client connection object associated with other process
198 sp<RpcConnection> connection;
199
200 // pre-fetched root object
201 sp<IBinder> rootBinder;
202
203 // whether connection should be invalidated by end of run
204 bool expectInvalid = false;
205
206 ~ProcessConnection() {
207 rootBinder = nullptr;
208 EXPECT_NE(nullptr, connection);
209 EXPECT_NE(nullptr, connection->state());
210 EXPECT_EQ(0, connection->state()->countBinders()) << (connection->state()->dump(), "dump:");
211
212 wp<RpcConnection> weakConnection = connection;
213 connection = nullptr;
214 EXPECT_EQ(nullptr, weakConnection.promote()) << "Leaked connection";
215 }
216};
217
Steven Moreland5553ac42020-11-11 02:14:45 +0000218// Process connection where the process hosts IBinderRpcTest, the server used
219// for most testing here
220struct BinderRpcTestProcessConnection {
221 ProcessConnection proc;
222
223 // pre-fetched root object
224 sp<IBinder> rootBinder;
225
226 // pre-casted root object
227 sp<IBinderRpcTest> rootIface;
228
229 ~BinderRpcTestProcessConnection() {
230 if (!proc.expectInvalid) {
231 int32_t remoteBinders = 0;
232 EXPECT_OK(rootIface->countBinders(&remoteBinders));
233 // should only be the root binder object, iface
234 EXPECT_EQ(remoteBinders, 1);
235 }
236
237 rootIface = nullptr;
238 rootBinder = nullptr;
239 }
240};
241
Steven Morelandc1635952021-04-01 16:20:47 +0000242enum class SocketType {
243 UNIX,
244 VSOCK,
245};
246static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
247 switch (info.param) {
248 case SocketType::UNIX:
249 return "unix_domain_socket";
250 case SocketType::VSOCK:
251 return "vm_socket";
252 default:
253 LOG_ALWAYS_FATAL("Unknown socket type");
254 return "";
255 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000256}
Steven Morelandc1635952021-04-01 16:20:47 +0000257class BinderRpc : public ::testing::TestWithParam<SocketType> {
258public:
259 // This creates a new process serving an interface on a certain number of
260 // threads.
261 ProcessConnection createRpcTestSocketServerProcess(
262 size_t numThreads,
263 const std::function<void(const sp<RpcServer>&, const sp<RpcConnection>&)>& configure) {
264 CHECK_GT(numThreads, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000265
Steven Morelandc1635952021-04-01 16:20:47 +0000266 SocketType socketType = GetParam();
267
268 std::string addr = allocateSocketAddress();
269 unlink(addr.c_str());
270 static unsigned int port = 3456;
271 port++;
272
273 auto ret = ProcessConnection{
274 .host = Process([&] {
275 sp<RpcServer> server = RpcServer::make();
276
277 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
278
279 // server supporting one client on one socket
280 sp<RpcConnection> connection = server->addClientConnection();
281
282 switch (socketType) {
283 case SocketType::UNIX:
284 CHECK(connection->setupUnixDomainServer(addr.c_str())) << addr;
285 break;
286 case SocketType::VSOCK:
287 CHECK(connection->setupVsockServer(port));
288 break;
289 default:
290 LOG_ALWAYS_FATAL("Unknown socket type");
291 }
292
293 configure(server, connection);
294
295 // accept 'numThreads' connections
296 std::vector<std::thread> pool;
297 for (size_t i = 0; i + 1 < numThreads; i++) {
298 pool.push_back(std::thread([=] { connection->join(); }));
299 }
300 connection->join();
301 for (auto& t : pool) t.join();
302 }),
303 .connection = RpcConnection::make(),
304 };
305
306 // create remainder of connections
307 for (size_t i = 0; i < numThreads; i++) {
308 for (size_t tries = 0; tries < 5; tries++) {
309 usleep(10000);
310 switch (socketType) {
311 case SocketType::UNIX:
312 if (ret.connection->addUnixDomainClient(addr.c_str())) goto success;
313 break;
314 case SocketType::VSOCK:
315 if (ret.connection->addVsockClient(VMADDR_CID_LOCAL, port)) goto success;
316 break;
317 default:
318 LOG_ALWAYS_FATAL("Unknown socket type");
319 }
320 }
321 LOG_ALWAYS_FATAL("Could not connect");
322 success:;
323 }
324
325 ret.rootBinder = ret.connection->getRootObject();
326 return ret;
327 }
328
329 BinderRpcTestProcessConnection createRpcTestSocketServerProcess(size_t numThreads) {
330 BinderRpcTestProcessConnection ret{
331 .proc = createRpcTestSocketServerProcess(numThreads,
332 [&](const sp<RpcServer>& server,
333 const sp<RpcConnection>& connection) {
334 sp<MyBinderRpcTest> service =
335 new MyBinderRpcTest;
336 server->setRootObject(service);
337 service->connection =
338 connection; // for testing only
339 }),
340 };
341
342 ret.rootBinder = ret.proc.rootBinder;
343 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
344
345 return ret;
346 }
347};
348
349TEST_P(BinderRpc, RootObjectIsNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000350 auto proc = createRpcTestSocketServerProcess(1,
351 [](const sp<RpcServer>& server,
352 const sp<RpcConnection>&) {
353 // this is the default, but to be explicit
354 server->setRootObject(nullptr);
355 });
356
357 // retrieved by getRootObject when process is created above
358 EXPECT_EQ(nullptr, proc.rootBinder);
359
360 // make sure we can retrieve it again (process doesn't crash)
361 EXPECT_EQ(nullptr, proc.connection->getRootObject());
362}
363
Steven Morelandc1635952021-04-01 16:20:47 +0000364TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000365 auto proc = createRpcTestSocketServerProcess(1);
366 ASSERT_NE(proc.rootBinder, nullptr);
367 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
368}
369
Steven Morelandc1635952021-04-01 16:20:47 +0000370TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000371 auto proc = createRpcTestSocketServerProcess(1);
372 Parcel data;
373 Parcel reply;
374 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
375}
376
Steven Morelandc1635952021-04-01 16:20:47 +0000377TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000378 auto proc = createRpcTestSocketServerProcess(1);
379 Parcel data;
380 data.markForBinder(proc.rootBinder);
381 Parcel reply;
382 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
383}
384
Steven Morelandc1635952021-04-01 16:20:47 +0000385TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000386 auto proc = createRpcTestSocketServerProcess(1);
387 EXPECT_OK(proc.rootIface->sendString("asdf"));
388}
389
Steven Morelandc1635952021-04-01 16:20:47 +0000390TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000391 auto proc = createRpcTestSocketServerProcess(1);
392 std::string doubled;
393 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
394 EXPECT_EQ("cool cool ", doubled);
395}
396
Steven Morelandc1635952021-04-01 16:20:47 +0000397TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000398 auto proc = createRpcTestSocketServerProcess(1);
399 std::string single = std::string(1024, 'a');
400 std::string doubled;
401 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
402 EXPECT_EQ(single + single, doubled);
403}
404
Steven Morelandc1635952021-04-01 16:20:47 +0000405TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000406 auto proc = createRpcTestSocketServerProcess(1);
407
408 int32_t pingResult;
409 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
410 EXPECT_EQ(OK, pingResult);
411
412 EXPECT_EQ(0, MyBinderRpcSession::gNum);
413}
414
Steven Morelandc1635952021-04-01 16:20:47 +0000415TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000416 auto proc = createRpcTestSocketServerProcess(1);
417
418 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
419 sp<IBinder> outBinder;
420 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
421 EXPECT_EQ(inBinder, outBinder);
422
423 wp<IBinder> weak = inBinder;
424 inBinder = nullptr;
425 outBinder = nullptr;
426
427 // Force reading a reply, to process any pending dec refs from the other
428 // process (the other process will process dec refs there before processing
429 // the ping here).
430 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
431
432 EXPECT_EQ(nullptr, weak.promote());
433
434 EXPECT_EQ(0, MyBinderRpcSession::gNum);
435}
436
Steven Morelandc1635952021-04-01 16:20:47 +0000437TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000438 auto proc = createRpcTestSocketServerProcess(1);
439
440 sp<IBinderRpcSession> session;
441 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
442
443 sp<IBinder> inBinder = IInterface::asBinder(session);
444 sp<IBinder> outBinder;
445 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
446 EXPECT_EQ(inBinder, outBinder);
447
448 wp<IBinder> weak = inBinder;
449 session = nullptr;
450 inBinder = nullptr;
451 outBinder = nullptr;
452
453 // Force reading a reply, to process any pending dec refs from the other
454 // process (the other process will process dec refs there before processing
455 // the ping here).
456 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
457
458 EXPECT_EQ(nullptr, weak.promote());
459}
460
Steven Morelandc1635952021-04-01 16:20:47 +0000461TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000462 auto proc = createRpcTestSocketServerProcess(1);
463
464 sp<IBinder> outBinder;
465 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
466 EXPECT_EQ(nullptr, outBinder);
467}
468
Steven Morelandc1635952021-04-01 16:20:47 +0000469TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000470 auto proc = createRpcTestSocketServerProcess(1);
471
472 IBinder* ptr = nullptr;
473 {
474 sp<IBinder> binder = new BBinder();
475 ptr = binder.get();
476 EXPECT_OK(proc.rootIface->holdBinder(binder));
477 }
478
479 sp<IBinder> held;
480 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
481
482 EXPECT_EQ(held.get(), ptr);
483
484 // stop holding binder, because we test to make sure references are cleaned
485 // up
486 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
487 // and flush ref counts
488 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
489}
490
491// START TESTS FOR LIMITATIONS OF SOCKET BINDER
492// These are behavioral differences form regular binder, where certain usecases
493// aren't supported.
494
Steven Morelandc1635952021-04-01 16:20:47 +0000495TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketConnections) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000496 auto proc1 = createRpcTestSocketServerProcess(1);
497 auto proc2 = createRpcTestSocketServerProcess(1);
498
499 sp<IBinder> outBinder;
500 EXPECT_EQ(INVALID_OPERATION,
501 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
502}
503
Steven Morelandc1635952021-04-01 16:20:47 +0000504TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000505 auto proc = createRpcTestSocketServerProcess(1);
506
507 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
508 sp<IBinder> outBinder;
509 EXPECT_EQ(INVALID_OPERATION,
510 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
511}
512
Steven Morelandc1635952021-04-01 16:20:47 +0000513TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000514 auto proc = createRpcTestSocketServerProcess(1);
515
516 // for historical reasons, IServiceManager interface only returns the
517 // exception code
518 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
519 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
520}
521
522// END TESTS FOR LIMITATIONS OF SOCKET BINDER
523
Steven Morelandc1635952021-04-01 16:20:47 +0000524TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000525 auto proc = createRpcTestSocketServerProcess(1);
526
527 sp<IBinder> outBinder;
528 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
529 EXPECT_EQ(proc.rootBinder, outBinder);
530}
531
Steven Morelandc1635952021-04-01 16:20:47 +0000532TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000533 auto proc = createRpcTestSocketServerProcess(1);
534
535 auto nastyNester = sp<MyBinderRpcTest>::make();
536 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
537
538 wp<IBinder> weak = nastyNester;
539 nastyNester = nullptr;
540 EXPECT_EQ(nullptr, weak.promote());
541}
542
Steven Morelandc1635952021-04-01 16:20:47 +0000543TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000544 auto proc = createRpcTestSocketServerProcess(1);
545
546 sp<IBinder> a;
547 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
548
549 sp<IBinder> b;
550 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
551
552 EXPECT_EQ(a, b);
553}
554
Steven Morelandc1635952021-04-01 16:20:47 +0000555TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000556 auto proc = createRpcTestSocketServerProcess(1);
557
558 sp<IBinder> a;
559 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
560 wp<IBinder> weak = a;
561 a = nullptr;
562
563 sp<IBinder> b;
564 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
565
566 // this is the wrong behavior, since BpBinder
567 // doesn't implement onIncStrongAttempted
568 // but make sure there is no crash
569 EXPECT_EQ(nullptr, weak.promote());
570
571 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
572
573 // In order to fix this:
574 // - need to have incStrongAttempted reflected across IPC boundary (wait for
575 // response to promote - round trip...)
576 // - sendOnLastWeakRef, to delete entries out of RpcState table
577 EXPECT_EQ(b, weak.promote());
578}
579
580#define expectSessions(expected, iface) \
581 do { \
582 int session; \
583 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
584 EXPECT_EQ(expected, session); \
585 } while (false)
586
Steven Morelandc1635952021-04-01 16:20:47 +0000587TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000588 auto proc = createRpcTestSocketServerProcess(1);
589
590 sp<IBinderRpcSession> session;
591 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
592 std::string out;
593 EXPECT_OK(session->getName(&out));
594 EXPECT_EQ("aoeu", out);
595
596 expectSessions(1, proc.rootIface);
597 session = nullptr;
598 expectSessions(0, proc.rootIface);
599}
600
Steven Morelandc1635952021-04-01 16:20:47 +0000601TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000602 auto proc = createRpcTestSocketServerProcess(1);
603
604 std::vector<sp<IBinderRpcSession>> sessions;
605
606 for (size_t i = 0; i < 15; i++) {
607 expectSessions(i, proc.rootIface);
608 sp<IBinderRpcSession> session;
609 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
610 sessions.push_back(session);
611 }
612 expectSessions(sessions.size(), proc.rootIface);
613 for (size_t i = 0; i < sessions.size(); i++) {
614 std::string out;
615 EXPECT_OK(sessions.at(i)->getName(&out));
616 EXPECT_EQ(std::to_string(i), out);
617 }
618 expectSessions(sessions.size(), proc.rootIface);
619
620 while (!sessions.empty()) {
621 sessions.pop_back();
622 expectSessions(sessions.size(), proc.rootIface);
623 }
624 expectSessions(0, proc.rootIface);
625}
626
627size_t epochMillis() {
628 using std::chrono::duration_cast;
629 using std::chrono::milliseconds;
630 using std::chrono::seconds;
631 using std::chrono::system_clock;
632 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
633}
634
Steven Morelandc1635952021-04-01 16:20:47 +0000635TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000636 constexpr size_t kNumThreads = 10;
637
638 auto proc = createRpcTestSocketServerProcess(kNumThreads);
639
640 EXPECT_OK(proc.rootIface->lock());
641
642 // block all but one thread taking locks
643 std::vector<std::thread> ts;
644 for (size_t i = 0; i < kNumThreads - 1; i++) {
645 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
646 }
647
648 usleep(100000); // give chance for calls on other threads
649
650 // other calls still work
651 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
652
653 constexpr size_t blockTimeMs = 500;
654 size_t epochMsBefore = epochMillis();
655 // after this, we should never see a response within this time
656 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
657
658 // this call should be blocked for blockTimeMs
659 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
660
661 size_t epochMsAfter = epochMillis();
662 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
663
664 for (auto& t : ts) t.join();
665}
666
Steven Morelandc1635952021-04-01 16:20:47 +0000667TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000668 constexpr size_t kNumThreads = 10;
669 constexpr size_t kNumCalls = kNumThreads + 3;
670 constexpr size_t kSleepMs = 500;
671
672 auto proc = createRpcTestSocketServerProcess(kNumThreads);
673
674 size_t epochMsBefore = epochMillis();
675
676 std::vector<std::thread> ts;
677 for (size_t i = 0; i < kNumCalls; i++) {
678 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
679 }
680
681 for (auto& t : ts) t.join();
682
683 size_t epochMsAfter = epochMillis();
684
685 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
686
687 // Potential flake, but make sure calls are handled in parallel.
688 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
689}
690
Steven Morelandc1635952021-04-01 16:20:47 +0000691TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000692 constexpr size_t kNumClientThreads = 10;
693 constexpr size_t kNumServerThreads = 10;
694 constexpr size_t kNumCalls = 100;
695
696 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
697
698 std::vector<std::thread> threads;
699 for (size_t i = 0; i < kNumClientThreads; i++) {
700 threads.push_back(std::thread([&] {
701 for (size_t j = 0; j < kNumCalls; j++) {
702 sp<IBinder> out;
703 proc.rootIface->repeatBinder(proc.rootBinder, &out);
704 EXPECT_EQ(proc.rootBinder, out);
705 }
706 }));
707 }
708
709 for (auto& t : threads) t.join();
710}
711
Steven Morelandc1635952021-04-01 16:20:47 +0000712TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000713 constexpr size_t kReallyLongTimeMs = 100;
714 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
715
716 // more than one thread, just so this doesn't deadlock
717 auto proc = createRpcTestSocketServerProcess(2);
718
719 size_t epochMsBefore = epochMillis();
720
721 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
722
723 size_t epochMsAfter = epochMillis();
724 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
725}
726
Steven Morelandc1635952021-04-01 16:20:47 +0000727TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000728 constexpr size_t kNumSleeps = 10;
729 constexpr size_t kNumExtraServerThreads = 4;
730 constexpr size_t kSleepMs = 50;
731
732 // make sure calls to the same object happen on the same thread
733 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
734
735 EXPECT_OK(proc.rootIface->lock());
736
737 for (size_t i = 0; i < kNumSleeps; i++) {
738 // these should be processed serially
739 proc.rootIface->sleepMsAsync(kSleepMs);
740 }
741 // should also be processesed serially
742 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
743
744 size_t epochMsBefore = epochMillis();
745 EXPECT_OK(proc.rootIface->lockUnlock());
746 size_t epochMsAfter = epochMillis();
747
748 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
749}
750
Steven Morelandc1635952021-04-01 16:20:47 +0000751TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000752 // TODO(b/183141167): handle this in library
753 signal(SIGPIPE, SIG_IGN);
754
755 for (bool doDeathCleanup : {true, false}) {
756 auto proc = createRpcTestSocketServerProcess(1);
757
758 // make sure there is some state during crash
759 // 1. we hold their binder
760 sp<IBinderRpcSession> session;
761 EXPECT_OK(proc.rootIface->openSession("happy", &session));
762 // 2. they hold our binder
763 sp<IBinder> binder = new BBinder();
764 EXPECT_OK(proc.rootIface->holdBinder(binder));
765
766 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
767 << "Do death cleanup: " << doDeathCleanup;
768
769 proc.proc.expectInvalid = true;
770 }
771}
772
773ssize_t countFds() {
774 DIR* dir = opendir("/proc/self/fd/");
775 if (dir == nullptr) return -1;
776 ssize_t ret = 0;
777 dirent* ent;
778 while ((ent = readdir(dir)) != nullptr) ret++;
779 closedir(dir);
780 return ret;
781}
782
Steven Morelandc1635952021-04-01 16:20:47 +0000783TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000784 ssize_t beforeFds = countFds();
785 ASSERT_GE(beforeFds, 0);
786 {
787 auto proc = createRpcTestSocketServerProcess(10);
788 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
789 }
790 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
791}
792
Steven Morelandc1635952021-04-01 16:20:47 +0000793INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
794 ::testing::Values(SocketType::UNIX, SocketType::VSOCK), PrintSocketType);
795
796} // namespace android
797
798int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000799 ::testing::InitGoogleTest(&argc, argv);
800 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
801 return RUN_ALL_TESTS();
802}