blob: 6fa53330ef3c73622806e5a2f35736c69d90a3b8 [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
Nikita Ioffe9630f9d2021-04-01 11:06:40 +000017#include <sys/prctl.h>
18#include <unistd.h>
19
20#include <chrono>
21#include <cstdlib>
22#include <iostream>
23#include <thread>
24
Steven Moreland5553ac42020-11-11 02:14:45 +000025#include <BnBinderRpcSession.h>
26#include <BnBinderRpcTest.h>
27#include <android-base/logging.h>
28#include <binder/Binder.h>
29#include <binder/BpBinder.h>
30#include <binder/IServiceManager.h>
31#include <binder/ProcessState.h>
32#include <binder/RpcConnection.h>
33#include <binder/RpcServer.h>
34#include <gtest/gtest.h>
35
36#include "../RpcState.h" // for debugging
37
38namespace android {
39
40using android::binder::Status;
41
42#define EXPECT_OK(status) \
43 do { \
44 Status stat = (status); \
45 EXPECT_TRUE(stat.isOk()) << stat; \
46 } while (false)
47
48class MyBinderRpcSession : public BnBinderRpcSession {
49public:
50 static std::atomic<int32_t> gNum;
51
52 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
53 Status getName(std::string* name) override {
54 *name = mName;
55 return Status::ok();
56 }
57 ~MyBinderRpcSession() { gNum--; }
58
59private:
60 std::string mName;
61};
62std::atomic<int32_t> MyBinderRpcSession::gNum;
63
64class MyBinderRpcTest : public BnBinderRpcTest {
65public:
66 sp<RpcConnection> connection;
67
68 Status sendString(const std::string& str) override {
69 std::cout << "Child received string: " << str << std::endl;
70 return Status::ok();
71 }
72 Status doubleString(const std::string& str, std::string* strstr) override {
73 std::cout << "Child received string to double: " << str << std::endl;
74 *strstr = str + str;
75 return Status::ok();
76 }
77 Status countBinders(int32_t* out) override {
78 if (connection == nullptr) {
79 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
80 }
81 *out = connection->state()->countBinders();
82 if (*out != 1) {
83 connection->state()->dump();
84 }
85 return Status::ok();
86 }
87 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
88 if (binder == nullptr) {
89 std::cout << "Received null binder!" << std::endl;
90 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
91 }
92 *out = binder->pingBinder();
93 return Status::ok();
94 }
95 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
96 *out = binder;
97 return Status::ok();
98 }
99 static sp<IBinder> mHeldBinder;
100 Status holdBinder(const sp<IBinder>& binder) override {
101 mHeldBinder = binder;
102 return Status::ok();
103 }
104 Status getHeldBinder(sp<IBinder>* held) override {
105 *held = mHeldBinder;
106 return Status::ok();
107 }
108 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
109 if (count <= 0) return Status::ok();
110 return binder->nestMe(this, count - 1);
111 }
112 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
113 static sp<IBinder> binder = new BBinder;
114 *out = binder;
115 return Status::ok();
116 }
117 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
118 *out = new MyBinderRpcSession(name);
119 return Status::ok();
120 }
121 Status getNumOpenSessions(int32_t* out) override {
122 *out = MyBinderRpcSession::gNum;
123 return Status::ok();
124 }
125
126 std::mutex blockMutex;
127 Status lock() override {
128 blockMutex.lock();
129 return Status::ok();
130 }
131 Status unlockInMsAsync(int32_t ms) override {
132 usleep(ms * 1000);
133 blockMutex.unlock();
134 return Status::ok();
135 }
136 Status lockUnlock() override {
137 std::lock_guard<std::mutex> _l(blockMutex);
138 return Status::ok();
139 }
140
141 Status sleepMs(int32_t ms) override {
142 usleep(ms * 1000);
143 return Status::ok();
144 }
145
146 Status sleepMsAsync(int32_t ms) override {
147 // In-process binder calls are asynchronous, but the call to this method
148 // is synchronous wrt its client. This in/out-process threading model
149 // diffentiation is a classic binder leaky abstraction (for better or
150 // worse) and is preserved here the way binder sockets plugs itself
151 // into BpBinder, as nothing is changed at the higher levels
152 // (IInterface) which result in this behavior.
153 return sleepMs(ms);
154 }
155
156 Status die(bool cleanup) override {
157 if (cleanup) {
158 exit(1);
159 } else {
160 _exit(1);
161 }
162 }
163};
164sp<IBinder> MyBinderRpcTest::mHeldBinder;
165
166class Process {
167public:
168 Process(const std::function<void()>& f) {
169 if (0 == (mPid = fork())) {
170 // racey: assume parent doesn't crash before this is set
171 prctl(PR_SET_PDEATHSIG, SIGHUP);
172
173 f();
174 }
175 }
176 ~Process() {
177 if (mPid != 0) {
178 kill(mPid, SIGKILL);
179 }
180 }
181
182private:
183 pid_t mPid = 0;
184};
185
186static std::string allocateSocketAddress() {
187 static size_t id = 0;
188
Nikita Ioffe92a9c782021-04-01 11:06:40 +0000189 return "/dev/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000190};
191
192struct ProcessConnection {
193 // reference to process hosting a socket server
194 Process host;
195
196 // client connection object associated with other process
197 sp<RpcConnection> connection;
198
199 // pre-fetched root object
200 sp<IBinder> rootBinder;
201
202 // whether connection should be invalidated by end of run
203 bool expectInvalid = false;
204
205 ~ProcessConnection() {
206 rootBinder = nullptr;
207 EXPECT_NE(nullptr, connection);
208 EXPECT_NE(nullptr, connection->state());
209 EXPECT_EQ(0, connection->state()->countBinders()) << (connection->state()->dump(), "dump:");
210
211 wp<RpcConnection> weakConnection = connection;
212 connection = nullptr;
213 EXPECT_EQ(nullptr, weakConnection.promote()) << "Leaked connection";
214 }
215};
216
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000217// This creates a new process serving an interface on a certain number of
218// threads.
219ProcessConnection createRpcTestSocketServerProcess(
220 size_t numThreads,
221 const std::function<void(const sp<RpcServer>&, const sp<RpcConnection>&)>& configure) {
222 CHECK_GT(numThreads, 0);
223
224 std::string addr = allocateSocketAddress();
225 unlink(addr.c_str());
226
227 auto ret = ProcessConnection{
228 .host = Process([&] {
229 sp<RpcServer> server = RpcServer::make();
230
231 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
232
233 // server supporting one client on one socket
234 sp<RpcConnection> connection = server->addClientConnection();
235 CHECK(connection->setupUnixDomainServer(addr.c_str())) << addr;
236
237 configure(server, connection);
238
239 // accept 'numThreads' connections
240 std::vector<std::thread> pool;
241 for (size_t i = 0; i + 1 < numThreads; i++) {
242 pool.push_back(std::thread([=] { connection->join(); }));
243 }
244 connection->join();
245 for (auto& t : pool) t.join();
246 }),
247 .connection = RpcConnection::make(),
248 };
249
250 // wait up to 1s for sockets to be created
251 constexpr useconds_t kMaxWaitUs = 1000000;
252 constexpr useconds_t kWaitDivision = 100;
253 for (size_t i = 0; i < kWaitDivision && 0 != access(addr.c_str(), F_OK); i++) {
254 usleep(kMaxWaitUs / kWaitDivision);
255 }
256
257 // create remainder of connections
258 for (size_t i = 0; i < numThreads; i++) {
259 // Connection refused sometimes after file created but before listening.
260 CHECK(ret.connection->addUnixDomainClient(addr.c_str()) ||
261 (usleep(10000), ret.connection->addUnixDomainClient(addr.c_str())))
262 << i;
263 }
264
265 ret.rootBinder = ret.connection->getRootObject();
266 return ret;
267}
268
Steven Moreland5553ac42020-11-11 02:14:45 +0000269// Process connection where the process hosts IBinderRpcTest, the server used
270// for most testing here
271struct BinderRpcTestProcessConnection {
272 ProcessConnection proc;
273
274 // pre-fetched root object
275 sp<IBinder> rootBinder;
276
277 // pre-casted root object
278 sp<IBinderRpcTest> rootIface;
279
280 ~BinderRpcTestProcessConnection() {
281 if (!proc.expectInvalid) {
282 int32_t remoteBinders = 0;
283 EXPECT_OK(rootIface->countBinders(&remoteBinders));
284 // should only be the root binder object, iface
285 EXPECT_EQ(remoteBinders, 1);
286 }
287
288 rootIface = nullptr;
289 rootBinder = nullptr;
290 }
291};
292
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000293BinderRpcTestProcessConnection createRpcTestSocketServerProcess(size_t numThreads) {
294 BinderRpcTestProcessConnection ret{
295 .proc = createRpcTestSocketServerProcess(numThreads,
296 [&](const sp<RpcServer>& server,
297 const sp<RpcConnection>& connection) {
298 sp<MyBinderRpcTest> service =
299 new MyBinderRpcTest;
300 server->setRootObject(service);
301 service->connection =
302 connection; // for testing only
303 }),
304 };
305
306 ret.rootBinder = ret.proc.rootBinder;
307 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
308
309 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000310}
311
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000312TEST(BinderRpc, RootObjectIsNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000313 auto proc = createRpcTestSocketServerProcess(1,
314 [](const sp<RpcServer>& server,
315 const sp<RpcConnection>&) {
316 // this is the default, but to be explicit
317 server->setRootObject(nullptr);
318 });
319
320 // retrieved by getRootObject when process is created above
321 EXPECT_EQ(nullptr, proc.rootBinder);
322
323 // make sure we can retrieve it again (process doesn't crash)
324 EXPECT_EQ(nullptr, proc.connection->getRootObject());
325}
326
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000327TEST(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000328 auto proc = createRpcTestSocketServerProcess(1);
329 ASSERT_NE(proc.rootBinder, nullptr);
330 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
331}
332
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000333TEST(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000334 auto proc = createRpcTestSocketServerProcess(1);
335 Parcel data;
336 Parcel reply;
337 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
338}
339
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000340TEST(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000341 auto proc = createRpcTestSocketServerProcess(1);
342 Parcel data;
343 data.markForBinder(proc.rootBinder);
344 Parcel reply;
345 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
346}
347
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000348TEST(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000349 auto proc = createRpcTestSocketServerProcess(1);
350 EXPECT_OK(proc.rootIface->sendString("asdf"));
351}
352
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000353TEST(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000354 auto proc = createRpcTestSocketServerProcess(1);
355 std::string doubled;
356 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
357 EXPECT_EQ("cool cool ", doubled);
358}
359
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000360TEST(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000361 auto proc = createRpcTestSocketServerProcess(1);
362 std::string single = std::string(1024, 'a');
363 std::string doubled;
364 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
365 EXPECT_EQ(single + single, doubled);
366}
367
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000368TEST(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000369 auto proc = createRpcTestSocketServerProcess(1);
370
371 int32_t pingResult;
372 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
373 EXPECT_EQ(OK, pingResult);
374
375 EXPECT_EQ(0, MyBinderRpcSession::gNum);
376}
377
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000378TEST(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000379 auto proc = createRpcTestSocketServerProcess(1);
380
381 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
382 sp<IBinder> outBinder;
383 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
384 EXPECT_EQ(inBinder, outBinder);
385
386 wp<IBinder> weak = inBinder;
387 inBinder = nullptr;
388 outBinder = nullptr;
389
390 // Force reading a reply, to process any pending dec refs from the other
391 // process (the other process will process dec refs there before processing
392 // the ping here).
393 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
394
395 EXPECT_EQ(nullptr, weak.promote());
396
397 EXPECT_EQ(0, MyBinderRpcSession::gNum);
398}
399
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000400TEST(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000401 auto proc = createRpcTestSocketServerProcess(1);
402
403 sp<IBinderRpcSession> session;
404 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
405
406 sp<IBinder> inBinder = IInterface::asBinder(session);
407 sp<IBinder> outBinder;
408 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
409 EXPECT_EQ(inBinder, outBinder);
410
411 wp<IBinder> weak = inBinder;
412 session = nullptr;
413 inBinder = nullptr;
414 outBinder = nullptr;
415
416 // Force reading a reply, to process any pending dec refs from the other
417 // process (the other process will process dec refs there before processing
418 // the ping here).
419 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
420
421 EXPECT_EQ(nullptr, weak.promote());
422}
423
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000424TEST(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000425 auto proc = createRpcTestSocketServerProcess(1);
426
427 sp<IBinder> outBinder;
428 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
429 EXPECT_EQ(nullptr, outBinder);
430}
431
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000432TEST(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000433 auto proc = createRpcTestSocketServerProcess(1);
434
435 IBinder* ptr = nullptr;
436 {
437 sp<IBinder> binder = new BBinder();
438 ptr = binder.get();
439 EXPECT_OK(proc.rootIface->holdBinder(binder));
440 }
441
442 sp<IBinder> held;
443 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
444
445 EXPECT_EQ(held.get(), ptr);
446
447 // stop holding binder, because we test to make sure references are cleaned
448 // up
449 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
450 // and flush ref counts
451 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
452}
453
454// START TESTS FOR LIMITATIONS OF SOCKET BINDER
455// These are behavioral differences form regular binder, where certain usecases
456// aren't supported.
457
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000458TEST(BinderRpc, CannotMixBindersBetweenUnrelatedSocketConnections) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000459 auto proc1 = createRpcTestSocketServerProcess(1);
460 auto proc2 = createRpcTestSocketServerProcess(1);
461
462 sp<IBinder> outBinder;
463 EXPECT_EQ(INVALID_OPERATION,
464 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
465}
466
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000467TEST(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000468 auto proc = createRpcTestSocketServerProcess(1);
469
470 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
471 sp<IBinder> outBinder;
472 EXPECT_EQ(INVALID_OPERATION,
473 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
474}
475
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000476TEST(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000477 auto proc = createRpcTestSocketServerProcess(1);
478
479 // for historical reasons, IServiceManager interface only returns the
480 // exception code
481 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
482 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
483}
484
485// END TESTS FOR LIMITATIONS OF SOCKET BINDER
486
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000487TEST(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000488 auto proc = createRpcTestSocketServerProcess(1);
489
490 sp<IBinder> outBinder;
491 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
492 EXPECT_EQ(proc.rootBinder, outBinder);
493}
494
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000495TEST(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000496 auto proc = createRpcTestSocketServerProcess(1);
497
498 auto nastyNester = sp<MyBinderRpcTest>::make();
499 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
500
501 wp<IBinder> weak = nastyNester;
502 nastyNester = nullptr;
503 EXPECT_EQ(nullptr, weak.promote());
504}
505
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000506TEST(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000507 auto proc = createRpcTestSocketServerProcess(1);
508
509 sp<IBinder> a;
510 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
511
512 sp<IBinder> b;
513 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
514
515 EXPECT_EQ(a, b);
516}
517
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000518TEST(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000519 auto proc = createRpcTestSocketServerProcess(1);
520
521 sp<IBinder> a;
522 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
523 wp<IBinder> weak = a;
524 a = nullptr;
525
526 sp<IBinder> b;
527 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
528
529 // this is the wrong behavior, since BpBinder
530 // doesn't implement onIncStrongAttempted
531 // but make sure there is no crash
532 EXPECT_EQ(nullptr, weak.promote());
533
534 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
535
536 // In order to fix this:
537 // - need to have incStrongAttempted reflected across IPC boundary (wait for
538 // response to promote - round trip...)
539 // - sendOnLastWeakRef, to delete entries out of RpcState table
540 EXPECT_EQ(b, weak.promote());
541}
542
543#define expectSessions(expected, iface) \
544 do { \
545 int session; \
546 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
547 EXPECT_EQ(expected, session); \
548 } while (false)
549
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000550TEST(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000551 auto proc = createRpcTestSocketServerProcess(1);
552
553 sp<IBinderRpcSession> session;
554 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
555 std::string out;
556 EXPECT_OK(session->getName(&out));
557 EXPECT_EQ("aoeu", out);
558
559 expectSessions(1, proc.rootIface);
560 session = nullptr;
561 expectSessions(0, proc.rootIface);
562}
563
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000564TEST(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000565 auto proc = createRpcTestSocketServerProcess(1);
566
567 std::vector<sp<IBinderRpcSession>> sessions;
568
569 for (size_t i = 0; i < 15; i++) {
570 expectSessions(i, proc.rootIface);
571 sp<IBinderRpcSession> session;
572 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
573 sessions.push_back(session);
574 }
575 expectSessions(sessions.size(), proc.rootIface);
576 for (size_t i = 0; i < sessions.size(); i++) {
577 std::string out;
578 EXPECT_OK(sessions.at(i)->getName(&out));
579 EXPECT_EQ(std::to_string(i), out);
580 }
581 expectSessions(sessions.size(), proc.rootIface);
582
583 while (!sessions.empty()) {
584 sessions.pop_back();
585 expectSessions(sessions.size(), proc.rootIface);
586 }
587 expectSessions(0, proc.rootIface);
588}
589
590size_t epochMillis() {
591 using std::chrono::duration_cast;
592 using std::chrono::milliseconds;
593 using std::chrono::seconds;
594 using std::chrono::system_clock;
595 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
596}
597
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000598TEST(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000599 constexpr size_t kNumThreads = 10;
600
601 auto proc = createRpcTestSocketServerProcess(kNumThreads);
602
603 EXPECT_OK(proc.rootIface->lock());
604
605 // block all but one thread taking locks
606 std::vector<std::thread> ts;
607 for (size_t i = 0; i < kNumThreads - 1; i++) {
608 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
609 }
610
611 usleep(100000); // give chance for calls on other threads
612
613 // other calls still work
614 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
615
616 constexpr size_t blockTimeMs = 500;
617 size_t epochMsBefore = epochMillis();
618 // after this, we should never see a response within this time
619 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
620
621 // this call should be blocked for blockTimeMs
622 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
623
624 size_t epochMsAfter = epochMillis();
625 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
626
627 for (auto& t : ts) t.join();
628}
629
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000630TEST(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000631 constexpr size_t kNumThreads = 10;
632 constexpr size_t kNumCalls = kNumThreads + 3;
633 constexpr size_t kSleepMs = 500;
634
635 auto proc = createRpcTestSocketServerProcess(kNumThreads);
636
637 size_t epochMsBefore = epochMillis();
638
639 std::vector<std::thread> ts;
640 for (size_t i = 0; i < kNumCalls; i++) {
641 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
642 }
643
644 for (auto& t : ts) t.join();
645
646 size_t epochMsAfter = epochMillis();
647
648 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
649
650 // Potential flake, but make sure calls are handled in parallel.
651 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
652}
653
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000654TEST(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000655 constexpr size_t kNumClientThreads = 10;
656 constexpr size_t kNumServerThreads = 10;
657 constexpr size_t kNumCalls = 100;
658
659 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
660
661 std::vector<std::thread> threads;
662 for (size_t i = 0; i < kNumClientThreads; i++) {
663 threads.push_back(std::thread([&] {
664 for (size_t j = 0; j < kNumCalls; j++) {
665 sp<IBinder> out;
666 proc.rootIface->repeatBinder(proc.rootBinder, &out);
667 EXPECT_EQ(proc.rootBinder, out);
668 }
669 }));
670 }
671
672 for (auto& t : threads) t.join();
673}
674
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000675TEST(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000676 constexpr size_t kReallyLongTimeMs = 100;
677 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
678
679 // more than one thread, just so this doesn't deadlock
680 auto proc = createRpcTestSocketServerProcess(2);
681
682 size_t epochMsBefore = epochMillis();
683
684 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
685
686 size_t epochMsAfter = epochMillis();
687 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
688}
689
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000690TEST(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000691 constexpr size_t kNumSleeps = 10;
692 constexpr size_t kNumExtraServerThreads = 4;
693 constexpr size_t kSleepMs = 50;
694
695 // make sure calls to the same object happen on the same thread
696 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
697
698 EXPECT_OK(proc.rootIface->lock());
699
700 for (size_t i = 0; i < kNumSleeps; i++) {
701 // these should be processed serially
702 proc.rootIface->sleepMsAsync(kSleepMs);
703 }
704 // should also be processesed serially
705 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
706
707 size_t epochMsBefore = epochMillis();
708 EXPECT_OK(proc.rootIface->lockUnlock());
709 size_t epochMsAfter = epochMillis();
710
711 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
712}
713
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000714TEST(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000715 // TODO(b/183141167): handle this in library
716 signal(SIGPIPE, SIG_IGN);
717
718 for (bool doDeathCleanup : {true, false}) {
719 auto proc = createRpcTestSocketServerProcess(1);
720
721 // make sure there is some state during crash
722 // 1. we hold their binder
723 sp<IBinderRpcSession> session;
724 EXPECT_OK(proc.rootIface->openSession("happy", &session));
725 // 2. they hold our binder
726 sp<IBinder> binder = new BBinder();
727 EXPECT_OK(proc.rootIface->holdBinder(binder));
728
729 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
730 << "Do death cleanup: " << doDeathCleanup;
731
732 proc.proc.expectInvalid = true;
733 }
734}
735
736ssize_t countFds() {
737 DIR* dir = opendir("/proc/self/fd/");
738 if (dir == nullptr) return -1;
739 ssize_t ret = 0;
740 dirent* ent;
741 while ((ent = readdir(dir)) != nullptr) ret++;
742 closedir(dir);
743 return ret;
744}
745
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000746TEST(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000747 ssize_t beforeFds = countFds();
748 ASSERT_GE(beforeFds, 0);
749 {
750 auto proc = createRpcTestSocketServerProcess(10);
751 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
752 }
753 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
754}
755
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000756extern "C" int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000757 ::testing::InitGoogleTest(&argc, argv);
758 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
759 return RUN_ALL_TESTS();
760}
Nikita Ioffe9630f9d2021-04-01 11:06:40 +0000761
762} // namespace android