blob: dd68fdbc6d8f7ae58bfdfa85e5664065878caf9f [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__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700259 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000260};
261static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
262 switch (info.param) {
263 case SocketType::UNIX:
264 return "unix_domain_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000265#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000266 case SocketType::VSOCK:
267 return "vm_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000268#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700269 case SocketType::INET:
270 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000271 default:
272 LOG_ALWAYS_FATAL("Unknown socket type");
273 return "";
274 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000275}
Steven Morelandc1635952021-04-01 16:20:47 +0000276class BinderRpc : public ::testing::TestWithParam<SocketType> {
277public:
278 // This creates a new process serving an interface on a certain number of
279 // threads.
280 ProcessConnection createRpcTestSocketServerProcess(
281 size_t numThreads,
282 const std::function<void(const sp<RpcServer>&, const sp<RpcConnection>&)>& configure) {
283 CHECK_GT(numThreads, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000284
Steven Morelandc1635952021-04-01 16:20:47 +0000285 SocketType socketType = GetParam();
286
287 std::string addr = allocateSocketAddress();
288 unlink(addr.c_str());
289 static unsigned int port = 3456;
290 port++;
291
292 auto ret = ProcessConnection{
293 .host = Process([&] {
294 sp<RpcServer> server = RpcServer::make();
295
296 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
297
298 // server supporting one client on one socket
299 sp<RpcConnection> connection = server->addClientConnection();
300
301 switch (socketType) {
302 case SocketType::UNIX:
303 CHECK(connection->setupUnixDomainServer(addr.c_str())) << addr;
304 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000305#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000306 case SocketType::VSOCK:
307 CHECK(connection->setupVsockServer(port));
308 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000309#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700310 case SocketType::INET:
311 CHECK(connection->setupInetServer(port));
312 break;
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__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700343 case SocketType::INET:
344 if (ret.connection->addInetClient("127.0.0.1", port)) goto success;
345 break;
Steven Morelandc1635952021-04-01 16:20:47 +0000346 default:
347 LOG_ALWAYS_FATAL("Unknown socket type");
348 }
349 }
350 LOG_ALWAYS_FATAL("Could not connect");
351 success:;
352 }
353
354 ret.rootBinder = ret.connection->getRootObject();
355 return ret;
356 }
357
358 BinderRpcTestProcessConnection createRpcTestSocketServerProcess(size_t numThreads) {
359 BinderRpcTestProcessConnection ret{
360 .proc = createRpcTestSocketServerProcess(numThreads,
361 [&](const sp<RpcServer>& server,
362 const sp<RpcConnection>& connection) {
363 sp<MyBinderRpcTest> service =
364 new MyBinderRpcTest;
365 server->setRootObject(service);
366 service->connection =
367 connection; // for testing only
368 }),
369 };
370
371 ret.rootBinder = ret.proc.rootBinder;
372 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
373
374 return ret;
375 }
376};
377
378TEST_P(BinderRpc, RootObjectIsNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000379 auto proc = createRpcTestSocketServerProcess(1,
380 [](const sp<RpcServer>& server,
381 const sp<RpcConnection>&) {
382 // this is the default, but to be explicit
383 server->setRootObject(nullptr);
384 });
385
386 // retrieved by getRootObject when process is created above
387 EXPECT_EQ(nullptr, proc.rootBinder);
388
389 // make sure we can retrieve it again (process doesn't crash)
390 EXPECT_EQ(nullptr, proc.connection->getRootObject());
391}
392
Steven Morelandc1635952021-04-01 16:20:47 +0000393TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000394 auto proc = createRpcTestSocketServerProcess(1);
395 ASSERT_NE(proc.rootBinder, nullptr);
396 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
397}
398
Steven Moreland4cf688f2021-03-31 01:48:58 +0000399TEST_P(BinderRpc, GetInterfaceDescriptor) {
400 auto proc = createRpcTestSocketServerProcess(1);
401 ASSERT_NE(proc.rootBinder, nullptr);
402 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
403}
404
Steven Morelandc1635952021-04-01 16:20:47 +0000405TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000406 auto proc = createRpcTestSocketServerProcess(1);
407 Parcel data;
408 Parcel reply;
409 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
410}
411
Steven Moreland67753c32021-04-02 18:45:19 +0000412TEST_P(BinderRpc, AppendSeparateFormats) {
413 auto proc = createRpcTestSocketServerProcess(1);
414
415 Parcel p1;
416 p1.markForBinder(proc.rootBinder);
417 p1.writeInt32(3);
418
419 Parcel p2;
420
421 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
422 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
423}
424
Steven Morelandc1635952021-04-01 16:20:47 +0000425TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000426 auto proc = createRpcTestSocketServerProcess(1);
427 Parcel data;
428 data.markForBinder(proc.rootBinder);
429 Parcel reply;
430 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
431}
432
Steven Morelandc1635952021-04-01 16:20:47 +0000433TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000434 auto proc = createRpcTestSocketServerProcess(1);
435 EXPECT_OK(proc.rootIface->sendString("asdf"));
436}
437
Steven Morelandc1635952021-04-01 16:20:47 +0000438TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000439 auto proc = createRpcTestSocketServerProcess(1);
440 std::string doubled;
441 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
442 EXPECT_EQ("cool cool ", doubled);
443}
444
Steven Morelandc1635952021-04-01 16:20:47 +0000445TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000446 auto proc = createRpcTestSocketServerProcess(1);
447 std::string single = std::string(1024, 'a');
448 std::string doubled;
449 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
450 EXPECT_EQ(single + single, doubled);
451}
452
Steven Morelandc1635952021-04-01 16:20:47 +0000453TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000454 auto proc = createRpcTestSocketServerProcess(1);
455
456 int32_t pingResult;
457 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
458 EXPECT_EQ(OK, pingResult);
459
460 EXPECT_EQ(0, MyBinderRpcSession::gNum);
461}
462
Steven Morelandc1635952021-04-01 16:20:47 +0000463TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000464 auto proc = createRpcTestSocketServerProcess(1);
465
466 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
467 sp<IBinder> outBinder;
468 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
469 EXPECT_EQ(inBinder, outBinder);
470
471 wp<IBinder> weak = inBinder;
472 inBinder = nullptr;
473 outBinder = nullptr;
474
475 // Force reading a reply, to process any pending dec refs from the other
476 // process (the other process will process dec refs there before processing
477 // the ping here).
478 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
479
480 EXPECT_EQ(nullptr, weak.promote());
481
482 EXPECT_EQ(0, MyBinderRpcSession::gNum);
483}
484
Steven Morelandc1635952021-04-01 16:20:47 +0000485TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000486 auto proc = createRpcTestSocketServerProcess(1);
487
488 sp<IBinderRpcSession> session;
489 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
490
491 sp<IBinder> inBinder = IInterface::asBinder(session);
492 sp<IBinder> outBinder;
493 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
494 EXPECT_EQ(inBinder, outBinder);
495
496 wp<IBinder> weak = inBinder;
497 session = nullptr;
498 inBinder = nullptr;
499 outBinder = nullptr;
500
501 // Force reading a reply, to process any pending dec refs from the other
502 // process (the other process will process dec refs there before processing
503 // the ping here).
504 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
505
506 EXPECT_EQ(nullptr, weak.promote());
507}
508
Steven Morelandc1635952021-04-01 16:20:47 +0000509TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000510 auto proc = createRpcTestSocketServerProcess(1);
511
512 sp<IBinder> outBinder;
513 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
514 EXPECT_EQ(nullptr, outBinder);
515}
516
Steven Morelandc1635952021-04-01 16:20:47 +0000517TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000518 auto proc = createRpcTestSocketServerProcess(1);
519
520 IBinder* ptr = nullptr;
521 {
522 sp<IBinder> binder = new BBinder();
523 ptr = binder.get();
524 EXPECT_OK(proc.rootIface->holdBinder(binder));
525 }
526
527 sp<IBinder> held;
528 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
529
530 EXPECT_EQ(held.get(), ptr);
531
532 // stop holding binder, because we test to make sure references are cleaned
533 // up
534 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
535 // and flush ref counts
536 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
537}
538
539// START TESTS FOR LIMITATIONS OF SOCKET BINDER
540// These are behavioral differences form regular binder, where certain usecases
541// aren't supported.
542
Steven Morelandc1635952021-04-01 16:20:47 +0000543TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketConnections) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000544 auto proc1 = createRpcTestSocketServerProcess(1);
545 auto proc2 = createRpcTestSocketServerProcess(1);
546
547 sp<IBinder> outBinder;
548 EXPECT_EQ(INVALID_OPERATION,
549 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
550}
551
Steven Morelandc1635952021-04-01 16:20:47 +0000552TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000553 auto proc = createRpcTestSocketServerProcess(1);
554
555 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
556 sp<IBinder> outBinder;
557 EXPECT_EQ(INVALID_OPERATION,
558 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
559}
560
Steven Morelandc1635952021-04-01 16:20:47 +0000561TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000562 auto proc = createRpcTestSocketServerProcess(1);
563
564 // for historical reasons, IServiceManager interface only returns the
565 // exception code
566 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
567 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
568}
569
570// END TESTS FOR LIMITATIONS OF SOCKET BINDER
571
Steven Morelandc1635952021-04-01 16:20:47 +0000572TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000573 auto proc = createRpcTestSocketServerProcess(1);
574
575 sp<IBinder> outBinder;
576 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
577 EXPECT_EQ(proc.rootBinder, outBinder);
578}
579
Steven Morelandc1635952021-04-01 16:20:47 +0000580TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000581 auto proc = createRpcTestSocketServerProcess(1);
582
583 auto nastyNester = sp<MyBinderRpcTest>::make();
584 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
585
586 wp<IBinder> weak = nastyNester;
587 nastyNester = nullptr;
588 EXPECT_EQ(nullptr, weak.promote());
589}
590
Steven Morelandc1635952021-04-01 16:20:47 +0000591TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000592 auto proc = createRpcTestSocketServerProcess(1);
593
594 sp<IBinder> a;
595 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
596
597 sp<IBinder> b;
598 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
599
600 EXPECT_EQ(a, b);
601}
602
Steven Morelandc1635952021-04-01 16:20:47 +0000603TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000604 auto proc = createRpcTestSocketServerProcess(1);
605
606 sp<IBinder> a;
607 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
608 wp<IBinder> weak = a;
609 a = nullptr;
610
611 sp<IBinder> b;
612 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
613
614 // this is the wrong behavior, since BpBinder
615 // doesn't implement onIncStrongAttempted
616 // but make sure there is no crash
617 EXPECT_EQ(nullptr, weak.promote());
618
619 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
620
621 // In order to fix this:
622 // - need to have incStrongAttempted reflected across IPC boundary (wait for
623 // response to promote - round trip...)
624 // - sendOnLastWeakRef, to delete entries out of RpcState table
625 EXPECT_EQ(b, weak.promote());
626}
627
628#define expectSessions(expected, iface) \
629 do { \
630 int session; \
631 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
632 EXPECT_EQ(expected, session); \
633 } while (false)
634
Steven Morelandc1635952021-04-01 16:20:47 +0000635TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000636 auto proc = createRpcTestSocketServerProcess(1);
637
638 sp<IBinderRpcSession> session;
639 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
640 std::string out;
641 EXPECT_OK(session->getName(&out));
642 EXPECT_EQ("aoeu", out);
643
644 expectSessions(1, proc.rootIface);
645 session = nullptr;
646 expectSessions(0, proc.rootIface);
647}
648
Steven Morelandc1635952021-04-01 16:20:47 +0000649TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000650 auto proc = createRpcTestSocketServerProcess(1);
651
652 std::vector<sp<IBinderRpcSession>> sessions;
653
654 for (size_t i = 0; i < 15; i++) {
655 expectSessions(i, proc.rootIface);
656 sp<IBinderRpcSession> session;
657 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
658 sessions.push_back(session);
659 }
660 expectSessions(sessions.size(), proc.rootIface);
661 for (size_t i = 0; i < sessions.size(); i++) {
662 std::string out;
663 EXPECT_OK(sessions.at(i)->getName(&out));
664 EXPECT_EQ(std::to_string(i), out);
665 }
666 expectSessions(sessions.size(), proc.rootIface);
667
668 while (!sessions.empty()) {
669 sessions.pop_back();
670 expectSessions(sessions.size(), proc.rootIface);
671 }
672 expectSessions(0, proc.rootIface);
673}
674
675size_t epochMillis() {
676 using std::chrono::duration_cast;
677 using std::chrono::milliseconds;
678 using std::chrono::seconds;
679 using std::chrono::system_clock;
680 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
681}
682
Steven Morelandc1635952021-04-01 16:20:47 +0000683TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000684 constexpr size_t kNumThreads = 10;
685
686 auto proc = createRpcTestSocketServerProcess(kNumThreads);
687
688 EXPECT_OK(proc.rootIface->lock());
689
690 // block all but one thread taking locks
691 std::vector<std::thread> ts;
692 for (size_t i = 0; i < kNumThreads - 1; i++) {
693 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
694 }
695
696 usleep(100000); // give chance for calls on other threads
697
698 // other calls still work
699 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
700
701 constexpr size_t blockTimeMs = 500;
702 size_t epochMsBefore = epochMillis();
703 // after this, we should never see a response within this time
704 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
705
706 // this call should be blocked for blockTimeMs
707 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
708
709 size_t epochMsAfter = epochMillis();
710 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
711
712 for (auto& t : ts) t.join();
713}
714
Steven Morelandc1635952021-04-01 16:20:47 +0000715TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000716 constexpr size_t kNumThreads = 10;
717 constexpr size_t kNumCalls = kNumThreads + 3;
718 constexpr size_t kSleepMs = 500;
719
720 auto proc = createRpcTestSocketServerProcess(kNumThreads);
721
722 size_t epochMsBefore = epochMillis();
723
724 std::vector<std::thread> ts;
725 for (size_t i = 0; i < kNumCalls; i++) {
726 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
727 }
728
729 for (auto& t : ts) t.join();
730
731 size_t epochMsAfter = epochMillis();
732
733 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
734
735 // Potential flake, but make sure calls are handled in parallel.
736 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
737}
738
Steven Morelandc1635952021-04-01 16:20:47 +0000739TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000740 constexpr size_t kNumClientThreads = 10;
741 constexpr size_t kNumServerThreads = 10;
742 constexpr size_t kNumCalls = 100;
743
744 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
745
746 std::vector<std::thread> threads;
747 for (size_t i = 0; i < kNumClientThreads; i++) {
748 threads.push_back(std::thread([&] {
749 for (size_t j = 0; j < kNumCalls; j++) {
750 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000751 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000752 EXPECT_EQ(proc.rootBinder, out);
753 }
754 }));
755 }
756
757 for (auto& t : threads) t.join();
758}
759
Steven Morelandc6046982021-04-20 00:49:42 +0000760TEST_P(BinderRpc, OnewayStressTest) {
761 constexpr size_t kNumClientThreads = 10;
762 constexpr size_t kNumServerThreads = 10;
763 constexpr size_t kNumCalls = 100;
764
765 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
766
767 std::vector<std::thread> threads;
768 for (size_t i = 0; i < kNumClientThreads; i++) {
769 threads.push_back(std::thread([&] {
770 for (size_t j = 0; j < kNumCalls; j++) {
771 EXPECT_OK(proc.rootIface->sendString("a"));
772 }
773
774 // check threads are not stuck
775 EXPECT_OK(proc.rootIface->sleepMs(250));
776 }));
777 }
778
779 for (auto& t : threads) t.join();
780}
781
Steven Morelandc1635952021-04-01 16:20:47 +0000782TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000783 constexpr size_t kReallyLongTimeMs = 100;
784 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
785
786 // more than one thread, just so this doesn't deadlock
787 auto proc = createRpcTestSocketServerProcess(2);
788
789 size_t epochMsBefore = epochMillis();
790
791 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
792
793 size_t epochMsAfter = epochMillis();
794 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
795}
796
Steven Morelandc1635952021-04-01 16:20:47 +0000797TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000798 constexpr size_t kNumSleeps = 10;
799 constexpr size_t kNumExtraServerThreads = 4;
800 constexpr size_t kSleepMs = 50;
801
802 // make sure calls to the same object happen on the same thread
803 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
804
805 EXPECT_OK(proc.rootIface->lock());
806
807 for (size_t i = 0; i < kNumSleeps; i++) {
808 // these should be processed serially
809 proc.rootIface->sleepMsAsync(kSleepMs);
810 }
811 // should also be processesed serially
812 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
813
814 size_t epochMsBefore = epochMillis();
815 EXPECT_OK(proc.rootIface->lockUnlock());
816 size_t epochMsAfter = epochMillis();
817
818 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
819}
820
Steven Morelandc1635952021-04-01 16:20:47 +0000821TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000822 for (bool doDeathCleanup : {true, false}) {
823 auto proc = createRpcTestSocketServerProcess(1);
824
825 // make sure there is some state during crash
826 // 1. we hold their binder
827 sp<IBinderRpcSession> session;
828 EXPECT_OK(proc.rootIface->openSession("happy", &session));
829 // 2. they hold our binder
830 sp<IBinder> binder = new BBinder();
831 EXPECT_OK(proc.rootIface->holdBinder(binder));
832
833 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
834 << "Do death cleanup: " << doDeathCleanup;
835
836 proc.proc.expectInvalid = true;
837 }
838}
839
Steven Moreland37aff182021-03-26 02:04:16 +0000840TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
841 auto proc = createRpcTestSocketServerProcess(1);
842
843 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
844 ASSERT_NE(binder, nullptr);
845
846 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
847}
848
849TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
850 auto proc = createRpcTestSocketServerProcess(1);
851
852 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
853 ASSERT_NE(binder, nullptr);
854
855 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
856 ASSERT_NE(ndkBinder, nullptr);
857
858 std::string out;
859 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
860 ASSERT_TRUE(status.isOk()) << status.getDescription();
861 ASSERT_EQ("aoeuaoeu", out);
862}
863
Steven Moreland5553ac42020-11-11 02:14:45 +0000864ssize_t countFds() {
865 DIR* dir = opendir("/proc/self/fd/");
866 if (dir == nullptr) return -1;
867 ssize_t ret = 0;
868 dirent* ent;
869 while ((ent = readdir(dir)) != nullptr) ret++;
870 closedir(dir);
871 return ret;
872}
873
Steven Morelandc1635952021-04-01 16:20:47 +0000874TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000875 ssize_t beforeFds = countFds();
876 ASSERT_GE(beforeFds, 0);
877 {
878 auto proc = createRpcTestSocketServerProcess(10);
879 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
880 }
881 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
882}
883
Steven Morelandc1635952021-04-01 16:20:47 +0000884INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700885 ::testing::ValuesIn({
886 SocketType::UNIX,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000887#ifdef __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700888 SocketType::VSOCK,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000889#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700890 SocketType::INET,
891 }),
Steven Morelandf6ec4632021-04-01 16:20:47 +0000892 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +0000893
894} // namespace android
895
896int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000897 ::testing::InitGoogleTest(&argc, argv);
898 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
899 return RUN_ALL_TESTS();
900}