blob: ec4ced299b91f2d24ea5f765cb6c9717626babec [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__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700260 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000261};
262static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
263 switch (info.param) {
264 case SocketType::UNIX:
265 return "unix_domain_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000266#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000267 case SocketType::VSOCK:
268 return "vm_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000269#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700270 case SocketType::INET:
271 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000272 default:
273 LOG_ALWAYS_FATAL("Unknown socket type");
274 return "";
275 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000276}
Steven Morelandc1635952021-04-01 16:20:47 +0000277class BinderRpc : public ::testing::TestWithParam<SocketType> {
278public:
279 // This creates a new process serving an interface on a certain number of
280 // threads.
281 ProcessConnection createRpcTestSocketServerProcess(
282 size_t numThreads,
283 const std::function<void(const sp<RpcServer>&, const sp<RpcConnection>&)>& configure) {
284 CHECK_GT(numThreads, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000285
Steven Morelandc1635952021-04-01 16:20:47 +0000286 SocketType socketType = GetParam();
287
288 std::string addr = allocateSocketAddress();
289 unlink(addr.c_str());
290 static unsigned int port = 3456;
291 port++;
292
293 auto ret = ProcessConnection{
294 .host = Process([&] {
295 sp<RpcServer> server = RpcServer::make();
296
297 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
298
299 // server supporting one client on one socket
300 sp<RpcConnection> connection = server->addClientConnection();
301
302 switch (socketType) {
303 case SocketType::UNIX:
304 CHECK(connection->setupUnixDomainServer(addr.c_str())) << addr;
305 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000306#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000307 case SocketType::VSOCK:
308 CHECK(connection->setupVsockServer(port));
309 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000310#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700311 case SocketType::INET:
312 CHECK(connection->setupInetServer(port));
313 break;
Steven Morelandc1635952021-04-01 16:20:47 +0000314 default:
315 LOG_ALWAYS_FATAL("Unknown socket type");
316 }
317
318 configure(server, connection);
319
320 // accept 'numThreads' connections
321 std::vector<std::thread> pool;
322 for (size_t i = 0; i + 1 < numThreads; i++) {
323 pool.push_back(std::thread([=] { connection->join(); }));
324 }
325 connection->join();
326 for (auto& t : pool) t.join();
327 }),
328 .connection = RpcConnection::make(),
329 };
330
331 // create remainder of connections
332 for (size_t i = 0; i < numThreads; i++) {
333 for (size_t tries = 0; tries < 5; tries++) {
334 usleep(10000);
335 switch (socketType) {
336 case SocketType::UNIX:
337 if (ret.connection->addUnixDomainClient(addr.c_str())) goto success;
338 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000339#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000340 case SocketType::VSOCK:
341 if (ret.connection->addVsockClient(VMADDR_CID_LOCAL, port)) goto success;
342 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000343#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700344 case SocketType::INET:
345 if (ret.connection->addInetClient("127.0.0.1", port)) goto success;
346 break;
Steven Morelandc1635952021-04-01 16:20:47 +0000347 default:
348 LOG_ALWAYS_FATAL("Unknown socket type");
349 }
350 }
351 LOG_ALWAYS_FATAL("Could not connect");
352 success:;
353 }
354
355 ret.rootBinder = ret.connection->getRootObject();
356 return ret;
357 }
358
359 BinderRpcTestProcessConnection createRpcTestSocketServerProcess(size_t numThreads) {
360 BinderRpcTestProcessConnection ret{
361 .proc = createRpcTestSocketServerProcess(numThreads,
362 [&](const sp<RpcServer>& server,
363 const sp<RpcConnection>& connection) {
364 sp<MyBinderRpcTest> service =
365 new MyBinderRpcTest;
366 server->setRootObject(service);
367 service->connection =
368 connection; // for testing only
369 }),
370 };
371
372 ret.rootBinder = ret.proc.rootBinder;
373 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
374
375 return ret;
376 }
377};
378
379TEST_P(BinderRpc, RootObjectIsNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000380 auto proc = createRpcTestSocketServerProcess(1,
381 [](const sp<RpcServer>& server,
382 const sp<RpcConnection>&) {
383 // this is the default, but to be explicit
384 server->setRootObject(nullptr);
385 });
386
387 // retrieved by getRootObject when process is created above
388 EXPECT_EQ(nullptr, proc.rootBinder);
389
390 // make sure we can retrieve it again (process doesn't crash)
391 EXPECT_EQ(nullptr, proc.connection->getRootObject());
392}
393
Steven Morelandc1635952021-04-01 16:20:47 +0000394TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000395 auto proc = createRpcTestSocketServerProcess(1);
396 ASSERT_NE(proc.rootBinder, nullptr);
397 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
398}
399
Steven Moreland4cf688f2021-03-31 01:48:58 +0000400TEST_P(BinderRpc, GetInterfaceDescriptor) {
401 auto proc = createRpcTestSocketServerProcess(1);
402 ASSERT_NE(proc.rootBinder, nullptr);
403 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
404}
405
Steven Morelandc1635952021-04-01 16:20:47 +0000406TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000407 auto proc = createRpcTestSocketServerProcess(1);
408 Parcel data;
409 Parcel reply;
410 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
411}
412
Steven Moreland67753c32021-04-02 18:45:19 +0000413TEST_P(BinderRpc, AppendSeparateFormats) {
414 auto proc = createRpcTestSocketServerProcess(1);
415
416 Parcel p1;
417 p1.markForBinder(proc.rootBinder);
418 p1.writeInt32(3);
419
420 Parcel p2;
421
422 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
423 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
424}
425
Steven Morelandc1635952021-04-01 16:20:47 +0000426TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000427 auto proc = createRpcTestSocketServerProcess(1);
428 Parcel data;
429 data.markForBinder(proc.rootBinder);
430 Parcel reply;
431 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
432}
433
Steven Morelandc1635952021-04-01 16:20:47 +0000434TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000435 auto proc = createRpcTestSocketServerProcess(1);
436 EXPECT_OK(proc.rootIface->sendString("asdf"));
437}
438
Steven Morelandc1635952021-04-01 16:20:47 +0000439TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000440 auto proc = createRpcTestSocketServerProcess(1);
441 std::string doubled;
442 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
443 EXPECT_EQ("cool cool ", doubled);
444}
445
Steven Morelandc1635952021-04-01 16:20:47 +0000446TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000447 auto proc = createRpcTestSocketServerProcess(1);
448 std::string single = std::string(1024, 'a');
449 std::string doubled;
450 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
451 EXPECT_EQ(single + single, doubled);
452}
453
Steven Morelandc1635952021-04-01 16:20:47 +0000454TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000455 auto proc = createRpcTestSocketServerProcess(1);
456
457 int32_t pingResult;
458 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
459 EXPECT_EQ(OK, pingResult);
460
461 EXPECT_EQ(0, MyBinderRpcSession::gNum);
462}
463
Steven Morelandc1635952021-04-01 16:20:47 +0000464TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000465 auto proc = createRpcTestSocketServerProcess(1);
466
467 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
468 sp<IBinder> outBinder;
469 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
470 EXPECT_EQ(inBinder, outBinder);
471
472 wp<IBinder> weak = inBinder;
473 inBinder = nullptr;
474 outBinder = nullptr;
475
476 // Force reading a reply, to process any pending dec refs from the other
477 // process (the other process will process dec refs there before processing
478 // the ping here).
479 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
480
481 EXPECT_EQ(nullptr, weak.promote());
482
483 EXPECT_EQ(0, MyBinderRpcSession::gNum);
484}
485
Steven Morelandc1635952021-04-01 16:20:47 +0000486TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000487 auto proc = createRpcTestSocketServerProcess(1);
488
489 sp<IBinderRpcSession> session;
490 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
491
492 sp<IBinder> inBinder = IInterface::asBinder(session);
493 sp<IBinder> outBinder;
494 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
495 EXPECT_EQ(inBinder, outBinder);
496
497 wp<IBinder> weak = inBinder;
498 session = nullptr;
499 inBinder = nullptr;
500 outBinder = nullptr;
501
502 // Force reading a reply, to process any pending dec refs from the other
503 // process (the other process will process dec refs there before processing
504 // the ping here).
505 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
506
507 EXPECT_EQ(nullptr, weak.promote());
508}
509
Steven Morelandc1635952021-04-01 16:20:47 +0000510TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000511 auto proc = createRpcTestSocketServerProcess(1);
512
513 sp<IBinder> outBinder;
514 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
515 EXPECT_EQ(nullptr, outBinder);
516}
517
Steven Morelandc1635952021-04-01 16:20:47 +0000518TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000519 auto proc = createRpcTestSocketServerProcess(1);
520
521 IBinder* ptr = nullptr;
522 {
523 sp<IBinder> binder = new BBinder();
524 ptr = binder.get();
525 EXPECT_OK(proc.rootIface->holdBinder(binder));
526 }
527
528 sp<IBinder> held;
529 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
530
531 EXPECT_EQ(held.get(), ptr);
532
533 // stop holding binder, because we test to make sure references are cleaned
534 // up
535 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
536 // and flush ref counts
537 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
538}
539
540// START TESTS FOR LIMITATIONS OF SOCKET BINDER
541// These are behavioral differences form regular binder, where certain usecases
542// aren't supported.
543
Steven Morelandc1635952021-04-01 16:20:47 +0000544TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketConnections) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000545 auto proc1 = createRpcTestSocketServerProcess(1);
546 auto proc2 = createRpcTestSocketServerProcess(1);
547
548 sp<IBinder> outBinder;
549 EXPECT_EQ(INVALID_OPERATION,
550 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
551}
552
Steven Morelandc1635952021-04-01 16:20:47 +0000553TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000554 auto proc = createRpcTestSocketServerProcess(1);
555
556 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
557 sp<IBinder> outBinder;
558 EXPECT_EQ(INVALID_OPERATION,
559 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
560}
561
Steven Morelandc1635952021-04-01 16:20:47 +0000562TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000563 auto proc = createRpcTestSocketServerProcess(1);
564
565 // for historical reasons, IServiceManager interface only returns the
566 // exception code
567 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
568 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
569}
570
571// END TESTS FOR LIMITATIONS OF SOCKET BINDER
572
Steven Morelandc1635952021-04-01 16:20:47 +0000573TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000574 auto proc = createRpcTestSocketServerProcess(1);
575
576 sp<IBinder> outBinder;
577 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
578 EXPECT_EQ(proc.rootBinder, outBinder);
579}
580
Steven Morelandc1635952021-04-01 16:20:47 +0000581TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000582 auto proc = createRpcTestSocketServerProcess(1);
583
584 auto nastyNester = sp<MyBinderRpcTest>::make();
585 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
586
587 wp<IBinder> weak = nastyNester;
588 nastyNester = nullptr;
589 EXPECT_EQ(nullptr, weak.promote());
590}
591
Steven Morelandc1635952021-04-01 16:20:47 +0000592TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000593 auto proc = createRpcTestSocketServerProcess(1);
594
595 sp<IBinder> a;
596 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
597
598 sp<IBinder> b;
599 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
600
601 EXPECT_EQ(a, b);
602}
603
Steven Morelandc1635952021-04-01 16:20:47 +0000604TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000605 auto proc = createRpcTestSocketServerProcess(1);
606
607 sp<IBinder> a;
608 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
609 wp<IBinder> weak = a;
610 a = nullptr;
611
612 sp<IBinder> b;
613 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
614
615 // this is the wrong behavior, since BpBinder
616 // doesn't implement onIncStrongAttempted
617 // but make sure there is no crash
618 EXPECT_EQ(nullptr, weak.promote());
619
620 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
621
622 // In order to fix this:
623 // - need to have incStrongAttempted reflected across IPC boundary (wait for
624 // response to promote - round trip...)
625 // - sendOnLastWeakRef, to delete entries out of RpcState table
626 EXPECT_EQ(b, weak.promote());
627}
628
629#define expectSessions(expected, iface) \
630 do { \
631 int session; \
632 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
633 EXPECT_EQ(expected, session); \
634 } while (false)
635
Steven Morelandc1635952021-04-01 16:20:47 +0000636TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000637 auto proc = createRpcTestSocketServerProcess(1);
638
639 sp<IBinderRpcSession> session;
640 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
641 std::string out;
642 EXPECT_OK(session->getName(&out));
643 EXPECT_EQ("aoeu", out);
644
645 expectSessions(1, proc.rootIface);
646 session = nullptr;
647 expectSessions(0, proc.rootIface);
648}
649
Steven Morelandc1635952021-04-01 16:20:47 +0000650TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000651 auto proc = createRpcTestSocketServerProcess(1);
652
653 std::vector<sp<IBinderRpcSession>> sessions;
654
655 for (size_t i = 0; i < 15; i++) {
656 expectSessions(i, proc.rootIface);
657 sp<IBinderRpcSession> session;
658 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
659 sessions.push_back(session);
660 }
661 expectSessions(sessions.size(), proc.rootIface);
662 for (size_t i = 0; i < sessions.size(); i++) {
663 std::string out;
664 EXPECT_OK(sessions.at(i)->getName(&out));
665 EXPECT_EQ(std::to_string(i), out);
666 }
667 expectSessions(sessions.size(), proc.rootIface);
668
669 while (!sessions.empty()) {
670 sessions.pop_back();
671 expectSessions(sessions.size(), proc.rootIface);
672 }
673 expectSessions(0, proc.rootIface);
674}
675
676size_t epochMillis() {
677 using std::chrono::duration_cast;
678 using std::chrono::milliseconds;
679 using std::chrono::seconds;
680 using std::chrono::system_clock;
681 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
682}
683
Steven Morelandc1635952021-04-01 16:20:47 +0000684TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000685 constexpr size_t kNumThreads = 10;
686
687 auto proc = createRpcTestSocketServerProcess(kNumThreads);
688
689 EXPECT_OK(proc.rootIface->lock());
690
691 // block all but one thread taking locks
692 std::vector<std::thread> ts;
693 for (size_t i = 0; i < kNumThreads - 1; i++) {
694 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
695 }
696
697 usleep(100000); // give chance for calls on other threads
698
699 // other calls still work
700 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
701
702 constexpr size_t blockTimeMs = 500;
703 size_t epochMsBefore = epochMillis();
704 // after this, we should never see a response within this time
705 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
706
707 // this call should be blocked for blockTimeMs
708 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
709
710 size_t epochMsAfter = epochMillis();
711 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
712
713 for (auto& t : ts) t.join();
714}
715
Steven Morelandc1635952021-04-01 16:20:47 +0000716TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000717 constexpr size_t kNumThreads = 10;
718 constexpr size_t kNumCalls = kNumThreads + 3;
719 constexpr size_t kSleepMs = 500;
720
721 auto proc = createRpcTestSocketServerProcess(kNumThreads);
722
723 size_t epochMsBefore = epochMillis();
724
725 std::vector<std::thread> ts;
726 for (size_t i = 0; i < kNumCalls; i++) {
727 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
728 }
729
730 for (auto& t : ts) t.join();
731
732 size_t epochMsAfter = epochMillis();
733
734 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
735
736 // Potential flake, but make sure calls are handled in parallel.
737 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
738}
739
Steven Morelandc1635952021-04-01 16:20:47 +0000740TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000741 constexpr size_t kNumClientThreads = 10;
742 constexpr size_t kNumServerThreads = 10;
743 constexpr size_t kNumCalls = 100;
744
745 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
746
747 std::vector<std::thread> threads;
748 for (size_t i = 0; i < kNumClientThreads; i++) {
749 threads.push_back(std::thread([&] {
750 for (size_t j = 0; j < kNumCalls; j++) {
751 sp<IBinder> out;
752 proc.rootIface->repeatBinder(proc.rootBinder, &out);
753 EXPECT_EQ(proc.rootBinder, out);
754 }
755 }));
756 }
757
758 for (auto& t : threads) t.join();
759}
760
Steven Morelandc1635952021-04-01 16:20:47 +0000761TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000762 constexpr size_t kReallyLongTimeMs = 100;
763 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
764
765 // more than one thread, just so this doesn't deadlock
766 auto proc = createRpcTestSocketServerProcess(2);
767
768 size_t epochMsBefore = epochMillis();
769
770 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
771
772 size_t epochMsAfter = epochMillis();
773 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
774}
775
Steven Morelandc1635952021-04-01 16:20:47 +0000776TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000777 constexpr size_t kNumSleeps = 10;
778 constexpr size_t kNumExtraServerThreads = 4;
779 constexpr size_t kSleepMs = 50;
780
781 // make sure calls to the same object happen on the same thread
782 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
783
784 EXPECT_OK(proc.rootIface->lock());
785
786 for (size_t i = 0; i < kNumSleeps; i++) {
787 // these should be processed serially
788 proc.rootIface->sleepMsAsync(kSleepMs);
789 }
790 // should also be processesed serially
791 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
792
793 size_t epochMsBefore = epochMillis();
794 EXPECT_OK(proc.rootIface->lockUnlock());
795 size_t epochMsAfter = epochMillis();
796
797 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
798}
799
Steven Morelandc1635952021-04-01 16:20:47 +0000800TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000801 for (bool doDeathCleanup : {true, false}) {
802 auto proc = createRpcTestSocketServerProcess(1);
803
804 // make sure there is some state during crash
805 // 1. we hold their binder
806 sp<IBinderRpcSession> session;
807 EXPECT_OK(proc.rootIface->openSession("happy", &session));
808 // 2. they hold our binder
809 sp<IBinder> binder = new BBinder();
810 EXPECT_OK(proc.rootIface->holdBinder(binder));
811
812 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
813 << "Do death cleanup: " << doDeathCleanup;
814
815 proc.proc.expectInvalid = true;
816 }
817}
818
Steven Moreland37aff182021-03-26 02:04:16 +0000819TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
820 auto proc = createRpcTestSocketServerProcess(1);
821
822 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
823 ASSERT_NE(binder, nullptr);
824
825 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
826}
827
828TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
829 auto proc = createRpcTestSocketServerProcess(1);
830
831 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
832 ASSERT_NE(binder, nullptr);
833
834 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
835 ASSERT_NE(ndkBinder, nullptr);
836
837 std::string out;
838 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
839 ASSERT_TRUE(status.isOk()) << status.getDescription();
840 ASSERT_EQ("aoeuaoeu", out);
841}
842
Steven Moreland5553ac42020-11-11 02:14:45 +0000843ssize_t countFds() {
844 DIR* dir = opendir("/proc/self/fd/");
845 if (dir == nullptr) return -1;
846 ssize_t ret = 0;
847 dirent* ent;
848 while ((ent = readdir(dir)) != nullptr) ret++;
849 closedir(dir);
850 return ret;
851}
852
Steven Morelandc1635952021-04-01 16:20:47 +0000853TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000854 ssize_t beforeFds = countFds();
855 ASSERT_GE(beforeFds, 0);
856 {
857 auto proc = createRpcTestSocketServerProcess(10);
858 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
859 }
860 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
861}
862
Steven Morelandc1635952021-04-01 16:20:47 +0000863INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700864 ::testing::ValuesIn({
865 SocketType::UNIX,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000866#ifdef __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700867 SocketType::VSOCK,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000868#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700869 SocketType::INET,
870 }),
Steven Morelandf6ec4632021-04-01 16:20:47 +0000871 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +0000872
873} // namespace android
874
875int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000876 ::testing::InitGoogleTest(&argc, argv);
877 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
878 return RUN_ALL_TESTS();
879}