blob: 936ee5e91a82dadb4ce0650ee8c90b3dbcec159d [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
Steven Morelandf6ec4632021-04-01 16:20:47 +000033#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +000034#include <linux/vm_sockets.h>
Steven Morelandf6ec4632021-04-01 16:20:47 +000035#endif //__BIONIC__
36
Steven Morelandc1635952021-04-01 16:20:47 +000037#include <sys/prctl.h>
38#include <unistd.h>
39
Steven Moreland5553ac42020-11-11 02:14:45 +000040#include "../RpcState.h" // for debugging
41
42namespace android {
43
44using android::binder::Status;
45
46#define EXPECT_OK(status) \
47 do { \
48 Status stat = (status); \
49 EXPECT_TRUE(stat.isOk()) << stat; \
50 } while (false)
51
52class MyBinderRpcSession : public BnBinderRpcSession {
53public:
54 static std::atomic<int32_t> gNum;
55
56 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
57 Status getName(std::string* name) override {
58 *name = mName;
59 return Status::ok();
60 }
61 ~MyBinderRpcSession() { gNum--; }
62
63private:
64 std::string mName;
65};
66std::atomic<int32_t> MyBinderRpcSession::gNum;
67
68class MyBinderRpcTest : public BnBinderRpcTest {
69public:
70 sp<RpcConnection> connection;
71
72 Status sendString(const std::string& str) override {
73 std::cout << "Child received string: " << str << std::endl;
74 return Status::ok();
75 }
76 Status doubleString(const std::string& str, std::string* strstr) override {
77 std::cout << "Child received string to double: " << str << std::endl;
78 *strstr = str + str;
79 return Status::ok();
80 }
81 Status countBinders(int32_t* out) override {
82 if (connection == nullptr) {
83 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
84 }
85 *out = connection->state()->countBinders();
86 if (*out != 1) {
87 connection->state()->dump();
88 }
89 return Status::ok();
90 }
91 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
92 if (binder == nullptr) {
93 std::cout << "Received null binder!" << std::endl;
94 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
95 }
96 *out = binder->pingBinder();
97 return Status::ok();
98 }
99 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
100 *out = binder;
101 return Status::ok();
102 }
103 static sp<IBinder> mHeldBinder;
104 Status holdBinder(const sp<IBinder>& binder) override {
105 mHeldBinder = binder;
106 return Status::ok();
107 }
108 Status getHeldBinder(sp<IBinder>* held) override {
109 *held = mHeldBinder;
110 return Status::ok();
111 }
112 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
113 if (count <= 0) return Status::ok();
114 return binder->nestMe(this, count - 1);
115 }
116 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
117 static sp<IBinder> binder = new BBinder;
118 *out = binder;
119 return Status::ok();
120 }
121 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
122 *out = new MyBinderRpcSession(name);
123 return Status::ok();
124 }
125 Status getNumOpenSessions(int32_t* out) override {
126 *out = MyBinderRpcSession::gNum;
127 return Status::ok();
128 }
129
130 std::mutex blockMutex;
131 Status lock() override {
132 blockMutex.lock();
133 return Status::ok();
134 }
135 Status unlockInMsAsync(int32_t ms) override {
136 usleep(ms * 1000);
137 blockMutex.unlock();
138 return Status::ok();
139 }
140 Status lockUnlock() override {
141 std::lock_guard<std::mutex> _l(blockMutex);
142 return Status::ok();
143 }
144
145 Status sleepMs(int32_t ms) override {
146 usleep(ms * 1000);
147 return Status::ok();
148 }
149
150 Status sleepMsAsync(int32_t ms) override {
151 // In-process binder calls are asynchronous, but the call to this method
152 // is synchronous wrt its client. This in/out-process threading model
153 // diffentiation is a classic binder leaky abstraction (for better or
154 // worse) and is preserved here the way binder sockets plugs itself
155 // into BpBinder, as nothing is changed at the higher levels
156 // (IInterface) which result in this behavior.
157 return sleepMs(ms);
158 }
159
160 Status die(bool cleanup) override {
161 if (cleanup) {
162 exit(1);
163 } else {
164 _exit(1);
165 }
166 }
167};
168sp<IBinder> MyBinderRpcTest::mHeldBinder;
169
170class Process {
171public:
172 Process(const std::function<void()>& f) {
173 if (0 == (mPid = fork())) {
174 // racey: assume parent doesn't crash before this is set
175 prctl(PR_SET_PDEATHSIG, SIGHUP);
176
177 f();
178 }
179 }
180 ~Process() {
181 if (mPid != 0) {
182 kill(mPid, SIGKILL);
183 }
184 }
185
186private:
187 pid_t mPid = 0;
188};
189
190static std::string allocateSocketAddress() {
191 static size_t id = 0;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000192 static bool gUseTmp = access("/tmp/", F_OK) != -1;
Steven Moreland5553ac42020-11-11 02:14:45 +0000193
Steven Morelandf6ec4632021-04-01 16:20:47 +0000194 if (gUseTmp) {
195 return "/tmp/binderRpcTest_" + std::to_string(id++);
196 } else {
197 return "/dev/binderRpcTest_" + std::to_string(id++);
198 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000199};
200
201struct ProcessConnection {
202 // reference to process hosting a socket server
203 Process host;
204
205 // client connection object associated with other process
206 sp<RpcConnection> connection;
207
208 // pre-fetched root object
209 sp<IBinder> rootBinder;
210
211 // whether connection should be invalidated by end of run
212 bool expectInvalid = false;
213
214 ~ProcessConnection() {
215 rootBinder = nullptr;
216 EXPECT_NE(nullptr, connection);
217 EXPECT_NE(nullptr, connection->state());
218 EXPECT_EQ(0, connection->state()->countBinders()) << (connection->state()->dump(), "dump:");
219
220 wp<RpcConnection> weakConnection = connection;
221 connection = nullptr;
222 EXPECT_EQ(nullptr, weakConnection.promote()) << "Leaked connection";
223 }
224};
225
Steven Moreland5553ac42020-11-11 02:14:45 +0000226// Process connection where the process hosts IBinderRpcTest, the server used
227// for most testing here
228struct BinderRpcTestProcessConnection {
229 ProcessConnection proc;
230
231 // pre-fetched root object
232 sp<IBinder> rootBinder;
233
234 // pre-casted root object
235 sp<IBinderRpcTest> rootIface;
236
237 ~BinderRpcTestProcessConnection() {
238 if (!proc.expectInvalid) {
239 int32_t remoteBinders = 0;
240 EXPECT_OK(rootIface->countBinders(&remoteBinders));
241 // should only be the root binder object, iface
242 EXPECT_EQ(remoteBinders, 1);
243 }
244
245 rootIface = nullptr;
246 rootBinder = nullptr;
247 }
248};
249
Steven Morelandc1635952021-04-01 16:20:47 +0000250enum class SocketType {
251 UNIX,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000252#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000253 VSOCK,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000254#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000255};
256static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
257 switch (info.param) {
258 case SocketType::UNIX:
259 return "unix_domain_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000260#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000261 case SocketType::VSOCK:
262 return "vm_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000263#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000264 default:
265 LOG_ALWAYS_FATAL("Unknown socket type");
266 return "";
267 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000268}
Steven Morelandc1635952021-04-01 16:20:47 +0000269class BinderRpc : public ::testing::TestWithParam<SocketType> {
270public:
271 // This creates a new process serving an interface on a certain number of
272 // threads.
273 ProcessConnection createRpcTestSocketServerProcess(
274 size_t numThreads,
275 const std::function<void(const sp<RpcServer>&, const sp<RpcConnection>&)>& configure) {
276 CHECK_GT(numThreads, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000277
Steven Morelandc1635952021-04-01 16:20:47 +0000278 SocketType socketType = GetParam();
279
280 std::string addr = allocateSocketAddress();
281 unlink(addr.c_str());
282 static unsigned int port = 3456;
283 port++;
284
285 auto ret = ProcessConnection{
286 .host = Process([&] {
287 sp<RpcServer> server = RpcServer::make();
288
289 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
290
291 // server supporting one client on one socket
292 sp<RpcConnection> connection = server->addClientConnection();
293
294 switch (socketType) {
295 case SocketType::UNIX:
296 CHECK(connection->setupUnixDomainServer(addr.c_str())) << addr;
297 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000298#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000299 case SocketType::VSOCK:
300 CHECK(connection->setupVsockServer(port));
301 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000302#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000303 default:
304 LOG_ALWAYS_FATAL("Unknown socket type");
305 }
306
307 configure(server, connection);
308
309 // accept 'numThreads' connections
310 std::vector<std::thread> pool;
311 for (size_t i = 0; i + 1 < numThreads; i++) {
312 pool.push_back(std::thread([=] { connection->join(); }));
313 }
314 connection->join();
315 for (auto& t : pool) t.join();
316 }),
317 .connection = RpcConnection::make(),
318 };
319
320 // create remainder of connections
321 for (size_t i = 0; i < numThreads; i++) {
322 for (size_t tries = 0; tries < 5; tries++) {
323 usleep(10000);
324 switch (socketType) {
325 case SocketType::UNIX:
326 if (ret.connection->addUnixDomainClient(addr.c_str())) goto success;
327 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000328#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000329 case SocketType::VSOCK:
330 if (ret.connection->addVsockClient(VMADDR_CID_LOCAL, port)) goto success;
331 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000332#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000333 default:
334 LOG_ALWAYS_FATAL("Unknown socket type");
335 }
336 }
337 LOG_ALWAYS_FATAL("Could not connect");
338 success:;
339 }
340
341 ret.rootBinder = ret.connection->getRootObject();
342 return ret;
343 }
344
345 BinderRpcTestProcessConnection createRpcTestSocketServerProcess(size_t numThreads) {
346 BinderRpcTestProcessConnection ret{
347 .proc = createRpcTestSocketServerProcess(numThreads,
348 [&](const sp<RpcServer>& server,
349 const sp<RpcConnection>& connection) {
350 sp<MyBinderRpcTest> service =
351 new MyBinderRpcTest;
352 server->setRootObject(service);
353 service->connection =
354 connection; // for testing only
355 }),
356 };
357
358 ret.rootBinder = ret.proc.rootBinder;
359 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
360
361 return ret;
362 }
363};
364
365TEST_P(BinderRpc, RootObjectIsNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000366 auto proc = createRpcTestSocketServerProcess(1,
367 [](const sp<RpcServer>& server,
368 const sp<RpcConnection>&) {
369 // this is the default, but to be explicit
370 server->setRootObject(nullptr);
371 });
372
373 // retrieved by getRootObject when process is created above
374 EXPECT_EQ(nullptr, proc.rootBinder);
375
376 // make sure we can retrieve it again (process doesn't crash)
377 EXPECT_EQ(nullptr, proc.connection->getRootObject());
378}
379
Steven Morelandc1635952021-04-01 16:20:47 +0000380TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000381 auto proc = createRpcTestSocketServerProcess(1);
382 ASSERT_NE(proc.rootBinder, nullptr);
383 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
384}
385
Steven Morelandc1635952021-04-01 16:20:47 +0000386TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000387 auto proc = createRpcTestSocketServerProcess(1);
388 Parcel data;
389 Parcel reply;
390 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
391}
392
Steven Morelandc1635952021-04-01 16:20:47 +0000393TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000394 auto proc = createRpcTestSocketServerProcess(1);
395 Parcel data;
396 data.markForBinder(proc.rootBinder);
397 Parcel reply;
398 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
399}
400
Steven Morelandc1635952021-04-01 16:20:47 +0000401TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000402 auto proc = createRpcTestSocketServerProcess(1);
403 EXPECT_OK(proc.rootIface->sendString("asdf"));
404}
405
Steven Morelandc1635952021-04-01 16:20:47 +0000406TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000407 auto proc = createRpcTestSocketServerProcess(1);
408 std::string doubled;
409 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
410 EXPECT_EQ("cool cool ", doubled);
411}
412
Steven Morelandc1635952021-04-01 16:20:47 +0000413TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000414 auto proc = createRpcTestSocketServerProcess(1);
415 std::string single = std::string(1024, 'a');
416 std::string doubled;
417 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
418 EXPECT_EQ(single + single, doubled);
419}
420
Steven Morelandc1635952021-04-01 16:20:47 +0000421TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000422 auto proc = createRpcTestSocketServerProcess(1);
423
424 int32_t pingResult;
425 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
426 EXPECT_EQ(OK, pingResult);
427
428 EXPECT_EQ(0, MyBinderRpcSession::gNum);
429}
430
Steven Morelandc1635952021-04-01 16:20:47 +0000431TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000432 auto proc = createRpcTestSocketServerProcess(1);
433
434 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
435 sp<IBinder> outBinder;
436 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
437 EXPECT_EQ(inBinder, outBinder);
438
439 wp<IBinder> weak = inBinder;
440 inBinder = nullptr;
441 outBinder = nullptr;
442
443 // Force reading a reply, to process any pending dec refs from the other
444 // process (the other process will process dec refs there before processing
445 // the ping here).
446 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
447
448 EXPECT_EQ(nullptr, weak.promote());
449
450 EXPECT_EQ(0, MyBinderRpcSession::gNum);
451}
452
Steven Morelandc1635952021-04-01 16:20:47 +0000453TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000454 auto proc = createRpcTestSocketServerProcess(1);
455
456 sp<IBinderRpcSession> session;
457 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
458
459 sp<IBinder> inBinder = IInterface::asBinder(session);
460 sp<IBinder> outBinder;
461 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
462 EXPECT_EQ(inBinder, outBinder);
463
464 wp<IBinder> weak = inBinder;
465 session = nullptr;
466 inBinder = nullptr;
467 outBinder = nullptr;
468
469 // Force reading a reply, to process any pending dec refs from the other
470 // process (the other process will process dec refs there before processing
471 // the ping here).
472 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
473
474 EXPECT_EQ(nullptr, weak.promote());
475}
476
Steven Morelandc1635952021-04-01 16:20:47 +0000477TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000478 auto proc = createRpcTestSocketServerProcess(1);
479
480 sp<IBinder> outBinder;
481 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
482 EXPECT_EQ(nullptr, outBinder);
483}
484
Steven Morelandc1635952021-04-01 16:20:47 +0000485TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000486 auto proc = createRpcTestSocketServerProcess(1);
487
488 IBinder* ptr = nullptr;
489 {
490 sp<IBinder> binder = new BBinder();
491 ptr = binder.get();
492 EXPECT_OK(proc.rootIface->holdBinder(binder));
493 }
494
495 sp<IBinder> held;
496 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
497
498 EXPECT_EQ(held.get(), ptr);
499
500 // stop holding binder, because we test to make sure references are cleaned
501 // up
502 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
503 // and flush ref counts
504 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
505}
506
507// START TESTS FOR LIMITATIONS OF SOCKET BINDER
508// These are behavioral differences form regular binder, where certain usecases
509// aren't supported.
510
Steven Morelandc1635952021-04-01 16:20:47 +0000511TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketConnections) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000512 auto proc1 = createRpcTestSocketServerProcess(1);
513 auto proc2 = createRpcTestSocketServerProcess(1);
514
515 sp<IBinder> outBinder;
516 EXPECT_EQ(INVALID_OPERATION,
517 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
518}
519
Steven Morelandc1635952021-04-01 16:20:47 +0000520TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000521 auto proc = createRpcTestSocketServerProcess(1);
522
523 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
524 sp<IBinder> outBinder;
525 EXPECT_EQ(INVALID_OPERATION,
526 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
527}
528
Steven Morelandc1635952021-04-01 16:20:47 +0000529TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000530 auto proc = createRpcTestSocketServerProcess(1);
531
532 // for historical reasons, IServiceManager interface only returns the
533 // exception code
534 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
535 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
536}
537
538// END TESTS FOR LIMITATIONS OF SOCKET BINDER
539
Steven Morelandc1635952021-04-01 16:20:47 +0000540TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000541 auto proc = createRpcTestSocketServerProcess(1);
542
543 sp<IBinder> outBinder;
544 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
545 EXPECT_EQ(proc.rootBinder, outBinder);
546}
547
Steven Morelandc1635952021-04-01 16:20:47 +0000548TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000549 auto proc = createRpcTestSocketServerProcess(1);
550
551 auto nastyNester = sp<MyBinderRpcTest>::make();
552 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
553
554 wp<IBinder> weak = nastyNester;
555 nastyNester = nullptr;
556 EXPECT_EQ(nullptr, weak.promote());
557}
558
Steven Morelandc1635952021-04-01 16:20:47 +0000559TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000560 auto proc = createRpcTestSocketServerProcess(1);
561
562 sp<IBinder> a;
563 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
564
565 sp<IBinder> b;
566 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
567
568 EXPECT_EQ(a, b);
569}
570
Steven Morelandc1635952021-04-01 16:20:47 +0000571TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000572 auto proc = createRpcTestSocketServerProcess(1);
573
574 sp<IBinder> a;
575 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
576 wp<IBinder> weak = a;
577 a = nullptr;
578
579 sp<IBinder> b;
580 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
581
582 // this is the wrong behavior, since BpBinder
583 // doesn't implement onIncStrongAttempted
584 // but make sure there is no crash
585 EXPECT_EQ(nullptr, weak.promote());
586
587 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
588
589 // In order to fix this:
590 // - need to have incStrongAttempted reflected across IPC boundary (wait for
591 // response to promote - round trip...)
592 // - sendOnLastWeakRef, to delete entries out of RpcState table
593 EXPECT_EQ(b, weak.promote());
594}
595
596#define expectSessions(expected, iface) \
597 do { \
598 int session; \
599 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
600 EXPECT_EQ(expected, session); \
601 } while (false)
602
Steven Morelandc1635952021-04-01 16:20:47 +0000603TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000604 auto proc = createRpcTestSocketServerProcess(1);
605
606 sp<IBinderRpcSession> session;
607 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
608 std::string out;
609 EXPECT_OK(session->getName(&out));
610 EXPECT_EQ("aoeu", out);
611
612 expectSessions(1, proc.rootIface);
613 session = nullptr;
614 expectSessions(0, proc.rootIface);
615}
616
Steven Morelandc1635952021-04-01 16:20:47 +0000617TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000618 auto proc = createRpcTestSocketServerProcess(1);
619
620 std::vector<sp<IBinderRpcSession>> sessions;
621
622 for (size_t i = 0; i < 15; i++) {
623 expectSessions(i, proc.rootIface);
624 sp<IBinderRpcSession> session;
625 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
626 sessions.push_back(session);
627 }
628 expectSessions(sessions.size(), proc.rootIface);
629 for (size_t i = 0; i < sessions.size(); i++) {
630 std::string out;
631 EXPECT_OK(sessions.at(i)->getName(&out));
632 EXPECT_EQ(std::to_string(i), out);
633 }
634 expectSessions(sessions.size(), proc.rootIface);
635
636 while (!sessions.empty()) {
637 sessions.pop_back();
638 expectSessions(sessions.size(), proc.rootIface);
639 }
640 expectSessions(0, proc.rootIface);
641}
642
643size_t epochMillis() {
644 using std::chrono::duration_cast;
645 using std::chrono::milliseconds;
646 using std::chrono::seconds;
647 using std::chrono::system_clock;
648 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
649}
650
Steven Morelandc1635952021-04-01 16:20:47 +0000651TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000652 constexpr size_t kNumThreads = 10;
653
654 auto proc = createRpcTestSocketServerProcess(kNumThreads);
655
656 EXPECT_OK(proc.rootIface->lock());
657
658 // block all but one thread taking locks
659 std::vector<std::thread> ts;
660 for (size_t i = 0; i < kNumThreads - 1; i++) {
661 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
662 }
663
664 usleep(100000); // give chance for calls on other threads
665
666 // other calls still work
667 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
668
669 constexpr size_t blockTimeMs = 500;
670 size_t epochMsBefore = epochMillis();
671 // after this, we should never see a response within this time
672 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
673
674 // this call should be blocked for blockTimeMs
675 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
676
677 size_t epochMsAfter = epochMillis();
678 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
679
680 for (auto& t : ts) t.join();
681}
682
Steven Morelandc1635952021-04-01 16:20:47 +0000683TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000684 constexpr size_t kNumThreads = 10;
685 constexpr size_t kNumCalls = kNumThreads + 3;
686 constexpr size_t kSleepMs = 500;
687
688 auto proc = createRpcTestSocketServerProcess(kNumThreads);
689
690 size_t epochMsBefore = epochMillis();
691
692 std::vector<std::thread> ts;
693 for (size_t i = 0; i < kNumCalls; i++) {
694 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
695 }
696
697 for (auto& t : ts) t.join();
698
699 size_t epochMsAfter = epochMillis();
700
701 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
702
703 // Potential flake, but make sure calls are handled in parallel.
704 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
705}
706
Steven Morelandc1635952021-04-01 16:20:47 +0000707TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000708 constexpr size_t kNumClientThreads = 10;
709 constexpr size_t kNumServerThreads = 10;
710 constexpr size_t kNumCalls = 100;
711
712 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
713
714 std::vector<std::thread> threads;
715 for (size_t i = 0; i < kNumClientThreads; i++) {
716 threads.push_back(std::thread([&] {
717 for (size_t j = 0; j < kNumCalls; j++) {
718 sp<IBinder> out;
719 proc.rootIface->repeatBinder(proc.rootBinder, &out);
720 EXPECT_EQ(proc.rootBinder, out);
721 }
722 }));
723 }
724
725 for (auto& t : threads) t.join();
726}
727
Steven Morelandc1635952021-04-01 16:20:47 +0000728TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000729 constexpr size_t kReallyLongTimeMs = 100;
730 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
731
732 // more than one thread, just so this doesn't deadlock
733 auto proc = createRpcTestSocketServerProcess(2);
734
735 size_t epochMsBefore = epochMillis();
736
737 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
738
739 size_t epochMsAfter = epochMillis();
740 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
741}
742
Steven Morelandc1635952021-04-01 16:20:47 +0000743TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000744 constexpr size_t kNumSleeps = 10;
745 constexpr size_t kNumExtraServerThreads = 4;
746 constexpr size_t kSleepMs = 50;
747
748 // make sure calls to the same object happen on the same thread
749 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
750
751 EXPECT_OK(proc.rootIface->lock());
752
753 for (size_t i = 0; i < kNumSleeps; i++) {
754 // these should be processed serially
755 proc.rootIface->sleepMsAsync(kSleepMs);
756 }
757 // should also be processesed serially
758 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
759
760 size_t epochMsBefore = epochMillis();
761 EXPECT_OK(proc.rootIface->lockUnlock());
762 size_t epochMsAfter = epochMillis();
763
764 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
765}
766
Steven Morelandc1635952021-04-01 16:20:47 +0000767TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000768 // TODO(b/183141167): handle this in library
769 signal(SIGPIPE, SIG_IGN);
770
771 for (bool doDeathCleanup : {true, false}) {
772 auto proc = createRpcTestSocketServerProcess(1);
773
774 // make sure there is some state during crash
775 // 1. we hold their binder
776 sp<IBinderRpcSession> session;
777 EXPECT_OK(proc.rootIface->openSession("happy", &session));
778 // 2. they hold our binder
779 sp<IBinder> binder = new BBinder();
780 EXPECT_OK(proc.rootIface->holdBinder(binder));
781
782 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
783 << "Do death cleanup: " << doDeathCleanup;
784
785 proc.proc.expectInvalid = true;
786 }
787}
788
789ssize_t countFds() {
790 DIR* dir = opendir("/proc/self/fd/");
791 if (dir == nullptr) return -1;
792 ssize_t ret = 0;
793 dirent* ent;
794 while ((ent = readdir(dir)) != nullptr) ret++;
795 closedir(dir);
796 return ret;
797}
798
Steven Morelandc1635952021-04-01 16:20:47 +0000799TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000800 ssize_t beforeFds = countFds();
801 ASSERT_GE(beforeFds, 0);
802 {
803 auto proc = createRpcTestSocketServerProcess(10);
804 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
805 }
806 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
807}
808
Steven Morelandc1635952021-04-01 16:20:47 +0000809INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000810 ::testing::Values(SocketType::UNIX
811#ifdef __BIONIC__
812 ,
813 SocketType::VSOCK
814#endif // __BIONIC__
815 ),
816 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +0000817
818} // namespace android
819
820int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000821 ::testing::InitGoogleTest(&argc, argv);
822 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
823 return RUN_ALL_TESTS();
824}