blob: a51c98774e5b8596650611ad458c3d9e7006f852 [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 Moreland67753c32021-04-02 18:45:19 +0000409TEST_P(BinderRpc, AppendSeparateFormats) {
410 auto proc = createRpcTestSocketServerProcess(1);
411
412 Parcel p1;
413 p1.markForBinder(proc.rootBinder);
414 p1.writeInt32(3);
415
416 Parcel p2;
417
418 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
419 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
420}
421
Steven Morelandc1635952021-04-01 16:20:47 +0000422TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000423 auto proc = createRpcTestSocketServerProcess(1);
424 Parcel data;
425 data.markForBinder(proc.rootBinder);
426 Parcel reply;
427 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
428}
429
Steven Morelandc1635952021-04-01 16:20:47 +0000430TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000431 auto proc = createRpcTestSocketServerProcess(1);
432 EXPECT_OK(proc.rootIface->sendString("asdf"));
433}
434
Steven Morelandc1635952021-04-01 16:20:47 +0000435TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000436 auto proc = createRpcTestSocketServerProcess(1);
437 std::string doubled;
438 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
439 EXPECT_EQ("cool cool ", doubled);
440}
441
Steven Morelandc1635952021-04-01 16:20:47 +0000442TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000443 auto proc = createRpcTestSocketServerProcess(1);
444 std::string single = std::string(1024, 'a');
445 std::string doubled;
446 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
447 EXPECT_EQ(single + single, doubled);
448}
449
Steven Morelandc1635952021-04-01 16:20:47 +0000450TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000451 auto proc = createRpcTestSocketServerProcess(1);
452
453 int32_t pingResult;
454 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
455 EXPECT_EQ(OK, pingResult);
456
457 EXPECT_EQ(0, MyBinderRpcSession::gNum);
458}
459
Steven Morelandc1635952021-04-01 16:20:47 +0000460TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000461 auto proc = createRpcTestSocketServerProcess(1);
462
463 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
464 sp<IBinder> outBinder;
465 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
466 EXPECT_EQ(inBinder, outBinder);
467
468 wp<IBinder> weak = inBinder;
469 inBinder = nullptr;
470 outBinder = nullptr;
471
472 // Force reading a reply, to process any pending dec refs from the other
473 // process (the other process will process dec refs there before processing
474 // the ping here).
475 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
476
477 EXPECT_EQ(nullptr, weak.promote());
478
479 EXPECT_EQ(0, MyBinderRpcSession::gNum);
480}
481
Steven Morelandc1635952021-04-01 16:20:47 +0000482TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000483 auto proc = createRpcTestSocketServerProcess(1);
484
485 sp<IBinderRpcSession> session;
486 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
487
488 sp<IBinder> inBinder = IInterface::asBinder(session);
489 sp<IBinder> outBinder;
490 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
491 EXPECT_EQ(inBinder, outBinder);
492
493 wp<IBinder> weak = inBinder;
494 session = nullptr;
495 inBinder = nullptr;
496 outBinder = nullptr;
497
498 // Force reading a reply, to process any pending dec refs from the other
499 // process (the other process will process dec refs there before processing
500 // the ping here).
501 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
502
503 EXPECT_EQ(nullptr, weak.promote());
504}
505
Steven Morelandc1635952021-04-01 16:20:47 +0000506TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000507 auto proc = createRpcTestSocketServerProcess(1);
508
509 sp<IBinder> outBinder;
510 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
511 EXPECT_EQ(nullptr, outBinder);
512}
513
Steven Morelandc1635952021-04-01 16:20:47 +0000514TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000515 auto proc = createRpcTestSocketServerProcess(1);
516
517 IBinder* ptr = nullptr;
518 {
519 sp<IBinder> binder = new BBinder();
520 ptr = binder.get();
521 EXPECT_OK(proc.rootIface->holdBinder(binder));
522 }
523
524 sp<IBinder> held;
525 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
526
527 EXPECT_EQ(held.get(), ptr);
528
529 // stop holding binder, because we test to make sure references are cleaned
530 // up
531 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
532 // and flush ref counts
533 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
534}
535
536// START TESTS FOR LIMITATIONS OF SOCKET BINDER
537// These are behavioral differences form regular binder, where certain usecases
538// aren't supported.
539
Steven Morelandc1635952021-04-01 16:20:47 +0000540TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketConnections) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000541 auto proc1 = createRpcTestSocketServerProcess(1);
542 auto proc2 = createRpcTestSocketServerProcess(1);
543
544 sp<IBinder> outBinder;
545 EXPECT_EQ(INVALID_OPERATION,
546 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
547}
548
Steven Morelandc1635952021-04-01 16:20:47 +0000549TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000550 auto proc = createRpcTestSocketServerProcess(1);
551
552 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
553 sp<IBinder> outBinder;
554 EXPECT_EQ(INVALID_OPERATION,
555 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
556}
557
Steven Morelandc1635952021-04-01 16:20:47 +0000558TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000559 auto proc = createRpcTestSocketServerProcess(1);
560
561 // for historical reasons, IServiceManager interface only returns the
562 // exception code
563 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
564 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
565}
566
567// END TESTS FOR LIMITATIONS OF SOCKET BINDER
568
Steven Morelandc1635952021-04-01 16:20:47 +0000569TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000570 auto proc = createRpcTestSocketServerProcess(1);
571
572 sp<IBinder> outBinder;
573 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
574 EXPECT_EQ(proc.rootBinder, outBinder);
575}
576
Steven Morelandc1635952021-04-01 16:20:47 +0000577TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000578 auto proc = createRpcTestSocketServerProcess(1);
579
580 auto nastyNester = sp<MyBinderRpcTest>::make();
581 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
582
583 wp<IBinder> weak = nastyNester;
584 nastyNester = nullptr;
585 EXPECT_EQ(nullptr, weak.promote());
586}
587
Steven Morelandc1635952021-04-01 16:20:47 +0000588TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000589 auto proc = createRpcTestSocketServerProcess(1);
590
591 sp<IBinder> a;
592 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
593
594 sp<IBinder> b;
595 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
596
597 EXPECT_EQ(a, b);
598}
599
Steven Morelandc1635952021-04-01 16:20:47 +0000600TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000601 auto proc = createRpcTestSocketServerProcess(1);
602
603 sp<IBinder> a;
604 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
605 wp<IBinder> weak = a;
606 a = nullptr;
607
608 sp<IBinder> b;
609 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
610
611 // this is the wrong behavior, since BpBinder
612 // doesn't implement onIncStrongAttempted
613 // but make sure there is no crash
614 EXPECT_EQ(nullptr, weak.promote());
615
616 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
617
618 // In order to fix this:
619 // - need to have incStrongAttempted reflected across IPC boundary (wait for
620 // response to promote - round trip...)
621 // - sendOnLastWeakRef, to delete entries out of RpcState table
622 EXPECT_EQ(b, weak.promote());
623}
624
625#define expectSessions(expected, iface) \
626 do { \
627 int session; \
628 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
629 EXPECT_EQ(expected, session); \
630 } while (false)
631
Steven Morelandc1635952021-04-01 16:20:47 +0000632TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000633 auto proc = createRpcTestSocketServerProcess(1);
634
635 sp<IBinderRpcSession> session;
636 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
637 std::string out;
638 EXPECT_OK(session->getName(&out));
639 EXPECT_EQ("aoeu", out);
640
641 expectSessions(1, proc.rootIface);
642 session = nullptr;
643 expectSessions(0, proc.rootIface);
644}
645
Steven Morelandc1635952021-04-01 16:20:47 +0000646TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000647 auto proc = createRpcTestSocketServerProcess(1);
648
649 std::vector<sp<IBinderRpcSession>> sessions;
650
651 for (size_t i = 0; i < 15; i++) {
652 expectSessions(i, proc.rootIface);
653 sp<IBinderRpcSession> session;
654 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
655 sessions.push_back(session);
656 }
657 expectSessions(sessions.size(), proc.rootIface);
658 for (size_t i = 0; i < sessions.size(); i++) {
659 std::string out;
660 EXPECT_OK(sessions.at(i)->getName(&out));
661 EXPECT_EQ(std::to_string(i), out);
662 }
663 expectSessions(sessions.size(), proc.rootIface);
664
665 while (!sessions.empty()) {
666 sessions.pop_back();
667 expectSessions(sessions.size(), proc.rootIface);
668 }
669 expectSessions(0, proc.rootIface);
670}
671
672size_t epochMillis() {
673 using std::chrono::duration_cast;
674 using std::chrono::milliseconds;
675 using std::chrono::seconds;
676 using std::chrono::system_clock;
677 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
678}
679
Steven Morelandc1635952021-04-01 16:20:47 +0000680TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000681 constexpr size_t kNumThreads = 10;
682
683 auto proc = createRpcTestSocketServerProcess(kNumThreads);
684
685 EXPECT_OK(proc.rootIface->lock());
686
687 // block all but one thread taking locks
688 std::vector<std::thread> ts;
689 for (size_t i = 0; i < kNumThreads - 1; i++) {
690 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
691 }
692
693 usleep(100000); // give chance for calls on other threads
694
695 // other calls still work
696 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
697
698 constexpr size_t blockTimeMs = 500;
699 size_t epochMsBefore = epochMillis();
700 // after this, we should never see a response within this time
701 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
702
703 // this call should be blocked for blockTimeMs
704 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
705
706 size_t epochMsAfter = epochMillis();
707 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
708
709 for (auto& t : ts) t.join();
710}
711
Steven Morelandc1635952021-04-01 16:20:47 +0000712TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000713 constexpr size_t kNumThreads = 10;
714 constexpr size_t kNumCalls = kNumThreads + 3;
715 constexpr size_t kSleepMs = 500;
716
717 auto proc = createRpcTestSocketServerProcess(kNumThreads);
718
719 size_t epochMsBefore = epochMillis();
720
721 std::vector<std::thread> ts;
722 for (size_t i = 0; i < kNumCalls; i++) {
723 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
724 }
725
726 for (auto& t : ts) t.join();
727
728 size_t epochMsAfter = epochMillis();
729
730 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
731
732 // Potential flake, but make sure calls are handled in parallel.
733 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
734}
735
Steven Morelandc1635952021-04-01 16:20:47 +0000736TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000737 constexpr size_t kNumClientThreads = 10;
738 constexpr size_t kNumServerThreads = 10;
739 constexpr size_t kNumCalls = 100;
740
741 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
742
743 std::vector<std::thread> threads;
744 for (size_t i = 0; i < kNumClientThreads; i++) {
745 threads.push_back(std::thread([&] {
746 for (size_t j = 0; j < kNumCalls; j++) {
747 sp<IBinder> out;
748 proc.rootIface->repeatBinder(proc.rootBinder, &out);
749 EXPECT_EQ(proc.rootBinder, out);
750 }
751 }));
752 }
753
754 for (auto& t : threads) t.join();
755}
756
Steven Morelandc1635952021-04-01 16:20:47 +0000757TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000758 constexpr size_t kReallyLongTimeMs = 100;
759 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
760
761 // more than one thread, just so this doesn't deadlock
762 auto proc = createRpcTestSocketServerProcess(2);
763
764 size_t epochMsBefore = epochMillis();
765
766 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
767
768 size_t epochMsAfter = epochMillis();
769 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
770}
771
Steven Morelandc1635952021-04-01 16:20:47 +0000772TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000773 constexpr size_t kNumSleeps = 10;
774 constexpr size_t kNumExtraServerThreads = 4;
775 constexpr size_t kSleepMs = 50;
776
777 // make sure calls to the same object happen on the same thread
778 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
779
780 EXPECT_OK(proc.rootIface->lock());
781
782 for (size_t i = 0; i < kNumSleeps; i++) {
783 // these should be processed serially
784 proc.rootIface->sleepMsAsync(kSleepMs);
785 }
786 // should also be processesed serially
787 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
788
789 size_t epochMsBefore = epochMillis();
790 EXPECT_OK(proc.rootIface->lockUnlock());
791 size_t epochMsAfter = epochMillis();
792
793 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
794}
795
Steven Morelandc1635952021-04-01 16:20:47 +0000796TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000797 for (bool doDeathCleanup : {true, false}) {
798 auto proc = createRpcTestSocketServerProcess(1);
799
800 // make sure there is some state during crash
801 // 1. we hold their binder
802 sp<IBinderRpcSession> session;
803 EXPECT_OK(proc.rootIface->openSession("happy", &session));
804 // 2. they hold our binder
805 sp<IBinder> binder = new BBinder();
806 EXPECT_OK(proc.rootIface->holdBinder(binder));
807
808 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
809 << "Do death cleanup: " << doDeathCleanup;
810
811 proc.proc.expectInvalid = true;
812 }
813}
814
Steven Moreland37aff182021-03-26 02:04:16 +0000815TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
816 auto proc = createRpcTestSocketServerProcess(1);
817
818 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
819 ASSERT_NE(binder, nullptr);
820
821 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
822}
823
824TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
825 auto proc = createRpcTestSocketServerProcess(1);
826
827 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
828 ASSERT_NE(binder, nullptr);
829
830 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
831 ASSERT_NE(ndkBinder, nullptr);
832
833 std::string out;
834 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
835 ASSERT_TRUE(status.isOk()) << status.getDescription();
836 ASSERT_EQ("aoeuaoeu", out);
837}
838
Steven Moreland5553ac42020-11-11 02:14:45 +0000839ssize_t countFds() {
840 DIR* dir = opendir("/proc/self/fd/");
841 if (dir == nullptr) return -1;
842 ssize_t ret = 0;
843 dirent* ent;
844 while ((ent = readdir(dir)) != nullptr) ret++;
845 closedir(dir);
846 return ret;
847}
848
Steven Morelandc1635952021-04-01 16:20:47 +0000849TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000850 ssize_t beforeFds = countFds();
851 ASSERT_GE(beforeFds, 0);
852 {
853 auto proc = createRpcTestSocketServerProcess(10);
854 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
855 }
856 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
857}
858
Steven Morelandc1635952021-04-01 16:20:47 +0000859INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000860 ::testing::Values(SocketType::UNIX
861#ifdef __BIONIC__
862 ,
863 SocketType::VSOCK
864#endif // __BIONIC__
865 ),
866 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +0000867
868} // namespace android
869
870int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000871 ::testing::InitGoogleTest(&argc, argv);
872 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
873 return RUN_ALL_TESTS();
874}