blob: ce69ea26a494fb65b387f2cd252af9914b4b8eae [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>
Yifan Hong6d82c8a2021-04-26 20:26:45 -070020#include <android-base/file.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000021#include <android-base/logging.h>
Steven Moreland37aff182021-03-26 02:04:16 +000022#include <android/binder_auto_utils.h>
23#include <android/binder_libbinder.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000024#include <binder/Binder.h>
25#include <binder/BpBinder.h>
26#include <binder/IServiceManager.h>
27#include <binder/ProcessState.h>
28#include <binder/RpcConnection.h>
29#include <binder/RpcServer.h>
30#include <gtest/gtest.h>
31
Steven Morelandc1635952021-04-01 16:20:47 +000032#include <chrono>
33#include <cstdlib>
34#include <iostream>
35#include <thread>
36
Steven Morelandf6ec4632021-04-01 16:20:47 +000037#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +000038#include <linux/vm_sockets.h>
Steven Morelandf6ec4632021-04-01 16:20:47 +000039#endif //__BIONIC__
40
Steven Morelandc1635952021-04-01 16:20:47 +000041#include <sys/prctl.h>
42#include <unistd.h>
43
Steven Moreland5553ac42020-11-11 02:14:45 +000044#include "../RpcState.h" // for debugging
45
46namespace android {
47
Steven Moreland1fda67b2021-04-02 18:35:50 +000048TEST(BinderRpcParcel, EntireParcelFormatted) {
49 Parcel p;
50 p.writeInt32(3);
51
52 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
53}
54
Steven Moreland5553ac42020-11-11 02:14:45 +000055using android::binder::Status;
56
57#define EXPECT_OK(status) \
58 do { \
59 Status stat = (status); \
60 EXPECT_TRUE(stat.isOk()) << stat; \
61 } while (false)
62
63class MyBinderRpcSession : public BnBinderRpcSession {
64public:
65 static std::atomic<int32_t> gNum;
66
67 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
68 Status getName(std::string* name) override {
69 *name = mName;
70 return Status::ok();
71 }
72 ~MyBinderRpcSession() { gNum--; }
73
74private:
75 std::string mName;
76};
77std::atomic<int32_t> MyBinderRpcSession::gNum;
78
79class MyBinderRpcTest : public BnBinderRpcTest {
80public:
81 sp<RpcConnection> connection;
82
83 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +000084 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +000085 return Status::ok();
86 }
87 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +000088 *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
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700180class Pipe {
181public:
182 Pipe() { CHECK(android::base::Pipe(&mRead, &mWrite)); }
183 Pipe(Pipe&&) = default;
184 android::base::borrowed_fd readEnd() { return mRead; }
185 android::base::borrowed_fd writeEnd() { return mWrite; }
186
187private:
188 android::base::unique_fd mRead;
189 android::base::unique_fd mWrite;
190};
191
Steven Moreland5553ac42020-11-11 02:14:45 +0000192class Process {
193public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700194 Process(Process&&) = default;
195 Process(const std::function<void(Pipe*)>& f) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000196 if (0 == (mPid = fork())) {
197 // racey: assume parent doesn't crash before this is set
198 prctl(PR_SET_PDEATHSIG, SIGHUP);
199
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700200 f(&mPipe);
Steven Moreland5553ac42020-11-11 02:14:45 +0000201 }
202 }
203 ~Process() {
204 if (mPid != 0) {
205 kill(mPid, SIGKILL);
206 }
207 }
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700208 Pipe* getPipe() { return &mPipe; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000209
210private:
211 pid_t mPid = 0;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700212 Pipe mPipe;
Steven Moreland5553ac42020-11-11 02:14:45 +0000213};
214
215static std::string allocateSocketAddress() {
216 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000217 std::string temp = getenv("TMPDIR") ?: "/tmp";
218 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000219};
220
221struct ProcessConnection {
222 // reference to process hosting a socket server
223 Process host;
224
225 // client connection object associated with other process
226 sp<RpcConnection> connection;
227
228 // pre-fetched root object
229 sp<IBinder> rootBinder;
230
231 // whether connection should be invalidated by end of run
232 bool expectInvalid = false;
233
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700234 ProcessConnection(ProcessConnection&&) = default;
Steven Moreland5553ac42020-11-11 02:14:45 +0000235 ~ProcessConnection() {
236 rootBinder = nullptr;
237 EXPECT_NE(nullptr, connection);
238 EXPECT_NE(nullptr, connection->state());
239 EXPECT_EQ(0, connection->state()->countBinders()) << (connection->state()->dump(), "dump:");
240
241 wp<RpcConnection> weakConnection = connection;
242 connection = nullptr;
243 EXPECT_EQ(nullptr, weakConnection.promote()) << "Leaked connection";
244 }
245};
246
Steven Moreland5553ac42020-11-11 02:14:45 +0000247// Process connection where the process hosts IBinderRpcTest, the server used
248// for most testing here
249struct BinderRpcTestProcessConnection {
250 ProcessConnection proc;
251
252 // pre-fetched root object
253 sp<IBinder> rootBinder;
254
255 // pre-casted root object
256 sp<IBinderRpcTest> rootIface;
257
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700258 BinderRpcTestProcessConnection(BinderRpcTestProcessConnection&&) = default;
Steven Moreland5553ac42020-11-11 02:14:45 +0000259 ~BinderRpcTestProcessConnection() {
260 if (!proc.expectInvalid) {
261 int32_t remoteBinders = 0;
262 EXPECT_OK(rootIface->countBinders(&remoteBinders));
263 // should only be the root binder object, iface
264 EXPECT_EQ(remoteBinders, 1);
265 }
266
267 rootIface = nullptr;
268 rootBinder = nullptr;
269 }
270};
271
Steven Morelandc1635952021-04-01 16:20:47 +0000272enum class SocketType {
273 UNIX,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000274#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000275 VSOCK,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000276#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700277 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000278};
279static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
280 switch (info.param) {
281 case SocketType::UNIX:
282 return "unix_domain_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000283#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000284 case SocketType::VSOCK:
285 return "vm_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000286#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700287 case SocketType::INET:
288 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000289 default:
290 LOG_ALWAYS_FATAL("Unknown socket type");
291 return "";
292 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000293}
Steven Morelandc1635952021-04-01 16:20:47 +0000294class BinderRpc : public ::testing::TestWithParam<SocketType> {
295public:
296 // This creates a new process serving an interface on a certain number of
297 // threads.
298 ProcessConnection createRpcTestSocketServerProcess(
299 size_t numThreads,
300 const std::function<void(const sp<RpcServer>&, const sp<RpcConnection>&)>& configure) {
301 CHECK_GT(numThreads, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000302
Steven Morelandc1635952021-04-01 16:20:47 +0000303 SocketType socketType = GetParam();
304
305 std::string addr = allocateSocketAddress();
306 unlink(addr.c_str());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700307 static unsigned int vsockPort = 3456;
308 vsockPort++;
Steven Morelandc1635952021-04-01 16:20:47 +0000309
310 auto ret = ProcessConnection{
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700311 .host = Process([&](Pipe* pipe) {
Steven Morelandc1635952021-04-01 16:20:47 +0000312 sp<RpcServer> server = RpcServer::make();
313
314 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
315
316 // server supporting one client on one socket
317 sp<RpcConnection> connection = server->addClientConnection();
318
319 switch (socketType) {
320 case SocketType::UNIX:
321 CHECK(connection->setupUnixDomainServer(addr.c_str())) << addr;
322 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000323#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000324 case SocketType::VSOCK:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700325 CHECK(connection->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000326 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000327#endif // __BIONIC__
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700328 case SocketType::INET: {
329 unsigned int outPort = 0;
330 CHECK(connection->setupInetServer(0, &outPort));
331 CHECK_NE(0, outPort);
332 CHECK(android::base::WriteFully(pipe->writeEnd(), &outPort,
333 sizeof(outPort)));
Yifan Hong0d2bd112021-04-13 17:38:36 -0700334 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700335 }
Steven Morelandc1635952021-04-01 16:20:47 +0000336 default:
337 LOG_ALWAYS_FATAL("Unknown socket type");
338 }
339
340 configure(server, connection);
341
342 // accept 'numThreads' connections
343 std::vector<std::thread> pool;
344 for (size_t i = 0; i + 1 < numThreads; i++) {
345 pool.push_back(std::thread([=] { connection->join(); }));
346 }
347 connection->join();
348 for (auto& t : pool) t.join();
349 }),
350 .connection = RpcConnection::make(),
351 };
352
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700353 unsigned int inetPort = 0;
354 if (socketType == SocketType::INET) {
355 CHECK(android::base::ReadFully(ret.host.getPipe()->readEnd(), &inetPort,
356 sizeof(inetPort)));
357 CHECK_NE(0, inetPort);
358 }
359
Steven Morelandc1635952021-04-01 16:20:47 +0000360 // create remainder of connections
361 for (size_t i = 0; i < numThreads; i++) {
362 for (size_t tries = 0; tries < 5; tries++) {
363 usleep(10000);
364 switch (socketType) {
365 case SocketType::UNIX:
366 if (ret.connection->addUnixDomainClient(addr.c_str())) goto success;
367 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000368#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000369 case SocketType::VSOCK:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700370 if (ret.connection->addVsockClient(VMADDR_CID_LOCAL, vsockPort))
371 goto success;
Steven Morelandc1635952021-04-01 16:20:47 +0000372 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000373#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700374 case SocketType::INET:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700375 if (ret.connection->addInetClient("127.0.0.1", inetPort)) goto success;
Yifan Hong0d2bd112021-04-13 17:38:36 -0700376 break;
Steven Morelandc1635952021-04-01 16:20:47 +0000377 default:
378 LOG_ALWAYS_FATAL("Unknown socket type");
379 }
380 }
381 LOG_ALWAYS_FATAL("Could not connect");
382 success:;
383 }
384
385 ret.rootBinder = ret.connection->getRootObject();
386 return ret;
387 }
388
389 BinderRpcTestProcessConnection createRpcTestSocketServerProcess(size_t numThreads) {
390 BinderRpcTestProcessConnection ret{
391 .proc = createRpcTestSocketServerProcess(numThreads,
392 [&](const sp<RpcServer>& server,
393 const sp<RpcConnection>& connection) {
394 sp<MyBinderRpcTest> service =
395 new MyBinderRpcTest;
396 server->setRootObject(service);
397 service->connection =
398 connection; // for testing only
399 }),
400 };
401
402 ret.rootBinder = ret.proc.rootBinder;
403 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
404
405 return ret;
406 }
407};
408
409TEST_P(BinderRpc, RootObjectIsNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000410 auto proc = createRpcTestSocketServerProcess(1,
411 [](const sp<RpcServer>& server,
412 const sp<RpcConnection>&) {
413 // this is the default, but to be explicit
414 server->setRootObject(nullptr);
415 });
416
417 // retrieved by getRootObject when process is created above
418 EXPECT_EQ(nullptr, proc.rootBinder);
419
420 // make sure we can retrieve it again (process doesn't crash)
421 EXPECT_EQ(nullptr, proc.connection->getRootObject());
422}
423
Steven Morelandc1635952021-04-01 16:20:47 +0000424TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000425 auto proc = createRpcTestSocketServerProcess(1);
426 ASSERT_NE(proc.rootBinder, nullptr);
427 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
428}
429
Steven Moreland4cf688f2021-03-31 01:48:58 +0000430TEST_P(BinderRpc, GetInterfaceDescriptor) {
431 auto proc = createRpcTestSocketServerProcess(1);
432 ASSERT_NE(proc.rootBinder, nullptr);
433 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
434}
435
Steven Morelandc1635952021-04-01 16:20:47 +0000436TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000437 auto proc = createRpcTestSocketServerProcess(1);
438 Parcel data;
439 Parcel reply;
440 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
441}
442
Steven Moreland67753c32021-04-02 18:45:19 +0000443TEST_P(BinderRpc, AppendSeparateFormats) {
444 auto proc = createRpcTestSocketServerProcess(1);
445
446 Parcel p1;
447 p1.markForBinder(proc.rootBinder);
448 p1.writeInt32(3);
449
450 Parcel p2;
451
452 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
453 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
454}
455
Steven Morelandc1635952021-04-01 16:20:47 +0000456TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000457 auto proc = createRpcTestSocketServerProcess(1);
458 Parcel data;
459 data.markForBinder(proc.rootBinder);
460 Parcel reply;
461 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
462}
463
Steven Morelandc1635952021-04-01 16:20:47 +0000464TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000465 auto proc = createRpcTestSocketServerProcess(1);
466 EXPECT_OK(proc.rootIface->sendString("asdf"));
467}
468
Steven Morelandc1635952021-04-01 16:20:47 +0000469TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000470 auto proc = createRpcTestSocketServerProcess(1);
471 std::string doubled;
472 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
473 EXPECT_EQ("cool cool ", doubled);
474}
475
Steven Morelandc1635952021-04-01 16:20:47 +0000476TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000477 auto proc = createRpcTestSocketServerProcess(1);
478 std::string single = std::string(1024, 'a');
479 std::string doubled;
480 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
481 EXPECT_EQ(single + single, doubled);
482}
483
Steven Morelandc1635952021-04-01 16:20:47 +0000484TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000485 auto proc = createRpcTestSocketServerProcess(1);
486
487 int32_t pingResult;
488 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
489 EXPECT_EQ(OK, pingResult);
490
491 EXPECT_EQ(0, MyBinderRpcSession::gNum);
492}
493
Steven Morelandc1635952021-04-01 16:20:47 +0000494TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000495 auto proc = createRpcTestSocketServerProcess(1);
496
497 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
498 sp<IBinder> outBinder;
499 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
500 EXPECT_EQ(inBinder, outBinder);
501
502 wp<IBinder> weak = inBinder;
503 inBinder = nullptr;
504 outBinder = nullptr;
505
506 // Force reading a reply, to process any pending dec refs from the other
507 // process (the other process will process dec refs there before processing
508 // the ping here).
509 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
510
511 EXPECT_EQ(nullptr, weak.promote());
512
513 EXPECT_EQ(0, MyBinderRpcSession::gNum);
514}
515
Steven Morelandc1635952021-04-01 16:20:47 +0000516TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000517 auto proc = createRpcTestSocketServerProcess(1);
518
519 sp<IBinderRpcSession> session;
520 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
521
522 sp<IBinder> inBinder = IInterface::asBinder(session);
523 sp<IBinder> outBinder;
524 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
525 EXPECT_EQ(inBinder, outBinder);
526
527 wp<IBinder> weak = inBinder;
528 session = nullptr;
529 inBinder = nullptr;
530 outBinder = nullptr;
531
532 // Force reading a reply, to process any pending dec refs from the other
533 // process (the other process will process dec refs there before processing
534 // the ping here).
535 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
536
537 EXPECT_EQ(nullptr, weak.promote());
538}
539
Steven Morelandc1635952021-04-01 16:20:47 +0000540TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000541 auto proc = createRpcTestSocketServerProcess(1);
542
543 sp<IBinder> outBinder;
544 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
545 EXPECT_EQ(nullptr, outBinder);
546}
547
Steven Morelandc1635952021-04-01 16:20:47 +0000548TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000549 auto proc = createRpcTestSocketServerProcess(1);
550
551 IBinder* ptr = nullptr;
552 {
553 sp<IBinder> binder = new BBinder();
554 ptr = binder.get();
555 EXPECT_OK(proc.rootIface->holdBinder(binder));
556 }
557
558 sp<IBinder> held;
559 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
560
561 EXPECT_EQ(held.get(), ptr);
562
563 // stop holding binder, because we test to make sure references are cleaned
564 // up
565 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
566 // and flush ref counts
567 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
568}
569
570// START TESTS FOR LIMITATIONS OF SOCKET BINDER
571// These are behavioral differences form regular binder, where certain usecases
572// aren't supported.
573
Steven Morelandc1635952021-04-01 16:20:47 +0000574TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketConnections) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000575 auto proc1 = createRpcTestSocketServerProcess(1);
576 auto proc2 = createRpcTestSocketServerProcess(1);
577
578 sp<IBinder> outBinder;
579 EXPECT_EQ(INVALID_OPERATION,
580 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
581}
582
Steven Morelandc1635952021-04-01 16:20:47 +0000583TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000584 auto proc = createRpcTestSocketServerProcess(1);
585
586 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
587 sp<IBinder> outBinder;
588 EXPECT_EQ(INVALID_OPERATION,
589 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
590}
591
Steven Morelandc1635952021-04-01 16:20:47 +0000592TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000593 auto proc = createRpcTestSocketServerProcess(1);
594
595 // for historical reasons, IServiceManager interface only returns the
596 // exception code
597 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
598 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
599}
600
601// END TESTS FOR LIMITATIONS OF SOCKET BINDER
602
Steven Morelandc1635952021-04-01 16:20:47 +0000603TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000604 auto proc = createRpcTestSocketServerProcess(1);
605
606 sp<IBinder> outBinder;
607 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
608 EXPECT_EQ(proc.rootBinder, outBinder);
609}
610
Steven Morelandc1635952021-04-01 16:20:47 +0000611TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000612 auto proc = createRpcTestSocketServerProcess(1);
613
614 auto nastyNester = sp<MyBinderRpcTest>::make();
615 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
616
617 wp<IBinder> weak = nastyNester;
618 nastyNester = nullptr;
619 EXPECT_EQ(nullptr, weak.promote());
620}
621
Steven Morelandc1635952021-04-01 16:20:47 +0000622TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000623 auto proc = createRpcTestSocketServerProcess(1);
624
625 sp<IBinder> a;
626 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
627
628 sp<IBinder> b;
629 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
630
631 EXPECT_EQ(a, b);
632}
633
Steven Morelandc1635952021-04-01 16:20:47 +0000634TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000635 auto proc = createRpcTestSocketServerProcess(1);
636
637 sp<IBinder> a;
638 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
639 wp<IBinder> weak = a;
640 a = nullptr;
641
642 sp<IBinder> b;
643 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
644
645 // this is the wrong behavior, since BpBinder
646 // doesn't implement onIncStrongAttempted
647 // but make sure there is no crash
648 EXPECT_EQ(nullptr, weak.promote());
649
650 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
651
652 // In order to fix this:
653 // - need to have incStrongAttempted reflected across IPC boundary (wait for
654 // response to promote - round trip...)
655 // - sendOnLastWeakRef, to delete entries out of RpcState table
656 EXPECT_EQ(b, weak.promote());
657}
658
659#define expectSessions(expected, iface) \
660 do { \
661 int session; \
662 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
663 EXPECT_EQ(expected, session); \
664 } while (false)
665
Steven Morelandc1635952021-04-01 16:20:47 +0000666TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000667 auto proc = createRpcTestSocketServerProcess(1);
668
669 sp<IBinderRpcSession> session;
670 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
671 std::string out;
672 EXPECT_OK(session->getName(&out));
673 EXPECT_EQ("aoeu", out);
674
675 expectSessions(1, proc.rootIface);
676 session = nullptr;
677 expectSessions(0, proc.rootIface);
678}
679
Steven Morelandc1635952021-04-01 16:20:47 +0000680TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000681 auto proc = createRpcTestSocketServerProcess(1);
682
683 std::vector<sp<IBinderRpcSession>> sessions;
684
685 for (size_t i = 0; i < 15; i++) {
686 expectSessions(i, proc.rootIface);
687 sp<IBinderRpcSession> session;
688 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
689 sessions.push_back(session);
690 }
691 expectSessions(sessions.size(), proc.rootIface);
692 for (size_t i = 0; i < sessions.size(); i++) {
693 std::string out;
694 EXPECT_OK(sessions.at(i)->getName(&out));
695 EXPECT_EQ(std::to_string(i), out);
696 }
697 expectSessions(sessions.size(), proc.rootIface);
698
699 while (!sessions.empty()) {
700 sessions.pop_back();
701 expectSessions(sessions.size(), proc.rootIface);
702 }
703 expectSessions(0, proc.rootIface);
704}
705
706size_t epochMillis() {
707 using std::chrono::duration_cast;
708 using std::chrono::milliseconds;
709 using std::chrono::seconds;
710 using std::chrono::system_clock;
711 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
712}
713
Steven Morelandc1635952021-04-01 16:20:47 +0000714TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000715 constexpr size_t kNumThreads = 10;
716
717 auto proc = createRpcTestSocketServerProcess(kNumThreads);
718
719 EXPECT_OK(proc.rootIface->lock());
720
721 // block all but one thread taking locks
722 std::vector<std::thread> ts;
723 for (size_t i = 0; i < kNumThreads - 1; i++) {
724 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
725 }
726
727 usleep(100000); // give chance for calls on other threads
728
729 // other calls still work
730 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
731
732 constexpr size_t blockTimeMs = 500;
733 size_t epochMsBefore = epochMillis();
734 // after this, we should never see a response within this time
735 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
736
737 // this call should be blocked for blockTimeMs
738 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
739
740 size_t epochMsAfter = epochMillis();
741 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
742
743 for (auto& t : ts) t.join();
744}
745
Steven Morelandc1635952021-04-01 16:20:47 +0000746TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000747 constexpr size_t kNumThreads = 10;
748 constexpr size_t kNumCalls = kNumThreads + 3;
749 constexpr size_t kSleepMs = 500;
750
751 auto proc = createRpcTestSocketServerProcess(kNumThreads);
752
753 size_t epochMsBefore = epochMillis();
754
755 std::vector<std::thread> ts;
756 for (size_t i = 0; i < kNumCalls; i++) {
757 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
758 }
759
760 for (auto& t : ts) t.join();
761
762 size_t epochMsAfter = epochMillis();
763
764 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
765
766 // Potential flake, but make sure calls are handled in parallel.
767 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
768}
769
Steven Morelandc1635952021-04-01 16:20:47 +0000770TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000771 constexpr size_t kNumClientThreads = 10;
772 constexpr size_t kNumServerThreads = 10;
773 constexpr size_t kNumCalls = 100;
774
775 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
776
777 std::vector<std::thread> threads;
778 for (size_t i = 0; i < kNumClientThreads; i++) {
779 threads.push_back(std::thread([&] {
780 for (size_t j = 0; j < kNumCalls; j++) {
781 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000782 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000783 EXPECT_EQ(proc.rootBinder, out);
784 }
785 }));
786 }
787
788 for (auto& t : threads) t.join();
789}
790
Steven Morelandc6046982021-04-20 00:49:42 +0000791TEST_P(BinderRpc, OnewayStressTest) {
792 constexpr size_t kNumClientThreads = 10;
793 constexpr size_t kNumServerThreads = 10;
794 constexpr size_t kNumCalls = 100;
795
796 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
797
798 std::vector<std::thread> threads;
799 for (size_t i = 0; i < kNumClientThreads; i++) {
800 threads.push_back(std::thread([&] {
801 for (size_t j = 0; j < kNumCalls; j++) {
802 EXPECT_OK(proc.rootIface->sendString("a"));
803 }
804
805 // check threads are not stuck
806 EXPECT_OK(proc.rootIface->sleepMs(250));
807 }));
808 }
809
810 for (auto& t : threads) t.join();
811}
812
Steven Morelandc1635952021-04-01 16:20:47 +0000813TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000814 constexpr size_t kReallyLongTimeMs = 100;
815 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
816
817 // more than one thread, just so this doesn't deadlock
818 auto proc = createRpcTestSocketServerProcess(2);
819
820 size_t epochMsBefore = epochMillis();
821
822 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
823
824 size_t epochMsAfter = epochMillis();
825 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
826}
827
Steven Morelandc1635952021-04-01 16:20:47 +0000828TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000829 constexpr size_t kNumSleeps = 10;
830 constexpr size_t kNumExtraServerThreads = 4;
831 constexpr size_t kSleepMs = 50;
832
833 // make sure calls to the same object happen on the same thread
834 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
835
836 EXPECT_OK(proc.rootIface->lock());
837
838 for (size_t i = 0; i < kNumSleeps; i++) {
839 // these should be processed serially
840 proc.rootIface->sleepMsAsync(kSleepMs);
841 }
842 // should also be processesed serially
843 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
844
845 size_t epochMsBefore = epochMillis();
846 EXPECT_OK(proc.rootIface->lockUnlock());
847 size_t epochMsAfter = epochMillis();
848
849 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
850}
851
Steven Morelandc1635952021-04-01 16:20:47 +0000852TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000853 for (bool doDeathCleanup : {true, false}) {
854 auto proc = createRpcTestSocketServerProcess(1);
855
856 // make sure there is some state during crash
857 // 1. we hold their binder
858 sp<IBinderRpcSession> session;
859 EXPECT_OK(proc.rootIface->openSession("happy", &session));
860 // 2. they hold our binder
861 sp<IBinder> binder = new BBinder();
862 EXPECT_OK(proc.rootIface->holdBinder(binder));
863
864 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
865 << "Do death cleanup: " << doDeathCleanup;
866
867 proc.proc.expectInvalid = true;
868 }
869}
870
Steven Moreland37aff182021-03-26 02:04:16 +0000871TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
872 auto proc = createRpcTestSocketServerProcess(1);
873
874 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
875 ASSERT_NE(binder, nullptr);
876
877 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
878}
879
880TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
881 auto proc = createRpcTestSocketServerProcess(1);
882
883 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
884 ASSERT_NE(binder, nullptr);
885
886 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
887 ASSERT_NE(ndkBinder, nullptr);
888
889 std::string out;
890 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
891 ASSERT_TRUE(status.isOk()) << status.getDescription();
892 ASSERT_EQ("aoeuaoeu", out);
893}
894
Steven Moreland5553ac42020-11-11 02:14:45 +0000895ssize_t countFds() {
896 DIR* dir = opendir("/proc/self/fd/");
897 if (dir == nullptr) return -1;
898 ssize_t ret = 0;
899 dirent* ent;
900 while ((ent = readdir(dir)) != nullptr) ret++;
901 closedir(dir);
902 return ret;
903}
904
Steven Morelandc1635952021-04-01 16:20:47 +0000905TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000906 ssize_t beforeFds = countFds();
907 ASSERT_GE(beforeFds, 0);
908 {
909 auto proc = createRpcTestSocketServerProcess(10);
910 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
911 }
912 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
913}
914
Steven Morelandc1635952021-04-01 16:20:47 +0000915INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700916 ::testing::ValuesIn({
917 SocketType::UNIX,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000918#ifdef __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700919 SocketType::VSOCK,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000920#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700921 SocketType::INET,
922 }),
Steven Morelandf6ec4632021-04-01 16:20:47 +0000923 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +0000924
925} // namespace android
926
927int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000928 ::testing::InitGoogleTest(&argc, argv);
929 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
930 return RUN_ALL_TESTS();
931}