blob: 33402937ab308f9d6afc3d2f1a0eb89f7987c4e2 [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
Steven Moreland1fda67b2021-04-02 18:35:50 +000047TEST(BinderRpcParcel, EntireParcelFormatted) {
48 Parcel p;
49 p.writeInt32(3);
50
51 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
52}
53
Steven Moreland5553ac42020-11-11 02:14:45 +000054using android::binder::Status;
55
56#define EXPECT_OK(status) \
57 do { \
58 Status stat = (status); \
59 EXPECT_TRUE(stat.isOk()) << stat; \
60 } while (false)
61
62class MyBinderRpcSession : public BnBinderRpcSession {
63public:
64 static std::atomic<int32_t> gNum;
65
66 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
67 Status getName(std::string* name) override {
68 *name = mName;
69 return Status::ok();
70 }
71 ~MyBinderRpcSession() { gNum--; }
72
73private:
74 std::string mName;
75};
76std::atomic<int32_t> MyBinderRpcSession::gNum;
77
78class MyBinderRpcTest : public BnBinderRpcTest {
79public:
80 sp<RpcConnection> connection;
81
82 Status sendString(const std::string& str) override {
83 std::cout << "Child received string: " << str << std::endl;
84 return Status::ok();
85 }
86 Status doubleString(const std::string& str, std::string* strstr) override {
87 std::cout << "Child received string to double: " << str << std::endl;
88 *strstr = str + str;
89 return Status::ok();
90 }
91 Status countBinders(int32_t* out) override {
92 if (connection == nullptr) {
93 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
94 }
95 *out = connection->state()->countBinders();
96 if (*out != 1) {
97 connection->state()->dump();
98 }
99 return Status::ok();
100 }
101 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
102 if (binder == nullptr) {
103 std::cout << "Received null binder!" << std::endl;
104 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
105 }
106 *out = binder->pingBinder();
107 return Status::ok();
108 }
109 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
110 *out = binder;
111 return Status::ok();
112 }
113 static sp<IBinder> mHeldBinder;
114 Status holdBinder(const sp<IBinder>& binder) override {
115 mHeldBinder = binder;
116 return Status::ok();
117 }
118 Status getHeldBinder(sp<IBinder>* held) override {
119 *held = mHeldBinder;
120 return Status::ok();
121 }
122 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
123 if (count <= 0) return Status::ok();
124 return binder->nestMe(this, count - 1);
125 }
126 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
127 static sp<IBinder> binder = new BBinder;
128 *out = binder;
129 return Status::ok();
130 }
131 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
132 *out = new MyBinderRpcSession(name);
133 return Status::ok();
134 }
135 Status getNumOpenSessions(int32_t* out) override {
136 *out = MyBinderRpcSession::gNum;
137 return Status::ok();
138 }
139
140 std::mutex blockMutex;
141 Status lock() override {
142 blockMutex.lock();
143 return Status::ok();
144 }
145 Status unlockInMsAsync(int32_t ms) override {
146 usleep(ms * 1000);
147 blockMutex.unlock();
148 return Status::ok();
149 }
150 Status lockUnlock() override {
151 std::lock_guard<std::mutex> _l(blockMutex);
152 return Status::ok();
153 }
154
155 Status sleepMs(int32_t ms) override {
156 usleep(ms * 1000);
157 return Status::ok();
158 }
159
160 Status sleepMsAsync(int32_t ms) override {
161 // In-process binder calls are asynchronous, but the call to this method
162 // is synchronous wrt its client. This in/out-process threading model
163 // diffentiation is a classic binder leaky abstraction (for better or
164 // worse) and is preserved here the way binder sockets plugs itself
165 // into BpBinder, as nothing is changed at the higher levels
166 // (IInterface) which result in this behavior.
167 return sleepMs(ms);
168 }
169
170 Status die(bool cleanup) override {
171 if (cleanup) {
172 exit(1);
173 } else {
174 _exit(1);
175 }
176 }
177};
178sp<IBinder> MyBinderRpcTest::mHeldBinder;
179
180class Process {
181public:
182 Process(const std::function<void()>& f) {
183 if (0 == (mPid = fork())) {
184 // racey: assume parent doesn't crash before this is set
185 prctl(PR_SET_PDEATHSIG, SIGHUP);
186
187 f();
188 }
189 }
190 ~Process() {
191 if (mPid != 0) {
192 kill(mPid, SIGKILL);
193 }
194 }
195
196private:
197 pid_t mPid = 0;
198};
199
200static std::string allocateSocketAddress() {
201 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000202 std::string temp = getenv("TMPDIR") ?: "/tmp";
203 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000204};
205
206struct ProcessConnection {
207 // reference to process hosting a socket server
208 Process host;
209
210 // client connection object associated with other process
211 sp<RpcConnection> connection;
212
213 // pre-fetched root object
214 sp<IBinder> rootBinder;
215
216 // whether connection should be invalidated by end of run
217 bool expectInvalid = false;
218
219 ~ProcessConnection() {
220 rootBinder = nullptr;
221 EXPECT_NE(nullptr, connection);
222 EXPECT_NE(nullptr, connection->state());
223 EXPECT_EQ(0, connection->state()->countBinders()) << (connection->state()->dump(), "dump:");
224
225 wp<RpcConnection> weakConnection = connection;
226 connection = nullptr;
227 EXPECT_EQ(nullptr, weakConnection.promote()) << "Leaked connection";
228 }
229};
230
Steven Moreland5553ac42020-11-11 02:14:45 +0000231// Process connection where the process hosts IBinderRpcTest, the server used
232// for most testing here
233struct BinderRpcTestProcessConnection {
234 ProcessConnection proc;
235
236 // pre-fetched root object
237 sp<IBinder> rootBinder;
238
239 // pre-casted root object
240 sp<IBinderRpcTest> rootIface;
241
242 ~BinderRpcTestProcessConnection() {
243 if (!proc.expectInvalid) {
244 int32_t remoteBinders = 0;
245 EXPECT_OK(rootIface->countBinders(&remoteBinders));
246 // should only be the root binder object, iface
247 EXPECT_EQ(remoteBinders, 1);
248 }
249
250 rootIface = nullptr;
251 rootBinder = nullptr;
252 }
253};
254
Steven Morelandc1635952021-04-01 16:20:47 +0000255enum class SocketType {
256 UNIX,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000257#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000258 VSOCK,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000259#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000260};
261static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
262 switch (info.param) {
263 case SocketType::UNIX:
264 return "unix_domain_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000265#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000266 case SocketType::VSOCK:
267 return "vm_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000268#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000269 default:
270 LOG_ALWAYS_FATAL("Unknown socket type");
271 return "";
272 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000273}
Steven Morelandc1635952021-04-01 16:20:47 +0000274class BinderRpc : public ::testing::TestWithParam<SocketType> {
275public:
276 // This creates a new process serving an interface on a certain number of
277 // threads.
278 ProcessConnection createRpcTestSocketServerProcess(
279 size_t numThreads,
280 const std::function<void(const sp<RpcServer>&, const sp<RpcConnection>&)>& configure) {
281 CHECK_GT(numThreads, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000282
Steven Morelandc1635952021-04-01 16:20:47 +0000283 SocketType socketType = GetParam();
284
285 std::string addr = allocateSocketAddress();
286 unlink(addr.c_str());
287 static unsigned int port = 3456;
288 port++;
289
290 auto ret = ProcessConnection{
291 .host = Process([&] {
292 sp<RpcServer> server = RpcServer::make();
293
294 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
295
296 // server supporting one client on one socket
297 sp<RpcConnection> connection = server->addClientConnection();
298
299 switch (socketType) {
300 case SocketType::UNIX:
301 CHECK(connection->setupUnixDomainServer(addr.c_str())) << addr;
302 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000303#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000304 case SocketType::VSOCK:
305 CHECK(connection->setupVsockServer(port));
306 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000307#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000308 default:
309 LOG_ALWAYS_FATAL("Unknown socket type");
310 }
311
312 configure(server, connection);
313
314 // accept 'numThreads' connections
315 std::vector<std::thread> pool;
316 for (size_t i = 0; i + 1 < numThreads; i++) {
317 pool.push_back(std::thread([=] { connection->join(); }));
318 }
319 connection->join();
320 for (auto& t : pool) t.join();
321 }),
322 .connection = RpcConnection::make(),
323 };
324
325 // create remainder of connections
326 for (size_t i = 0; i < numThreads; i++) {
327 for (size_t tries = 0; tries < 5; tries++) {
328 usleep(10000);
329 switch (socketType) {
330 case SocketType::UNIX:
331 if (ret.connection->addUnixDomainClient(addr.c_str())) goto success;
332 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000333#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000334 case SocketType::VSOCK:
335 if (ret.connection->addVsockClient(VMADDR_CID_LOCAL, port)) goto success;
336 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000337#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000338 default:
339 LOG_ALWAYS_FATAL("Unknown socket type");
340 }
341 }
342 LOG_ALWAYS_FATAL("Could not connect");
343 success:;
344 }
345
346 ret.rootBinder = ret.connection->getRootObject();
347 return ret;
348 }
349
350 BinderRpcTestProcessConnection createRpcTestSocketServerProcess(size_t numThreads) {
351 BinderRpcTestProcessConnection ret{
352 .proc = createRpcTestSocketServerProcess(numThreads,
353 [&](const sp<RpcServer>& server,
354 const sp<RpcConnection>& connection) {
355 sp<MyBinderRpcTest> service =
356 new MyBinderRpcTest;
357 server->setRootObject(service);
358 service->connection =
359 connection; // for testing only
360 }),
361 };
362
363 ret.rootBinder = ret.proc.rootBinder;
364 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
365
366 return ret;
367 }
368};
369
370TEST_P(BinderRpc, RootObjectIsNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000371 auto proc = createRpcTestSocketServerProcess(1,
372 [](const sp<RpcServer>& server,
373 const sp<RpcConnection>&) {
374 // this is the default, but to be explicit
375 server->setRootObject(nullptr);
376 });
377
378 // retrieved by getRootObject when process is created above
379 EXPECT_EQ(nullptr, proc.rootBinder);
380
381 // make sure we can retrieve it again (process doesn't crash)
382 EXPECT_EQ(nullptr, proc.connection->getRootObject());
383}
384
Steven Morelandc1635952021-04-01 16:20:47 +0000385TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000386 auto proc = createRpcTestSocketServerProcess(1);
387 ASSERT_NE(proc.rootBinder, nullptr);
388 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
389}
390
Steven Moreland4cf688f2021-03-31 01:48:58 +0000391TEST_P(BinderRpc, GetInterfaceDescriptor) {
392 auto proc = createRpcTestSocketServerProcess(1);
393 ASSERT_NE(proc.rootBinder, nullptr);
394 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
395}
396
Steven Morelandc1635952021-04-01 16:20:47 +0000397TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000398 auto proc = createRpcTestSocketServerProcess(1);
399 Parcel data;
400 Parcel reply;
401 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
402}
403
Steven Moreland67753c32021-04-02 18:45:19 +0000404TEST_P(BinderRpc, AppendSeparateFormats) {
405 auto proc = createRpcTestSocketServerProcess(1);
406
407 Parcel p1;
408 p1.markForBinder(proc.rootBinder);
409 p1.writeInt32(3);
410
411 Parcel p2;
412
413 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
414 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
415}
416
Steven Morelandc1635952021-04-01 16:20:47 +0000417TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000418 auto proc = createRpcTestSocketServerProcess(1);
419 Parcel data;
420 data.markForBinder(proc.rootBinder);
421 Parcel reply;
422 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
423}
424
Steven Morelandc1635952021-04-01 16:20:47 +0000425TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000426 auto proc = createRpcTestSocketServerProcess(1);
427 EXPECT_OK(proc.rootIface->sendString("asdf"));
428}
429
Steven Morelandc1635952021-04-01 16:20:47 +0000430TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000431 auto proc = createRpcTestSocketServerProcess(1);
432 std::string doubled;
433 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
434 EXPECT_EQ("cool cool ", doubled);
435}
436
Steven Morelandc1635952021-04-01 16:20:47 +0000437TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000438 auto proc = createRpcTestSocketServerProcess(1);
439 std::string single = std::string(1024, 'a');
440 std::string doubled;
441 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
442 EXPECT_EQ(single + single, doubled);
443}
444
Steven Morelandc1635952021-04-01 16:20:47 +0000445TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000446 auto proc = createRpcTestSocketServerProcess(1);
447
448 int32_t pingResult;
449 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
450 EXPECT_EQ(OK, pingResult);
451
452 EXPECT_EQ(0, MyBinderRpcSession::gNum);
453}
454
Steven Morelandc1635952021-04-01 16:20:47 +0000455TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000456 auto proc = createRpcTestSocketServerProcess(1);
457
458 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
459 sp<IBinder> outBinder;
460 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
461 EXPECT_EQ(inBinder, outBinder);
462
463 wp<IBinder> weak = inBinder;
464 inBinder = nullptr;
465 outBinder = nullptr;
466
467 // Force reading a reply, to process any pending dec refs from the other
468 // process (the other process will process dec refs there before processing
469 // the ping here).
470 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
471
472 EXPECT_EQ(nullptr, weak.promote());
473
474 EXPECT_EQ(0, MyBinderRpcSession::gNum);
475}
476
Steven Morelandc1635952021-04-01 16:20:47 +0000477TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000478 auto proc = createRpcTestSocketServerProcess(1);
479
480 sp<IBinderRpcSession> session;
481 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
482
483 sp<IBinder> inBinder = IInterface::asBinder(session);
484 sp<IBinder> outBinder;
485 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
486 EXPECT_EQ(inBinder, outBinder);
487
488 wp<IBinder> weak = inBinder;
489 session = nullptr;
490 inBinder = nullptr;
491 outBinder = nullptr;
492
493 // Force reading a reply, to process any pending dec refs from the other
494 // process (the other process will process dec refs there before processing
495 // the ping here).
496 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
497
498 EXPECT_EQ(nullptr, weak.promote());
499}
500
Steven Morelandc1635952021-04-01 16:20:47 +0000501TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000502 auto proc = createRpcTestSocketServerProcess(1);
503
504 sp<IBinder> outBinder;
505 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
506 EXPECT_EQ(nullptr, outBinder);
507}
508
Steven Morelandc1635952021-04-01 16:20:47 +0000509TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000510 auto proc = createRpcTestSocketServerProcess(1);
511
512 IBinder* ptr = nullptr;
513 {
514 sp<IBinder> binder = new BBinder();
515 ptr = binder.get();
516 EXPECT_OK(proc.rootIface->holdBinder(binder));
517 }
518
519 sp<IBinder> held;
520 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
521
522 EXPECT_EQ(held.get(), ptr);
523
524 // stop holding binder, because we test to make sure references are cleaned
525 // up
526 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
527 // and flush ref counts
528 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
529}
530
531// START TESTS FOR LIMITATIONS OF SOCKET BINDER
532// These are behavioral differences form regular binder, where certain usecases
533// aren't supported.
534
Steven Morelandc1635952021-04-01 16:20:47 +0000535TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketConnections) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000536 auto proc1 = createRpcTestSocketServerProcess(1);
537 auto proc2 = createRpcTestSocketServerProcess(1);
538
539 sp<IBinder> outBinder;
540 EXPECT_EQ(INVALID_OPERATION,
541 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
542}
543
Steven Morelandc1635952021-04-01 16:20:47 +0000544TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000545 auto proc = createRpcTestSocketServerProcess(1);
546
547 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
548 sp<IBinder> outBinder;
549 EXPECT_EQ(INVALID_OPERATION,
550 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
551}
552
Steven Morelandc1635952021-04-01 16:20:47 +0000553TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000554 auto proc = createRpcTestSocketServerProcess(1);
555
556 // for historical reasons, IServiceManager interface only returns the
557 // exception code
558 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
559 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
560}
561
562// END TESTS FOR LIMITATIONS OF SOCKET BINDER
563
Steven Morelandc1635952021-04-01 16:20:47 +0000564TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000565 auto proc = createRpcTestSocketServerProcess(1);
566
567 sp<IBinder> outBinder;
568 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
569 EXPECT_EQ(proc.rootBinder, outBinder);
570}
571
Steven Morelandc1635952021-04-01 16:20:47 +0000572TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000573 auto proc = createRpcTestSocketServerProcess(1);
574
575 auto nastyNester = sp<MyBinderRpcTest>::make();
576 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
577
578 wp<IBinder> weak = nastyNester;
579 nastyNester = nullptr;
580 EXPECT_EQ(nullptr, weak.promote());
581}
582
Steven Morelandc1635952021-04-01 16:20:47 +0000583TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000584 auto proc = createRpcTestSocketServerProcess(1);
585
586 sp<IBinder> a;
587 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
588
589 sp<IBinder> b;
590 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
591
592 EXPECT_EQ(a, b);
593}
594
Steven Morelandc1635952021-04-01 16:20:47 +0000595TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000596 auto proc = createRpcTestSocketServerProcess(1);
597
598 sp<IBinder> a;
599 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
600 wp<IBinder> weak = a;
601 a = nullptr;
602
603 sp<IBinder> b;
604 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
605
606 // this is the wrong behavior, since BpBinder
607 // doesn't implement onIncStrongAttempted
608 // but make sure there is no crash
609 EXPECT_EQ(nullptr, weak.promote());
610
611 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
612
613 // In order to fix this:
614 // - need to have incStrongAttempted reflected across IPC boundary (wait for
615 // response to promote - round trip...)
616 // - sendOnLastWeakRef, to delete entries out of RpcState table
617 EXPECT_EQ(b, weak.promote());
618}
619
620#define expectSessions(expected, iface) \
621 do { \
622 int session; \
623 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
624 EXPECT_EQ(expected, session); \
625 } while (false)
626
Steven Morelandc1635952021-04-01 16:20:47 +0000627TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000628 auto proc = createRpcTestSocketServerProcess(1);
629
630 sp<IBinderRpcSession> session;
631 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
632 std::string out;
633 EXPECT_OK(session->getName(&out));
634 EXPECT_EQ("aoeu", out);
635
636 expectSessions(1, proc.rootIface);
637 session = nullptr;
638 expectSessions(0, proc.rootIface);
639}
640
Steven Morelandc1635952021-04-01 16:20:47 +0000641TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000642 auto proc = createRpcTestSocketServerProcess(1);
643
644 std::vector<sp<IBinderRpcSession>> sessions;
645
646 for (size_t i = 0; i < 15; i++) {
647 expectSessions(i, proc.rootIface);
648 sp<IBinderRpcSession> session;
649 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
650 sessions.push_back(session);
651 }
652 expectSessions(sessions.size(), proc.rootIface);
653 for (size_t i = 0; i < sessions.size(); i++) {
654 std::string out;
655 EXPECT_OK(sessions.at(i)->getName(&out));
656 EXPECT_EQ(std::to_string(i), out);
657 }
658 expectSessions(sessions.size(), proc.rootIface);
659
660 while (!sessions.empty()) {
661 sessions.pop_back();
662 expectSessions(sessions.size(), proc.rootIface);
663 }
664 expectSessions(0, proc.rootIface);
665}
666
667size_t epochMillis() {
668 using std::chrono::duration_cast;
669 using std::chrono::milliseconds;
670 using std::chrono::seconds;
671 using std::chrono::system_clock;
672 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
673}
674
Steven Morelandc1635952021-04-01 16:20:47 +0000675TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000676 constexpr size_t kNumThreads = 10;
677
678 auto proc = createRpcTestSocketServerProcess(kNumThreads);
679
680 EXPECT_OK(proc.rootIface->lock());
681
682 // block all but one thread taking locks
683 std::vector<std::thread> ts;
684 for (size_t i = 0; i < kNumThreads - 1; i++) {
685 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
686 }
687
688 usleep(100000); // give chance for calls on other threads
689
690 // other calls still work
691 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
692
693 constexpr size_t blockTimeMs = 500;
694 size_t epochMsBefore = epochMillis();
695 // after this, we should never see a response within this time
696 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
697
698 // this call should be blocked for blockTimeMs
699 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
700
701 size_t epochMsAfter = epochMillis();
702 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
703
704 for (auto& t : ts) t.join();
705}
706
Steven Morelandc1635952021-04-01 16:20:47 +0000707TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000708 constexpr size_t kNumThreads = 10;
709 constexpr size_t kNumCalls = kNumThreads + 3;
710 constexpr size_t kSleepMs = 500;
711
712 auto proc = createRpcTestSocketServerProcess(kNumThreads);
713
714 size_t epochMsBefore = epochMillis();
715
716 std::vector<std::thread> ts;
717 for (size_t i = 0; i < kNumCalls; i++) {
718 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
719 }
720
721 for (auto& t : ts) t.join();
722
723 size_t epochMsAfter = epochMillis();
724
725 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
726
727 // Potential flake, but make sure calls are handled in parallel.
728 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
729}
730
Steven Morelandc1635952021-04-01 16:20:47 +0000731TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000732 constexpr size_t kNumClientThreads = 10;
733 constexpr size_t kNumServerThreads = 10;
734 constexpr size_t kNumCalls = 100;
735
736 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
737
738 std::vector<std::thread> threads;
739 for (size_t i = 0; i < kNumClientThreads; i++) {
740 threads.push_back(std::thread([&] {
741 for (size_t j = 0; j < kNumCalls; j++) {
742 sp<IBinder> out;
743 proc.rootIface->repeatBinder(proc.rootBinder, &out);
744 EXPECT_EQ(proc.rootBinder, out);
745 }
746 }));
747 }
748
749 for (auto& t : threads) t.join();
750}
751
Steven Morelandc1635952021-04-01 16:20:47 +0000752TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000753 constexpr size_t kReallyLongTimeMs = 100;
754 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
755
756 // more than one thread, just so this doesn't deadlock
757 auto proc = createRpcTestSocketServerProcess(2);
758
759 size_t epochMsBefore = epochMillis();
760
761 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
762
763 size_t epochMsAfter = epochMillis();
764 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
765}
766
Steven Morelandc1635952021-04-01 16:20:47 +0000767TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000768 constexpr size_t kNumSleeps = 10;
769 constexpr size_t kNumExtraServerThreads = 4;
770 constexpr size_t kSleepMs = 50;
771
772 // make sure calls to the same object happen on the same thread
773 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
774
775 EXPECT_OK(proc.rootIface->lock());
776
777 for (size_t i = 0; i < kNumSleeps; i++) {
778 // these should be processed serially
779 proc.rootIface->sleepMsAsync(kSleepMs);
780 }
781 // should also be processesed serially
782 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
783
784 size_t epochMsBefore = epochMillis();
785 EXPECT_OK(proc.rootIface->lockUnlock());
786 size_t epochMsAfter = epochMillis();
787
788 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
789}
790
Steven Morelandc1635952021-04-01 16:20:47 +0000791TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000792 for (bool doDeathCleanup : {true, false}) {
793 auto proc = createRpcTestSocketServerProcess(1);
794
795 // make sure there is some state during crash
796 // 1. we hold their binder
797 sp<IBinderRpcSession> session;
798 EXPECT_OK(proc.rootIface->openSession("happy", &session));
799 // 2. they hold our binder
800 sp<IBinder> binder = new BBinder();
801 EXPECT_OK(proc.rootIface->holdBinder(binder));
802
803 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
804 << "Do death cleanup: " << doDeathCleanup;
805
806 proc.proc.expectInvalid = true;
807 }
808}
809
Steven Moreland37aff182021-03-26 02:04:16 +0000810TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
811 auto proc = createRpcTestSocketServerProcess(1);
812
813 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
814 ASSERT_NE(binder, nullptr);
815
816 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
817}
818
819TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
820 auto proc = createRpcTestSocketServerProcess(1);
821
822 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
823 ASSERT_NE(binder, nullptr);
824
825 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
826 ASSERT_NE(ndkBinder, nullptr);
827
828 std::string out;
829 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
830 ASSERT_TRUE(status.isOk()) << status.getDescription();
831 ASSERT_EQ("aoeuaoeu", out);
832}
833
Steven Moreland5553ac42020-11-11 02:14:45 +0000834ssize_t countFds() {
835 DIR* dir = opendir("/proc/self/fd/");
836 if (dir == nullptr) return -1;
837 ssize_t ret = 0;
838 dirent* ent;
839 while ((ent = readdir(dir)) != nullptr) ret++;
840 closedir(dir);
841 return ret;
842}
843
Steven Morelandc1635952021-04-01 16:20:47 +0000844TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000845 ssize_t beforeFds = countFds();
846 ASSERT_GE(beforeFds, 0);
847 {
848 auto proc = createRpcTestSocketServerProcess(10);
849 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
850 }
851 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
852}
853
Steven Morelandc1635952021-04-01 16:20:47 +0000854INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000855 ::testing::Values(SocketType::UNIX
856#ifdef __BIONIC__
857 ,
858 SocketType::VSOCK
859#endif // __BIONIC__
860 ),
861 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +0000862
863} // namespace android
864
865int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000866 ::testing::InitGoogleTest(&argc, argv);
867 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
868 return RUN_ALL_TESTS();
869}