blob: 985d086d738fc70dca04de2f1367598220b5b74f [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 Morelandf6ec4632021-04-01 16:20:47 +0000202 static bool gUseTmp = access("/tmp/", F_OK) != -1;
Steven Moreland5553ac42020-11-11 02:14:45 +0000203
Steven Morelandf6ec4632021-04-01 16:20:47 +0000204 if (gUseTmp) {
205 return "/tmp/binderRpcTest_" + std::to_string(id++);
206 } else {
207 return "/dev/binderRpcTest_" + std::to_string(id++);
208 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000209};
210
211struct ProcessConnection {
212 // reference to process hosting a socket server
213 Process host;
214
215 // client connection object associated with other process
216 sp<RpcConnection> connection;
217
218 // pre-fetched root object
219 sp<IBinder> rootBinder;
220
221 // whether connection should be invalidated by end of run
222 bool expectInvalid = false;
223
224 ~ProcessConnection() {
225 rootBinder = nullptr;
226 EXPECT_NE(nullptr, connection);
227 EXPECT_NE(nullptr, connection->state());
228 EXPECT_EQ(0, connection->state()->countBinders()) << (connection->state()->dump(), "dump:");
229
230 wp<RpcConnection> weakConnection = connection;
231 connection = nullptr;
232 EXPECT_EQ(nullptr, weakConnection.promote()) << "Leaked connection";
233 }
234};
235
Steven Moreland5553ac42020-11-11 02:14:45 +0000236// Process connection where the process hosts IBinderRpcTest, the server used
237// for most testing here
238struct BinderRpcTestProcessConnection {
239 ProcessConnection proc;
240
241 // pre-fetched root object
242 sp<IBinder> rootBinder;
243
244 // pre-casted root object
245 sp<IBinderRpcTest> rootIface;
246
247 ~BinderRpcTestProcessConnection() {
248 if (!proc.expectInvalid) {
249 int32_t remoteBinders = 0;
250 EXPECT_OK(rootIface->countBinders(&remoteBinders));
251 // should only be the root binder object, iface
252 EXPECT_EQ(remoteBinders, 1);
253 }
254
255 rootIface = nullptr;
256 rootBinder = nullptr;
257 }
258};
259
Steven Morelandc1635952021-04-01 16:20:47 +0000260enum class SocketType {
261 UNIX,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000262#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000263 VSOCK,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000264#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000265};
266static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
267 switch (info.param) {
268 case SocketType::UNIX:
269 return "unix_domain_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000270#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000271 case SocketType::VSOCK:
272 return "vm_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000273#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000274 default:
275 LOG_ALWAYS_FATAL("Unknown socket type");
276 return "";
277 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000278}
Steven Morelandc1635952021-04-01 16:20:47 +0000279class BinderRpc : public ::testing::TestWithParam<SocketType> {
280public:
281 // This creates a new process serving an interface on a certain number of
282 // threads.
283 ProcessConnection createRpcTestSocketServerProcess(
284 size_t numThreads,
285 const std::function<void(const sp<RpcServer>&, const sp<RpcConnection>&)>& configure) {
286 CHECK_GT(numThreads, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000287
Steven Morelandc1635952021-04-01 16:20:47 +0000288 SocketType socketType = GetParam();
289
290 std::string addr = allocateSocketAddress();
291 unlink(addr.c_str());
292 static unsigned int port = 3456;
293 port++;
294
295 auto ret = ProcessConnection{
296 .host = Process([&] {
297 sp<RpcServer> server = RpcServer::make();
298
299 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
300
301 // server supporting one client on one socket
302 sp<RpcConnection> connection = server->addClientConnection();
303
304 switch (socketType) {
305 case SocketType::UNIX:
306 CHECK(connection->setupUnixDomainServer(addr.c_str())) << addr;
307 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000308#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000309 case SocketType::VSOCK:
310 CHECK(connection->setupVsockServer(port));
311 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000312#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000313 default:
314 LOG_ALWAYS_FATAL("Unknown socket type");
315 }
316
317 configure(server, connection);
318
319 // accept 'numThreads' connections
320 std::vector<std::thread> pool;
321 for (size_t i = 0; i + 1 < numThreads; i++) {
322 pool.push_back(std::thread([=] { connection->join(); }));
323 }
324 connection->join();
325 for (auto& t : pool) t.join();
326 }),
327 .connection = RpcConnection::make(),
328 };
329
330 // create remainder of connections
331 for (size_t i = 0; i < numThreads; i++) {
332 for (size_t tries = 0; tries < 5; tries++) {
333 usleep(10000);
334 switch (socketType) {
335 case SocketType::UNIX:
336 if (ret.connection->addUnixDomainClient(addr.c_str())) goto success;
337 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000338#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000339 case SocketType::VSOCK:
340 if (ret.connection->addVsockClient(VMADDR_CID_LOCAL, port)) goto success;
341 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000342#endif // __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000343 default:
344 LOG_ALWAYS_FATAL("Unknown socket type");
345 }
346 }
347 LOG_ALWAYS_FATAL("Could not connect");
348 success:;
349 }
350
351 ret.rootBinder = ret.connection->getRootObject();
352 return ret;
353 }
354
355 BinderRpcTestProcessConnection createRpcTestSocketServerProcess(size_t numThreads) {
356 BinderRpcTestProcessConnection ret{
357 .proc = createRpcTestSocketServerProcess(numThreads,
358 [&](const sp<RpcServer>& server,
359 const sp<RpcConnection>& connection) {
360 sp<MyBinderRpcTest> service =
361 new MyBinderRpcTest;
362 server->setRootObject(service);
363 service->connection =
364 connection; // for testing only
365 }),
366 };
367
368 ret.rootBinder = ret.proc.rootBinder;
369 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
370
371 return ret;
372 }
373};
374
375TEST_P(BinderRpc, RootObjectIsNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000376 auto proc = createRpcTestSocketServerProcess(1,
377 [](const sp<RpcServer>& server,
378 const sp<RpcConnection>&) {
379 // this is the default, but to be explicit
380 server->setRootObject(nullptr);
381 });
382
383 // retrieved by getRootObject when process is created above
384 EXPECT_EQ(nullptr, proc.rootBinder);
385
386 // make sure we can retrieve it again (process doesn't crash)
387 EXPECT_EQ(nullptr, proc.connection->getRootObject());
388}
389
Steven Morelandc1635952021-04-01 16:20:47 +0000390TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000391 auto proc = createRpcTestSocketServerProcess(1);
392 ASSERT_NE(proc.rootBinder, nullptr);
393 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
394}
395
Steven Moreland4cf688f2021-03-31 01:48:58 +0000396TEST_P(BinderRpc, GetInterfaceDescriptor) {
397 auto proc = createRpcTestSocketServerProcess(1);
398 ASSERT_NE(proc.rootBinder, nullptr);
399 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
400}
401
Steven Morelandc1635952021-04-01 16:20:47 +0000402TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000403 auto proc = createRpcTestSocketServerProcess(1);
404 Parcel data;
405 Parcel reply;
406 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
407}
408
Steven Morelandc1635952021-04-01 16:20:47 +0000409TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000410 auto proc = createRpcTestSocketServerProcess(1);
411 Parcel data;
412 data.markForBinder(proc.rootBinder);
413 Parcel reply;
414 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
415}
416
Steven Morelandc1635952021-04-01 16:20:47 +0000417TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000418 auto proc = createRpcTestSocketServerProcess(1);
419 EXPECT_OK(proc.rootIface->sendString("asdf"));
420}
421
Steven Morelandc1635952021-04-01 16:20:47 +0000422TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000423 auto proc = createRpcTestSocketServerProcess(1);
424 std::string doubled;
425 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
426 EXPECT_EQ("cool cool ", doubled);
427}
428
Steven Morelandc1635952021-04-01 16:20:47 +0000429TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000430 auto proc = createRpcTestSocketServerProcess(1);
431 std::string single = std::string(1024, 'a');
432 std::string doubled;
433 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
434 EXPECT_EQ(single + single, doubled);
435}
436
Steven Morelandc1635952021-04-01 16:20:47 +0000437TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000438 auto proc = createRpcTestSocketServerProcess(1);
439
440 int32_t pingResult;
441 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
442 EXPECT_EQ(OK, pingResult);
443
444 EXPECT_EQ(0, MyBinderRpcSession::gNum);
445}
446
Steven Morelandc1635952021-04-01 16:20:47 +0000447TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000448 auto proc = createRpcTestSocketServerProcess(1);
449
450 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
451 sp<IBinder> outBinder;
452 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
453 EXPECT_EQ(inBinder, outBinder);
454
455 wp<IBinder> weak = inBinder;
456 inBinder = nullptr;
457 outBinder = nullptr;
458
459 // Force reading a reply, to process any pending dec refs from the other
460 // process (the other process will process dec refs there before processing
461 // the ping here).
462 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
463
464 EXPECT_EQ(nullptr, weak.promote());
465
466 EXPECT_EQ(0, MyBinderRpcSession::gNum);
467}
468
Steven Morelandc1635952021-04-01 16:20:47 +0000469TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000470 auto proc = createRpcTestSocketServerProcess(1);
471
472 sp<IBinderRpcSession> session;
473 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
474
475 sp<IBinder> inBinder = IInterface::asBinder(session);
476 sp<IBinder> outBinder;
477 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
478 EXPECT_EQ(inBinder, outBinder);
479
480 wp<IBinder> weak = inBinder;
481 session = nullptr;
482 inBinder = nullptr;
483 outBinder = nullptr;
484
485 // Force reading a reply, to process any pending dec refs from the other
486 // process (the other process will process dec refs there before processing
487 // the ping here).
488 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
489
490 EXPECT_EQ(nullptr, weak.promote());
491}
492
Steven Morelandc1635952021-04-01 16:20:47 +0000493TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000494 auto proc = createRpcTestSocketServerProcess(1);
495
496 sp<IBinder> outBinder;
497 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
498 EXPECT_EQ(nullptr, outBinder);
499}
500
Steven Morelandc1635952021-04-01 16:20:47 +0000501TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000502 auto proc = createRpcTestSocketServerProcess(1);
503
504 IBinder* ptr = nullptr;
505 {
506 sp<IBinder> binder = new BBinder();
507 ptr = binder.get();
508 EXPECT_OK(proc.rootIface->holdBinder(binder));
509 }
510
511 sp<IBinder> held;
512 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
513
514 EXPECT_EQ(held.get(), ptr);
515
516 // stop holding binder, because we test to make sure references are cleaned
517 // up
518 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
519 // and flush ref counts
520 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
521}
522
523// START TESTS FOR LIMITATIONS OF SOCKET BINDER
524// These are behavioral differences form regular binder, where certain usecases
525// aren't supported.
526
Steven Morelandc1635952021-04-01 16:20:47 +0000527TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketConnections) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000528 auto proc1 = createRpcTestSocketServerProcess(1);
529 auto proc2 = createRpcTestSocketServerProcess(1);
530
531 sp<IBinder> outBinder;
532 EXPECT_EQ(INVALID_OPERATION,
533 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
534}
535
Steven Morelandc1635952021-04-01 16:20:47 +0000536TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000537 auto proc = createRpcTestSocketServerProcess(1);
538
539 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
540 sp<IBinder> outBinder;
541 EXPECT_EQ(INVALID_OPERATION,
542 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
543}
544
Steven Morelandc1635952021-04-01 16:20:47 +0000545TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000546 auto proc = createRpcTestSocketServerProcess(1);
547
548 // for historical reasons, IServiceManager interface only returns the
549 // exception code
550 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
551 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
552}
553
554// END TESTS FOR LIMITATIONS OF SOCKET BINDER
555
Steven Morelandc1635952021-04-01 16:20:47 +0000556TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000557 auto proc = createRpcTestSocketServerProcess(1);
558
559 sp<IBinder> outBinder;
560 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
561 EXPECT_EQ(proc.rootBinder, outBinder);
562}
563
Steven Morelandc1635952021-04-01 16:20:47 +0000564TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000565 auto proc = createRpcTestSocketServerProcess(1);
566
567 auto nastyNester = sp<MyBinderRpcTest>::make();
568 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
569
570 wp<IBinder> weak = nastyNester;
571 nastyNester = nullptr;
572 EXPECT_EQ(nullptr, weak.promote());
573}
574
Steven Morelandc1635952021-04-01 16:20:47 +0000575TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000576 auto proc = createRpcTestSocketServerProcess(1);
577
578 sp<IBinder> a;
579 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
580
581 sp<IBinder> b;
582 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
583
584 EXPECT_EQ(a, b);
585}
586
Steven Morelandc1635952021-04-01 16:20:47 +0000587TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000588 auto proc = createRpcTestSocketServerProcess(1);
589
590 sp<IBinder> a;
591 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
592 wp<IBinder> weak = a;
593 a = nullptr;
594
595 sp<IBinder> b;
596 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
597
598 // this is the wrong behavior, since BpBinder
599 // doesn't implement onIncStrongAttempted
600 // but make sure there is no crash
601 EXPECT_EQ(nullptr, weak.promote());
602
603 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
604
605 // In order to fix this:
606 // - need to have incStrongAttempted reflected across IPC boundary (wait for
607 // response to promote - round trip...)
608 // - sendOnLastWeakRef, to delete entries out of RpcState table
609 EXPECT_EQ(b, weak.promote());
610}
611
612#define expectSessions(expected, iface) \
613 do { \
614 int session; \
615 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
616 EXPECT_EQ(expected, session); \
617 } while (false)
618
Steven Morelandc1635952021-04-01 16:20:47 +0000619TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000620 auto proc = createRpcTestSocketServerProcess(1);
621
622 sp<IBinderRpcSession> session;
623 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
624 std::string out;
625 EXPECT_OK(session->getName(&out));
626 EXPECT_EQ("aoeu", out);
627
628 expectSessions(1, proc.rootIface);
629 session = nullptr;
630 expectSessions(0, proc.rootIface);
631}
632
Steven Morelandc1635952021-04-01 16:20:47 +0000633TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000634 auto proc = createRpcTestSocketServerProcess(1);
635
636 std::vector<sp<IBinderRpcSession>> sessions;
637
638 for (size_t i = 0; i < 15; i++) {
639 expectSessions(i, proc.rootIface);
640 sp<IBinderRpcSession> session;
641 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
642 sessions.push_back(session);
643 }
644 expectSessions(sessions.size(), proc.rootIface);
645 for (size_t i = 0; i < sessions.size(); i++) {
646 std::string out;
647 EXPECT_OK(sessions.at(i)->getName(&out));
648 EXPECT_EQ(std::to_string(i), out);
649 }
650 expectSessions(sessions.size(), proc.rootIface);
651
652 while (!sessions.empty()) {
653 sessions.pop_back();
654 expectSessions(sessions.size(), proc.rootIface);
655 }
656 expectSessions(0, proc.rootIface);
657}
658
659size_t epochMillis() {
660 using std::chrono::duration_cast;
661 using std::chrono::milliseconds;
662 using std::chrono::seconds;
663 using std::chrono::system_clock;
664 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
665}
666
Steven Morelandc1635952021-04-01 16:20:47 +0000667TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000668 constexpr size_t kNumThreads = 10;
669
670 auto proc = createRpcTestSocketServerProcess(kNumThreads);
671
672 EXPECT_OK(proc.rootIface->lock());
673
674 // block all but one thread taking locks
675 std::vector<std::thread> ts;
676 for (size_t i = 0; i < kNumThreads - 1; i++) {
677 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
678 }
679
680 usleep(100000); // give chance for calls on other threads
681
682 // other calls still work
683 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
684
685 constexpr size_t blockTimeMs = 500;
686 size_t epochMsBefore = epochMillis();
687 // after this, we should never see a response within this time
688 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
689
690 // this call should be blocked for blockTimeMs
691 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
692
693 size_t epochMsAfter = epochMillis();
694 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
695
696 for (auto& t : ts) t.join();
697}
698
Steven Morelandc1635952021-04-01 16:20:47 +0000699TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000700 constexpr size_t kNumThreads = 10;
701 constexpr size_t kNumCalls = kNumThreads + 3;
702 constexpr size_t kSleepMs = 500;
703
704 auto proc = createRpcTestSocketServerProcess(kNumThreads);
705
706 size_t epochMsBefore = epochMillis();
707
708 std::vector<std::thread> ts;
709 for (size_t i = 0; i < kNumCalls; i++) {
710 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
711 }
712
713 for (auto& t : ts) t.join();
714
715 size_t epochMsAfter = epochMillis();
716
717 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
718
719 // Potential flake, but make sure calls are handled in parallel.
720 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
721}
722
Steven Morelandc1635952021-04-01 16:20:47 +0000723TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000724 constexpr size_t kNumClientThreads = 10;
725 constexpr size_t kNumServerThreads = 10;
726 constexpr size_t kNumCalls = 100;
727
728 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
729
730 std::vector<std::thread> threads;
731 for (size_t i = 0; i < kNumClientThreads; i++) {
732 threads.push_back(std::thread([&] {
733 for (size_t j = 0; j < kNumCalls; j++) {
734 sp<IBinder> out;
735 proc.rootIface->repeatBinder(proc.rootBinder, &out);
736 EXPECT_EQ(proc.rootBinder, out);
737 }
738 }));
739 }
740
741 for (auto& t : threads) t.join();
742}
743
Steven Morelandc1635952021-04-01 16:20:47 +0000744TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000745 constexpr size_t kReallyLongTimeMs = 100;
746 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
747
748 // more than one thread, just so this doesn't deadlock
749 auto proc = createRpcTestSocketServerProcess(2);
750
751 size_t epochMsBefore = epochMillis();
752
753 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
754
755 size_t epochMsAfter = epochMillis();
756 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
757}
758
Steven Morelandc1635952021-04-01 16:20:47 +0000759TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000760 constexpr size_t kNumSleeps = 10;
761 constexpr size_t kNumExtraServerThreads = 4;
762 constexpr size_t kSleepMs = 50;
763
764 // make sure calls to the same object happen on the same thread
765 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
766
767 EXPECT_OK(proc.rootIface->lock());
768
769 for (size_t i = 0; i < kNumSleeps; i++) {
770 // these should be processed serially
771 proc.rootIface->sleepMsAsync(kSleepMs);
772 }
773 // should also be processesed serially
774 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
775
776 size_t epochMsBefore = epochMillis();
777 EXPECT_OK(proc.rootIface->lockUnlock());
778 size_t epochMsAfter = epochMillis();
779
780 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
781}
782
Steven Morelandc1635952021-04-01 16:20:47 +0000783TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000784 for (bool doDeathCleanup : {true, false}) {
785 auto proc = createRpcTestSocketServerProcess(1);
786
787 // make sure there is some state during crash
788 // 1. we hold their binder
789 sp<IBinderRpcSession> session;
790 EXPECT_OK(proc.rootIface->openSession("happy", &session));
791 // 2. they hold our binder
792 sp<IBinder> binder = new BBinder();
793 EXPECT_OK(proc.rootIface->holdBinder(binder));
794
795 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
796 << "Do death cleanup: " << doDeathCleanup;
797
798 proc.proc.expectInvalid = true;
799 }
800}
801
Steven Moreland37aff182021-03-26 02:04:16 +0000802TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
803 auto proc = createRpcTestSocketServerProcess(1);
804
805 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
806 ASSERT_NE(binder, nullptr);
807
808 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
809}
810
811TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
812 auto proc = createRpcTestSocketServerProcess(1);
813
814 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
815 ASSERT_NE(binder, nullptr);
816
817 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
818 ASSERT_NE(ndkBinder, nullptr);
819
820 std::string out;
821 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
822 ASSERT_TRUE(status.isOk()) << status.getDescription();
823 ASSERT_EQ("aoeuaoeu", out);
824}
825
Steven Moreland5553ac42020-11-11 02:14:45 +0000826ssize_t countFds() {
827 DIR* dir = opendir("/proc/self/fd/");
828 if (dir == nullptr) return -1;
829 ssize_t ret = 0;
830 dirent* ent;
831 while ((ent = readdir(dir)) != nullptr) ret++;
832 closedir(dir);
833 return ret;
834}
835
Steven Morelandc1635952021-04-01 16:20:47 +0000836TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000837 ssize_t beforeFds = countFds();
838 ASSERT_GE(beforeFds, 0);
839 {
840 auto proc = createRpcTestSocketServerProcess(10);
841 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
842 }
843 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
844}
845
Steven Morelandc1635952021-04-01 16:20:47 +0000846INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000847 ::testing::Values(SocketType::UNIX
848#ifdef __BIONIC__
849 ,
850 SocketType::VSOCK
851#endif // __BIONIC__
852 ),
853 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +0000854
855} // namespace android
856
857int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000858 ::testing::InitGoogleTest(&argc, argv);
859 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
860 return RUN_ALL_TESTS();
861}