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