blob: 27f18df0967bd30910d43b60a4c917ffbcaa891e [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>
Steven Moreland37aff182021-03-26 02:04:16 +000019#include <aidl/IBinderRpcTest.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000020#include <android-base/logging.h>
Steven Moreland37aff182021-03-26 02:04:16 +000021#include <android/binder_auto_utils.h>
22#include <android/binder_libbinder.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000023#include <binder/Binder.h>
24#include <binder/BpBinder.h>
25#include <binder/IServiceManager.h>
26#include <binder/ProcessState.h>
27#include <binder/RpcConnection.h>
28#include <binder/RpcServer.h>
29#include <gtest/gtest.h>
30
Steven Morelandc1635952021-04-01 16:20:47 +000031#include <chrono>
32#include <cstdlib>
33#include <iostream>
34#include <thread>
35
Steven Morelandf6ec4632021-04-01 16:20:47 +000036#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +000037#include <linux/vm_sockets.h>
Steven Morelandf6ec4632021-04-01 16:20:47 +000038#endif //__BIONIC__
39
Steven Morelandc1635952021-04-01 16:20:47 +000040#include <sys/prctl.h>
41#include <unistd.h>
42
Steven Moreland5553ac42020-11-11 02:14:45 +000043#include "../RpcState.h" // for debugging
44
45namespace android {
46
47using android::binder::Status;
48
49#define EXPECT_OK(status) \
50 do { \
51 Status stat = (status); \
52 EXPECT_TRUE(stat.isOk()) << stat; \
53 } while (false)
54
55class MyBinderRpcSession : public BnBinderRpcSession {
56public:
57 static std::atomic<int32_t> gNum;
58
59 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
60 Status getName(std::string* name) override {
61 *name = mName;
62 return Status::ok();
63 }
64 ~MyBinderRpcSession() { gNum--; }
65
66private:
67 std::string mName;
68};
69std::atomic<int32_t> MyBinderRpcSession::gNum;
70
71class MyBinderRpcTest : public BnBinderRpcTest {
72public:
73 sp<RpcConnection> connection;
74
75 Status sendString(const std::string& str) override {
76 std::cout << "Child received string: " << str << std::endl;
77 return Status::ok();
78 }
79 Status doubleString(const std::string& str, std::string* strstr) override {
80 std::cout << "Child received string to double: " << str << std::endl;
81 *strstr = str + str;
82 return Status::ok();
83 }
84 Status countBinders(int32_t* out) override {
85 if (connection == nullptr) {
86 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
87 }
88 *out = connection->state()->countBinders();
89 if (*out != 1) {
90 connection->state()->dump();
91 }
92 return Status::ok();
93 }
94 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
95 if (binder == nullptr) {
96 std::cout << "Received null binder!" << std::endl;
97 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
98 }
99 *out = binder->pingBinder();
100 return Status::ok();
101 }
102 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
103 *out = binder;
104 return Status::ok();
105 }
106 static sp<IBinder> mHeldBinder;
107 Status holdBinder(const sp<IBinder>& binder) override {
108 mHeldBinder = binder;
109 return Status::ok();
110 }
111 Status getHeldBinder(sp<IBinder>* held) override {
112 *held = mHeldBinder;
113 return Status::ok();
114 }
115 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
116 if (count <= 0) return Status::ok();
117 return binder->nestMe(this, count - 1);
118 }
119 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
120 static sp<IBinder> binder = new BBinder;
121 *out = binder;
122 return Status::ok();
123 }
124 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
125 *out = new MyBinderRpcSession(name);
126 return Status::ok();
127 }
128 Status getNumOpenSessions(int32_t* out) override {
129 *out = MyBinderRpcSession::gNum;
130 return Status::ok();
131 }
132
133 std::mutex blockMutex;
134 Status lock() override {
135 blockMutex.lock();
136 return Status::ok();
137 }
138 Status unlockInMsAsync(int32_t ms) override {
139 usleep(ms * 1000);
140 blockMutex.unlock();
141 return Status::ok();
142 }
143 Status lockUnlock() override {
144 std::lock_guard<std::mutex> _l(blockMutex);
145 return Status::ok();
146 }
147
148 Status sleepMs(int32_t ms) override {
149 usleep(ms * 1000);
150 return Status::ok();
151 }
152
153 Status sleepMsAsync(int32_t ms) override {
154 // In-process binder calls are asynchronous, but the call to this method
155 // is synchronous wrt its client. This in/out-process threading model
156 // diffentiation is a classic binder leaky abstraction (for better or
157 // worse) and is preserved here the way binder sockets plugs itself
158 // into BpBinder, as nothing is changed at the higher levels
159 // (IInterface) which result in this behavior.
160 return sleepMs(ms);
161 }
162
163 Status die(bool cleanup) override {
164 if (cleanup) {
165 exit(1);
166 } else {
167 _exit(1);
168 }
169 }
170};
171sp<IBinder> MyBinderRpcTest::mHeldBinder;
172
173class Process {
174public:
175 Process(const std::function<void()>& f) {
176 if (0 == (mPid = fork())) {
177 // racey: assume parent doesn't crash before this is set
178 prctl(PR_SET_PDEATHSIG, SIGHUP);
179
180 f();
181 }
182 }
183 ~Process() {
184 if (mPid != 0) {
185 kill(mPid, SIGKILL);
186 }
187 }
188
189private:
190 pid_t mPid = 0;
191};
192
193static std::string allocateSocketAddress() {
194 static size_t id = 0;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000195 static bool gUseTmp = access("/tmp/", F_OK) != -1;
Steven Moreland5553ac42020-11-11 02:14:45 +0000196
Steven Morelandf6ec4632021-04-01 16:20:47 +0000197 if (gUseTmp) {
198 return "/tmp/binderRpcTest_" + std::to_string(id++);
199 } else {
200 return "/dev/binderRpcTest_" + std::to_string(id++);
201 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000202};
203
204struct ProcessConnection {
205 // reference to process hosting a socket server
206 Process host;
207
208 // client connection object associated with other process
209 sp<RpcConnection> connection;
210
211 // pre-fetched root object
212 sp<IBinder> rootBinder;
213
214 // whether connection should be invalidated by end of run
215 bool expectInvalid = false;
216
217 ~ProcessConnection() {
218 rootBinder = nullptr;
219 EXPECT_NE(nullptr, connection);
220 EXPECT_NE(nullptr, connection->state());
221 EXPECT_EQ(0, connection->state()->countBinders()) << (connection->state()->dump(), "dump:");
222
223 wp<RpcConnection> weakConnection = connection;
224 connection = nullptr;
225 EXPECT_EQ(nullptr, weakConnection.promote()) << "Leaked connection";
226 }
227};
228
Steven Moreland5553ac42020-11-11 02:14:45 +0000229// Process connection where the process hosts IBinderRpcTest, the server used
230// for most testing here
231struct BinderRpcTestProcessConnection {
232 ProcessConnection proc;
233
234 // pre-fetched root object
235 sp<IBinder> rootBinder;
236
237 // pre-casted root object
238 sp<IBinderRpcTest> rootIface;
239
240 ~BinderRpcTestProcessConnection() {
241 if (!proc.expectInvalid) {
242 int32_t remoteBinders = 0;
243 EXPECT_OK(rootIface->countBinders(&remoteBinders));
244 // should only be the root binder object, iface
245 EXPECT_EQ(remoteBinders, 1);
246 }
247
248 rootIface = nullptr;
249 rootBinder = nullptr;
250 }
251};
252
Steven Morelandc1635952021-04-01 16:20:47 +0000253enum class SocketType {
254 UNIX,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000255#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000256 VSOCK,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000257#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000258};
259static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
260 switch (info.param) {
261 case SocketType::UNIX:
262 return "unix_domain_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000263#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000264 case SocketType::VSOCK:
265 return "vm_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000266#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000267 default:
268 LOG_ALWAYS_FATAL("Unknown socket type");
269 return "";
270 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000271}
Steven Morelandc1635952021-04-01 16:20:47 +0000272class BinderRpc : public ::testing::TestWithParam<SocketType> {
273public:
274 // This creates a new process serving an interface on a certain number of
275 // threads.
276 ProcessConnection createRpcTestSocketServerProcess(
277 size_t numThreads,
278 const std::function<void(const sp<RpcServer>&, const sp<RpcConnection>&)>& configure) {
279 CHECK_GT(numThreads, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000280
Steven Morelandc1635952021-04-01 16:20:47 +0000281 SocketType socketType = GetParam();
282
283 std::string addr = allocateSocketAddress();
284 unlink(addr.c_str());
285 static unsigned int port = 3456;
286 port++;
287
288 auto ret = ProcessConnection{
289 .host = Process([&] {
290 sp<RpcServer> server = RpcServer::make();
291
292 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
293
294 // server supporting one client on one socket
295 sp<RpcConnection> connection = server->addClientConnection();
296
297 switch (socketType) {
298 case SocketType::UNIX:
299 CHECK(connection->setupUnixDomainServer(addr.c_str())) << addr;
300 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000301#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000302 case SocketType::VSOCK:
303 CHECK(connection->setupVsockServer(port));
304 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000305#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000306 default:
307 LOG_ALWAYS_FATAL("Unknown socket type");
308 }
309
310 configure(server, connection);
311
312 // accept 'numThreads' connections
313 std::vector<std::thread> pool;
314 for (size_t i = 0; i + 1 < numThreads; i++) {
315 pool.push_back(std::thread([=] { connection->join(); }));
316 }
317 connection->join();
318 for (auto& t : pool) t.join();
319 }),
320 .connection = RpcConnection::make(),
321 };
322
323 // create remainder of connections
324 for (size_t i = 0; i < numThreads; i++) {
325 for (size_t tries = 0; tries < 5; tries++) {
326 usleep(10000);
327 switch (socketType) {
328 case SocketType::UNIX:
329 if (ret.connection->addUnixDomainClient(addr.c_str())) goto success;
330 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000331#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000332 case SocketType::VSOCK:
333 if (ret.connection->addVsockClient(VMADDR_CID_LOCAL, port)) goto success;
334 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000335#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000336 default:
337 LOG_ALWAYS_FATAL("Unknown socket type");
338 }
339 }
340 LOG_ALWAYS_FATAL("Could not connect");
341 success:;
342 }
343
344 ret.rootBinder = ret.connection->getRootObject();
345 return ret;
346 }
347
348 BinderRpcTestProcessConnection createRpcTestSocketServerProcess(size_t numThreads) {
349 BinderRpcTestProcessConnection ret{
350 .proc = createRpcTestSocketServerProcess(numThreads,
351 [&](const sp<RpcServer>& server,
352 const sp<RpcConnection>& connection) {
353 sp<MyBinderRpcTest> service =
354 new MyBinderRpcTest;
355 server->setRootObject(service);
356 service->connection =
357 connection; // for testing only
358 }),
359 };
360
361 ret.rootBinder = ret.proc.rootBinder;
362 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
363
364 return ret;
365 }
366};
367
368TEST_P(BinderRpc, RootObjectIsNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000369 auto proc = createRpcTestSocketServerProcess(1,
370 [](const sp<RpcServer>& server,
371 const sp<RpcConnection>&) {
372 // this is the default, but to be explicit
373 server->setRootObject(nullptr);
374 });
375
376 // retrieved by getRootObject when process is created above
377 EXPECT_EQ(nullptr, proc.rootBinder);
378
379 // make sure we can retrieve it again (process doesn't crash)
380 EXPECT_EQ(nullptr, proc.connection->getRootObject());
381}
382
Steven Morelandc1635952021-04-01 16:20:47 +0000383TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000384 auto proc = createRpcTestSocketServerProcess(1);
385 ASSERT_NE(proc.rootBinder, nullptr);
386 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
387}
388
Steven Moreland4cf688f2021-03-31 01:48:58 +0000389TEST_P(BinderRpc, GetInterfaceDescriptor) {
390 auto proc = createRpcTestSocketServerProcess(1);
391 ASSERT_NE(proc.rootBinder, nullptr);
392 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
393}
394
Steven Morelandc1635952021-04-01 16:20:47 +0000395TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000396 auto proc = createRpcTestSocketServerProcess(1);
397 Parcel data;
398 Parcel reply;
399 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
400}
401
Steven Morelandc1635952021-04-01 16:20:47 +0000402TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000403 auto proc = createRpcTestSocketServerProcess(1);
404 Parcel data;
405 data.markForBinder(proc.rootBinder);
406 Parcel reply;
407 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
408}
409
Steven Morelandc1635952021-04-01 16:20:47 +0000410TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000411 auto proc = createRpcTestSocketServerProcess(1);
412 EXPECT_OK(proc.rootIface->sendString("asdf"));
413}
414
Steven Morelandc1635952021-04-01 16:20:47 +0000415TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000416 auto proc = createRpcTestSocketServerProcess(1);
417 std::string doubled;
418 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
419 EXPECT_EQ("cool cool ", doubled);
420}
421
Steven Morelandc1635952021-04-01 16:20:47 +0000422TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000423 auto proc = createRpcTestSocketServerProcess(1);
424 std::string single = std::string(1024, 'a');
425 std::string doubled;
426 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
427 EXPECT_EQ(single + single, doubled);
428}
429
Steven Morelandc1635952021-04-01 16:20:47 +0000430TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000431 auto proc = createRpcTestSocketServerProcess(1);
432
433 int32_t pingResult;
434 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
435 EXPECT_EQ(OK, pingResult);
436
437 EXPECT_EQ(0, MyBinderRpcSession::gNum);
438}
439
Steven Morelandc1635952021-04-01 16:20:47 +0000440TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000441 auto proc = createRpcTestSocketServerProcess(1);
442
443 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
444 sp<IBinder> outBinder;
445 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
446 EXPECT_EQ(inBinder, outBinder);
447
448 wp<IBinder> weak = inBinder;
449 inBinder = nullptr;
450 outBinder = nullptr;
451
452 // Force reading a reply, to process any pending dec refs from the other
453 // process (the other process will process dec refs there before processing
454 // the ping here).
455 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
456
457 EXPECT_EQ(nullptr, weak.promote());
458
459 EXPECT_EQ(0, MyBinderRpcSession::gNum);
460}
461
Steven Morelandc1635952021-04-01 16:20:47 +0000462TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000463 auto proc = createRpcTestSocketServerProcess(1);
464
465 sp<IBinderRpcSession> session;
466 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
467
468 sp<IBinder> inBinder = IInterface::asBinder(session);
469 sp<IBinder> outBinder;
470 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
471 EXPECT_EQ(inBinder, outBinder);
472
473 wp<IBinder> weak = inBinder;
474 session = nullptr;
475 inBinder = nullptr;
476 outBinder = nullptr;
477
478 // Force reading a reply, to process any pending dec refs from the other
479 // process (the other process will process dec refs there before processing
480 // the ping here).
481 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
482
483 EXPECT_EQ(nullptr, weak.promote());
484}
485
Steven Morelandc1635952021-04-01 16:20:47 +0000486TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000487 auto proc = createRpcTestSocketServerProcess(1);
488
489 sp<IBinder> outBinder;
490 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
491 EXPECT_EQ(nullptr, outBinder);
492}
493
Steven Morelandc1635952021-04-01 16:20:47 +0000494TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000495 auto proc = createRpcTestSocketServerProcess(1);
496
497 IBinder* ptr = nullptr;
498 {
499 sp<IBinder> binder = new BBinder();
500 ptr = binder.get();
501 EXPECT_OK(proc.rootIface->holdBinder(binder));
502 }
503
504 sp<IBinder> held;
505 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
506
507 EXPECT_EQ(held.get(), ptr);
508
509 // stop holding binder, because we test to make sure references are cleaned
510 // up
511 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
512 // and flush ref counts
513 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
514}
515
516// START TESTS FOR LIMITATIONS OF SOCKET BINDER
517// These are behavioral differences form regular binder, where certain usecases
518// aren't supported.
519
Steven Morelandc1635952021-04-01 16:20:47 +0000520TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketConnections) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000521 auto proc1 = createRpcTestSocketServerProcess(1);
522 auto proc2 = createRpcTestSocketServerProcess(1);
523
524 sp<IBinder> outBinder;
525 EXPECT_EQ(INVALID_OPERATION,
526 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
527}
528
Steven Morelandc1635952021-04-01 16:20:47 +0000529TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000530 auto proc = createRpcTestSocketServerProcess(1);
531
532 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
533 sp<IBinder> outBinder;
534 EXPECT_EQ(INVALID_OPERATION,
535 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
536}
537
Steven Morelandc1635952021-04-01 16:20:47 +0000538TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000539 auto proc = createRpcTestSocketServerProcess(1);
540
541 // for historical reasons, IServiceManager interface only returns the
542 // exception code
543 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
544 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
545}
546
547// END TESTS FOR LIMITATIONS OF SOCKET BINDER
548
Steven Morelandc1635952021-04-01 16:20:47 +0000549TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000550 auto proc = createRpcTestSocketServerProcess(1);
551
552 sp<IBinder> outBinder;
553 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
554 EXPECT_EQ(proc.rootBinder, outBinder);
555}
556
Steven Morelandc1635952021-04-01 16:20:47 +0000557TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000558 auto proc = createRpcTestSocketServerProcess(1);
559
560 auto nastyNester = sp<MyBinderRpcTest>::make();
561 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
562
563 wp<IBinder> weak = nastyNester;
564 nastyNester = nullptr;
565 EXPECT_EQ(nullptr, weak.promote());
566}
567
Steven Morelandc1635952021-04-01 16:20:47 +0000568TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000569 auto proc = createRpcTestSocketServerProcess(1);
570
571 sp<IBinder> a;
572 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
573
574 sp<IBinder> b;
575 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
576
577 EXPECT_EQ(a, b);
578}
579
Steven Morelandc1635952021-04-01 16:20:47 +0000580TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000581 auto proc = createRpcTestSocketServerProcess(1);
582
583 sp<IBinder> a;
584 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
585 wp<IBinder> weak = a;
586 a = nullptr;
587
588 sp<IBinder> b;
589 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
590
591 // this is the wrong behavior, since BpBinder
592 // doesn't implement onIncStrongAttempted
593 // but make sure there is no crash
594 EXPECT_EQ(nullptr, weak.promote());
595
596 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
597
598 // In order to fix this:
599 // - need to have incStrongAttempted reflected across IPC boundary (wait for
600 // response to promote - round trip...)
601 // - sendOnLastWeakRef, to delete entries out of RpcState table
602 EXPECT_EQ(b, weak.promote());
603}
604
605#define expectSessions(expected, iface) \
606 do { \
607 int session; \
608 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
609 EXPECT_EQ(expected, session); \
610 } while (false)
611
Steven Morelandc1635952021-04-01 16:20:47 +0000612TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000613 auto proc = createRpcTestSocketServerProcess(1);
614
615 sp<IBinderRpcSession> session;
616 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
617 std::string out;
618 EXPECT_OK(session->getName(&out));
619 EXPECT_EQ("aoeu", out);
620
621 expectSessions(1, proc.rootIface);
622 session = nullptr;
623 expectSessions(0, proc.rootIface);
624}
625
Steven Morelandc1635952021-04-01 16:20:47 +0000626TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000627 auto proc = createRpcTestSocketServerProcess(1);
628
629 std::vector<sp<IBinderRpcSession>> sessions;
630
631 for (size_t i = 0; i < 15; i++) {
632 expectSessions(i, proc.rootIface);
633 sp<IBinderRpcSession> session;
634 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
635 sessions.push_back(session);
636 }
637 expectSessions(sessions.size(), proc.rootIface);
638 for (size_t i = 0; i < sessions.size(); i++) {
639 std::string out;
640 EXPECT_OK(sessions.at(i)->getName(&out));
641 EXPECT_EQ(std::to_string(i), out);
642 }
643 expectSessions(sessions.size(), proc.rootIface);
644
645 while (!sessions.empty()) {
646 sessions.pop_back();
647 expectSessions(sessions.size(), proc.rootIface);
648 }
649 expectSessions(0, proc.rootIface);
650}
651
652size_t epochMillis() {
653 using std::chrono::duration_cast;
654 using std::chrono::milliseconds;
655 using std::chrono::seconds;
656 using std::chrono::system_clock;
657 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
658}
659
Steven Morelandc1635952021-04-01 16:20:47 +0000660TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000661 constexpr size_t kNumThreads = 10;
662
663 auto proc = createRpcTestSocketServerProcess(kNumThreads);
664
665 EXPECT_OK(proc.rootIface->lock());
666
667 // block all but one thread taking locks
668 std::vector<std::thread> ts;
669 for (size_t i = 0; i < kNumThreads - 1; i++) {
670 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
671 }
672
673 usleep(100000); // give chance for calls on other threads
674
675 // other calls still work
676 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
677
678 constexpr size_t blockTimeMs = 500;
679 size_t epochMsBefore = epochMillis();
680 // after this, we should never see a response within this time
681 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
682
683 // this call should be blocked for blockTimeMs
684 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
685
686 size_t epochMsAfter = epochMillis();
687 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
688
689 for (auto& t : ts) t.join();
690}
691
Steven Morelandc1635952021-04-01 16:20:47 +0000692TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000693 constexpr size_t kNumThreads = 10;
694 constexpr size_t kNumCalls = kNumThreads + 3;
695 constexpr size_t kSleepMs = 500;
696
697 auto proc = createRpcTestSocketServerProcess(kNumThreads);
698
699 size_t epochMsBefore = epochMillis();
700
701 std::vector<std::thread> ts;
702 for (size_t i = 0; i < kNumCalls; i++) {
703 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
704 }
705
706 for (auto& t : ts) t.join();
707
708 size_t epochMsAfter = epochMillis();
709
710 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
711
712 // Potential flake, but make sure calls are handled in parallel.
713 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
714}
715
Steven Morelandc1635952021-04-01 16:20:47 +0000716TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000717 constexpr size_t kNumClientThreads = 10;
718 constexpr size_t kNumServerThreads = 10;
719 constexpr size_t kNumCalls = 100;
720
721 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
722
723 std::vector<std::thread> threads;
724 for (size_t i = 0; i < kNumClientThreads; i++) {
725 threads.push_back(std::thread([&] {
726 for (size_t j = 0; j < kNumCalls; j++) {
727 sp<IBinder> out;
728 proc.rootIface->repeatBinder(proc.rootBinder, &out);
729 EXPECT_EQ(proc.rootBinder, out);
730 }
731 }));
732 }
733
734 for (auto& t : threads) t.join();
735}
736
Steven Morelandc1635952021-04-01 16:20:47 +0000737TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000738 constexpr size_t kReallyLongTimeMs = 100;
739 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
740
741 // more than one thread, just so this doesn't deadlock
742 auto proc = createRpcTestSocketServerProcess(2);
743
744 size_t epochMsBefore = epochMillis();
745
746 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
747
748 size_t epochMsAfter = epochMillis();
749 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
750}
751
Steven Morelandc1635952021-04-01 16:20:47 +0000752TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000753 constexpr size_t kNumSleeps = 10;
754 constexpr size_t kNumExtraServerThreads = 4;
755 constexpr size_t kSleepMs = 50;
756
757 // make sure calls to the same object happen on the same thread
758 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
759
760 EXPECT_OK(proc.rootIface->lock());
761
762 for (size_t i = 0; i < kNumSleeps; i++) {
763 // these should be processed serially
764 proc.rootIface->sleepMsAsync(kSleepMs);
765 }
766 // should also be processesed serially
767 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
768
769 size_t epochMsBefore = epochMillis();
770 EXPECT_OK(proc.rootIface->lockUnlock());
771 size_t epochMsAfter = epochMillis();
772
773 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
774}
775
Steven Morelandc1635952021-04-01 16:20:47 +0000776TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000777 // TODO(b/183141167): handle this in library
778 signal(SIGPIPE, SIG_IGN);
779
780 for (bool doDeathCleanup : {true, false}) {
781 auto proc = createRpcTestSocketServerProcess(1);
782
783 // make sure there is some state during crash
784 // 1. we hold their binder
785 sp<IBinderRpcSession> session;
786 EXPECT_OK(proc.rootIface->openSession("happy", &session));
787 // 2. they hold our binder
788 sp<IBinder> binder = new BBinder();
789 EXPECT_OK(proc.rootIface->holdBinder(binder));
790
791 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
792 << "Do death cleanup: " << doDeathCleanup;
793
794 proc.proc.expectInvalid = true;
795 }
796}
797
Steven Moreland37aff182021-03-26 02:04:16 +0000798TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
799 auto proc = createRpcTestSocketServerProcess(1);
800
801 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
802 ASSERT_NE(binder, nullptr);
803
804 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
805}
806
807TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
808 auto proc = createRpcTestSocketServerProcess(1);
809
810 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
811 ASSERT_NE(binder, nullptr);
812
813 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
814 ASSERT_NE(ndkBinder, nullptr);
815
816 std::string out;
817 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
818 ASSERT_TRUE(status.isOk()) << status.getDescription();
819 ASSERT_EQ("aoeuaoeu", out);
820}
821
Steven Moreland5553ac42020-11-11 02:14:45 +0000822ssize_t countFds() {
823 DIR* dir = opendir("/proc/self/fd/");
824 if (dir == nullptr) return -1;
825 ssize_t ret = 0;
826 dirent* ent;
827 while ((ent = readdir(dir)) != nullptr) ret++;
828 closedir(dir);
829 return ret;
830}
831
Steven Morelandc1635952021-04-01 16:20:47 +0000832TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000833 ssize_t beforeFds = countFds();
834 ASSERT_GE(beforeFds, 0);
835 {
836 auto proc = createRpcTestSocketServerProcess(10);
837 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
838 }
839 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
840}
841
Steven Morelandc1635952021-04-01 16:20:47 +0000842INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000843 ::testing::Values(SocketType::UNIX
844#ifdef __BIONIC__
845 ,
846 SocketType::VSOCK
847#endif // __BIONIC__
848 ),
849 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +0000850
851} // namespace android
852
853int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000854 ::testing::InitGoogleTest(&argc, argv);
855 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
856 return RUN_ALL_TESTS();
857}