blob: f3ec904d6984a104efa091d50b31f134b0ab6424 [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) {
Steven Morelandc1635952021-04-01 16:20:47 +0000301 SocketType socketType = GetParam();
302
303 std::string addr = allocateSocketAddress();
304 unlink(addr.c_str());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700305 static unsigned int vsockPort = 3456;
306 vsockPort++;
Steven Morelandc1635952021-04-01 16:20:47 +0000307
308 auto ret = ProcessConnection{
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700309 .host = Process([&](Pipe* pipe) {
Steven Morelandc1635952021-04-01 16:20:47 +0000310 sp<RpcServer> server = RpcServer::make();
311
312 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Morelandf137de92021-04-24 01:54:26 +0000313 server->setMaxThreads(numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000314
315 // server supporting one client on one socket
316 sp<RpcConnection> connection = server->addClientConnection();
317
318 switch (socketType) {
319 case SocketType::UNIX:
320 CHECK(connection->setupUnixDomainServer(addr.c_str())) << addr;
321 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000322#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000323 case SocketType::VSOCK:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700324 CHECK(connection->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000325 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000326#endif // __BIONIC__
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700327 case SocketType::INET: {
328 unsigned int outPort = 0;
329 CHECK(connection->setupInetServer(0, &outPort));
330 CHECK_NE(0, outPort);
331 CHECK(android::base::WriteFully(pipe->writeEnd(), &outPort,
332 sizeof(outPort)));
Yifan Hong0d2bd112021-04-13 17:38:36 -0700333 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700334 }
Steven Morelandc1635952021-04-01 16:20:47 +0000335 default:
336 LOG_ALWAYS_FATAL("Unknown socket type");
337 }
338
339 configure(server, connection);
340
Steven Morelandf137de92021-04-24 01:54:26 +0000341 server->join();
Steven Morelandc1635952021-04-01 16:20:47 +0000342 }),
343 .connection = RpcConnection::make(),
344 };
345
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700346 unsigned int inetPort = 0;
347 if (socketType == SocketType::INET) {
348 CHECK(android::base::ReadFully(ret.host.getPipe()->readEnd(), &inetPort,
349 sizeof(inetPort)));
350 CHECK_NE(0, inetPort);
351 }
352
Steven Morelandc1635952021-04-01 16:20:47 +0000353 // create remainder of connections
Steven Morelandf137de92021-04-24 01:54:26 +0000354 for (size_t tries = 0; tries < 10; tries++) {
355 usleep(10000);
356 switch (socketType) {
357 case SocketType::UNIX:
358 if (ret.connection->setupUnixDomainClient(addr.c_str())) goto success;
359 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000360#ifdef __BIONIC__
Steven Morelandf137de92021-04-24 01:54:26 +0000361 case SocketType::VSOCK:
362 if (ret.connection->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
363 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000364#endif // __BIONIC__
Steven Morelandf137de92021-04-24 01:54:26 +0000365 case SocketType::INET:
366 if (ret.connection->setupInetClient("127.0.0.1", inetPort)) goto success;
367 break;
368 default:
369 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000370 }
Steven Morelandc1635952021-04-01 16:20:47 +0000371 }
Steven Morelandf137de92021-04-24 01:54:26 +0000372 LOG_ALWAYS_FATAL("Could not connect");
373 success:
Steven Morelandc1635952021-04-01 16:20:47 +0000374
375 ret.rootBinder = ret.connection->getRootObject();
376 return ret;
377 }
378
379 BinderRpcTestProcessConnection createRpcTestSocketServerProcess(size_t numThreads) {
380 BinderRpcTestProcessConnection ret{
381 .proc = createRpcTestSocketServerProcess(numThreads,
382 [&](const sp<RpcServer>& server,
383 const sp<RpcConnection>& connection) {
384 sp<MyBinderRpcTest> service =
385 new MyBinderRpcTest;
386 server->setRootObject(service);
387 service->connection =
388 connection; // for testing only
389 }),
390 };
391
392 ret.rootBinder = ret.proc.rootBinder;
393 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
394
395 return ret;
396 }
397};
398
399TEST_P(BinderRpc, RootObjectIsNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000400 auto proc = createRpcTestSocketServerProcess(1,
401 [](const sp<RpcServer>& server,
402 const sp<RpcConnection>&) {
403 // this is the default, but to be explicit
404 server->setRootObject(nullptr);
405 });
406
407 // retrieved by getRootObject when process is created above
408 EXPECT_EQ(nullptr, proc.rootBinder);
409
410 // make sure we can retrieve it again (process doesn't crash)
411 EXPECT_EQ(nullptr, proc.connection->getRootObject());
412}
413
Steven Morelandc1635952021-04-01 16:20:47 +0000414TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000415 auto proc = createRpcTestSocketServerProcess(1);
416 ASSERT_NE(proc.rootBinder, nullptr);
417 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
418}
419
Steven Moreland4cf688f2021-03-31 01:48:58 +0000420TEST_P(BinderRpc, GetInterfaceDescriptor) {
421 auto proc = createRpcTestSocketServerProcess(1);
422 ASSERT_NE(proc.rootBinder, nullptr);
423 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
424}
425
Steven Morelandc1635952021-04-01 16:20:47 +0000426TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000427 auto proc = createRpcTestSocketServerProcess(1);
428 Parcel data;
429 Parcel reply;
430 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
431}
432
Steven Moreland67753c32021-04-02 18:45:19 +0000433TEST_P(BinderRpc, AppendSeparateFormats) {
434 auto proc = createRpcTestSocketServerProcess(1);
435
436 Parcel p1;
437 p1.markForBinder(proc.rootBinder);
438 p1.writeInt32(3);
439
440 Parcel p2;
441
442 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
443 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
444}
445
Steven Morelandc1635952021-04-01 16:20:47 +0000446TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000447 auto proc = createRpcTestSocketServerProcess(1);
448 Parcel data;
449 data.markForBinder(proc.rootBinder);
450 Parcel reply;
451 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
452}
453
Steven Morelandc1635952021-04-01 16:20:47 +0000454TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000455 auto proc = createRpcTestSocketServerProcess(1);
456 EXPECT_OK(proc.rootIface->sendString("asdf"));
457}
458
Steven Morelandc1635952021-04-01 16:20:47 +0000459TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000460 auto proc = createRpcTestSocketServerProcess(1);
461 std::string doubled;
462 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
463 EXPECT_EQ("cool cool ", doubled);
464}
465
Steven Morelandc1635952021-04-01 16:20:47 +0000466TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000467 auto proc = createRpcTestSocketServerProcess(1);
468 std::string single = std::string(1024, 'a');
469 std::string doubled;
470 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
471 EXPECT_EQ(single + single, doubled);
472}
473
Steven Morelandc1635952021-04-01 16:20:47 +0000474TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000475 auto proc = createRpcTestSocketServerProcess(1);
476
477 int32_t pingResult;
478 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
479 EXPECT_EQ(OK, pingResult);
480
481 EXPECT_EQ(0, MyBinderRpcSession::gNum);
482}
483
Steven Morelandc1635952021-04-01 16:20:47 +0000484TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000485 auto proc = createRpcTestSocketServerProcess(1);
486
487 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
488 sp<IBinder> outBinder;
489 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
490 EXPECT_EQ(inBinder, outBinder);
491
492 wp<IBinder> weak = inBinder;
493 inBinder = nullptr;
494 outBinder = nullptr;
495
496 // Force reading a reply, to process any pending dec refs from the other
497 // process (the other process will process dec refs there before processing
498 // the ping here).
499 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
500
501 EXPECT_EQ(nullptr, weak.promote());
502
503 EXPECT_EQ(0, MyBinderRpcSession::gNum);
504}
505
Steven Morelandc1635952021-04-01 16:20:47 +0000506TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000507 auto proc = createRpcTestSocketServerProcess(1);
508
509 sp<IBinderRpcSession> session;
510 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
511
512 sp<IBinder> inBinder = IInterface::asBinder(session);
513 sp<IBinder> outBinder;
514 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
515 EXPECT_EQ(inBinder, outBinder);
516
517 wp<IBinder> weak = inBinder;
518 session = nullptr;
519 inBinder = nullptr;
520 outBinder = nullptr;
521
522 // Force reading a reply, to process any pending dec refs from the other
523 // process (the other process will process dec refs there before processing
524 // the ping here).
525 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
526
527 EXPECT_EQ(nullptr, weak.promote());
528}
529
Steven Morelandc1635952021-04-01 16:20:47 +0000530TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000531 auto proc = createRpcTestSocketServerProcess(1);
532
533 sp<IBinder> outBinder;
534 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
535 EXPECT_EQ(nullptr, outBinder);
536}
537
Steven Morelandc1635952021-04-01 16:20:47 +0000538TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000539 auto proc = createRpcTestSocketServerProcess(1);
540
541 IBinder* ptr = nullptr;
542 {
543 sp<IBinder> binder = new BBinder();
544 ptr = binder.get();
545 EXPECT_OK(proc.rootIface->holdBinder(binder));
546 }
547
548 sp<IBinder> held;
549 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
550
551 EXPECT_EQ(held.get(), ptr);
552
553 // stop holding binder, because we test to make sure references are cleaned
554 // up
555 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
556 // and flush ref counts
557 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
558}
559
560// START TESTS FOR LIMITATIONS OF SOCKET BINDER
561// These are behavioral differences form regular binder, where certain usecases
562// aren't supported.
563
Steven Morelandc1635952021-04-01 16:20:47 +0000564TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketConnections) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000565 auto proc1 = createRpcTestSocketServerProcess(1);
566 auto proc2 = createRpcTestSocketServerProcess(1);
567
568 sp<IBinder> outBinder;
569 EXPECT_EQ(INVALID_OPERATION,
570 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
571}
572
Steven Morelandc1635952021-04-01 16:20:47 +0000573TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000574 auto proc = createRpcTestSocketServerProcess(1);
575
576 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
577 sp<IBinder> outBinder;
578 EXPECT_EQ(INVALID_OPERATION,
579 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
580}
581
Steven Morelandc1635952021-04-01 16:20:47 +0000582TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000583 auto proc = createRpcTestSocketServerProcess(1);
584
585 // for historical reasons, IServiceManager interface only returns the
586 // exception code
587 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
588 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
589}
590
591// END TESTS FOR LIMITATIONS OF SOCKET BINDER
592
Steven Morelandc1635952021-04-01 16:20:47 +0000593TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000594 auto proc = createRpcTestSocketServerProcess(1);
595
596 sp<IBinder> outBinder;
597 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
598 EXPECT_EQ(proc.rootBinder, outBinder);
599}
600
Steven Morelandc1635952021-04-01 16:20:47 +0000601TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000602 auto proc = createRpcTestSocketServerProcess(1);
603
604 auto nastyNester = sp<MyBinderRpcTest>::make();
605 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
606
607 wp<IBinder> weak = nastyNester;
608 nastyNester = nullptr;
609 EXPECT_EQ(nullptr, weak.promote());
610}
611
Steven Morelandc1635952021-04-01 16:20:47 +0000612TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000613 auto proc = createRpcTestSocketServerProcess(1);
614
615 sp<IBinder> a;
616 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
617
618 sp<IBinder> b;
619 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
620
621 EXPECT_EQ(a, b);
622}
623
Steven Morelandc1635952021-04-01 16:20:47 +0000624TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000625 auto proc = createRpcTestSocketServerProcess(1);
626
627 sp<IBinder> a;
628 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
629 wp<IBinder> weak = a;
630 a = nullptr;
631
632 sp<IBinder> b;
633 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
634
635 // this is the wrong behavior, since BpBinder
636 // doesn't implement onIncStrongAttempted
637 // but make sure there is no crash
638 EXPECT_EQ(nullptr, weak.promote());
639
640 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
641
642 // In order to fix this:
643 // - need to have incStrongAttempted reflected across IPC boundary (wait for
644 // response to promote - round trip...)
645 // - sendOnLastWeakRef, to delete entries out of RpcState table
646 EXPECT_EQ(b, weak.promote());
647}
648
649#define expectSessions(expected, iface) \
650 do { \
651 int session; \
652 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
653 EXPECT_EQ(expected, session); \
654 } while (false)
655
Steven Morelandc1635952021-04-01 16:20:47 +0000656TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000657 auto proc = createRpcTestSocketServerProcess(1);
658
659 sp<IBinderRpcSession> session;
660 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
661 std::string out;
662 EXPECT_OK(session->getName(&out));
663 EXPECT_EQ("aoeu", out);
664
665 expectSessions(1, proc.rootIface);
666 session = nullptr;
667 expectSessions(0, proc.rootIface);
668}
669
Steven Morelandc1635952021-04-01 16:20:47 +0000670TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000671 auto proc = createRpcTestSocketServerProcess(1);
672
673 std::vector<sp<IBinderRpcSession>> sessions;
674
675 for (size_t i = 0; i < 15; i++) {
676 expectSessions(i, proc.rootIface);
677 sp<IBinderRpcSession> session;
678 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
679 sessions.push_back(session);
680 }
681 expectSessions(sessions.size(), proc.rootIface);
682 for (size_t i = 0; i < sessions.size(); i++) {
683 std::string out;
684 EXPECT_OK(sessions.at(i)->getName(&out));
685 EXPECT_EQ(std::to_string(i), out);
686 }
687 expectSessions(sessions.size(), proc.rootIface);
688
689 while (!sessions.empty()) {
690 sessions.pop_back();
691 expectSessions(sessions.size(), proc.rootIface);
692 }
693 expectSessions(0, proc.rootIface);
694}
695
696size_t epochMillis() {
697 using std::chrono::duration_cast;
698 using std::chrono::milliseconds;
699 using std::chrono::seconds;
700 using std::chrono::system_clock;
701 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
702}
703
Steven Morelandc1635952021-04-01 16:20:47 +0000704TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000705 constexpr size_t kNumThreads = 10;
706
707 auto proc = createRpcTestSocketServerProcess(kNumThreads);
708
709 EXPECT_OK(proc.rootIface->lock());
710
711 // block all but one thread taking locks
712 std::vector<std::thread> ts;
713 for (size_t i = 0; i < kNumThreads - 1; i++) {
714 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
715 }
716
717 usleep(100000); // give chance for calls on other threads
718
719 // other calls still work
720 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
721
722 constexpr size_t blockTimeMs = 500;
723 size_t epochMsBefore = epochMillis();
724 // after this, we should never see a response within this time
725 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
726
727 // this call should be blocked for blockTimeMs
728 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
729
730 size_t epochMsAfter = epochMillis();
731 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
732
733 for (auto& t : ts) t.join();
734}
735
Steven Morelandc1635952021-04-01 16:20:47 +0000736TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000737 constexpr size_t kNumThreads = 10;
738 constexpr size_t kNumCalls = kNumThreads + 3;
739 constexpr size_t kSleepMs = 500;
740
741 auto proc = createRpcTestSocketServerProcess(kNumThreads);
742
743 size_t epochMsBefore = epochMillis();
744
745 std::vector<std::thread> ts;
746 for (size_t i = 0; i < kNumCalls; i++) {
747 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
748 }
749
750 for (auto& t : ts) t.join();
751
752 size_t epochMsAfter = epochMillis();
753
754 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
755
756 // Potential flake, but make sure calls are handled in parallel.
757 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
758}
759
Steven Morelandc1635952021-04-01 16:20:47 +0000760TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000761 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 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000772 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000773 EXPECT_EQ(proc.rootBinder, out);
774 }
775 }));
776 }
777
778 for (auto& t : threads) t.join();
779}
780
Steven Morelandc6046982021-04-20 00:49:42 +0000781TEST_P(BinderRpc, OnewayStressTest) {
782 constexpr size_t kNumClientThreads = 10;
783 constexpr size_t kNumServerThreads = 10;
784 constexpr size_t kNumCalls = 100;
785
786 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
787
788 std::vector<std::thread> threads;
789 for (size_t i = 0; i < kNumClientThreads; i++) {
790 threads.push_back(std::thread([&] {
791 for (size_t j = 0; j < kNumCalls; j++) {
792 EXPECT_OK(proc.rootIface->sendString("a"));
793 }
794
795 // check threads are not stuck
796 EXPECT_OK(proc.rootIface->sleepMs(250));
797 }));
798 }
799
800 for (auto& t : threads) t.join();
801}
802
Steven Morelandc1635952021-04-01 16:20:47 +0000803TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000804 constexpr size_t kReallyLongTimeMs = 100;
805 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
806
807 // more than one thread, just so this doesn't deadlock
808 auto proc = createRpcTestSocketServerProcess(2);
809
810 size_t epochMsBefore = epochMillis();
811
812 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
813
814 size_t epochMsAfter = epochMillis();
815 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
816}
817
Steven Morelandc1635952021-04-01 16:20:47 +0000818TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000819 constexpr size_t kNumSleeps = 10;
820 constexpr size_t kNumExtraServerThreads = 4;
821 constexpr size_t kSleepMs = 50;
822
823 // make sure calls to the same object happen on the same thread
824 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
825
826 EXPECT_OK(proc.rootIface->lock());
827
828 for (size_t i = 0; i < kNumSleeps; i++) {
829 // these should be processed serially
830 proc.rootIface->sleepMsAsync(kSleepMs);
831 }
832 // should also be processesed serially
833 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
834
835 size_t epochMsBefore = epochMillis();
836 EXPECT_OK(proc.rootIface->lockUnlock());
837 size_t epochMsAfter = epochMillis();
838
839 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
840}
841
Steven Morelandc1635952021-04-01 16:20:47 +0000842TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000843 for (bool doDeathCleanup : {true, false}) {
844 auto proc = createRpcTestSocketServerProcess(1);
845
846 // make sure there is some state during crash
847 // 1. we hold their binder
848 sp<IBinderRpcSession> session;
849 EXPECT_OK(proc.rootIface->openSession("happy", &session));
850 // 2. they hold our binder
851 sp<IBinder> binder = new BBinder();
852 EXPECT_OK(proc.rootIface->holdBinder(binder));
853
854 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
855 << "Do death cleanup: " << doDeathCleanup;
856
857 proc.proc.expectInvalid = true;
858 }
859}
860
Steven Moreland37aff182021-03-26 02:04:16 +0000861TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
862 auto proc = createRpcTestSocketServerProcess(1);
863
864 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
865 ASSERT_NE(binder, nullptr);
866
867 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
868}
869
870TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
871 auto proc = createRpcTestSocketServerProcess(1);
872
873 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
874 ASSERT_NE(binder, nullptr);
875
876 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
877 ASSERT_NE(ndkBinder, nullptr);
878
879 std::string out;
880 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
881 ASSERT_TRUE(status.isOk()) << status.getDescription();
882 ASSERT_EQ("aoeuaoeu", out);
883}
884
Steven Moreland5553ac42020-11-11 02:14:45 +0000885ssize_t countFds() {
886 DIR* dir = opendir("/proc/self/fd/");
887 if (dir == nullptr) return -1;
888 ssize_t ret = 0;
889 dirent* ent;
890 while ((ent = readdir(dir)) != nullptr) ret++;
891 closedir(dir);
892 return ret;
893}
894
Steven Morelandc1635952021-04-01 16:20:47 +0000895TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000896 ssize_t beforeFds = countFds();
897 ASSERT_GE(beforeFds, 0);
898 {
899 auto proc = createRpcTestSocketServerProcess(10);
900 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
901 }
902 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
903}
904
Steven Morelandc1635952021-04-01 16:20:47 +0000905INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700906 ::testing::ValuesIn({
907 SocketType::UNIX,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000908#ifdef __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700909 SocketType::VSOCK,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000910#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700911 SocketType::INET,
912 }),
Steven Morelandf6ec4632021-04-01 16:20:47 +0000913 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +0000914
915} // namespace android
916
917int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000918 ::testing::InitGoogleTest(&argc, argv);
919 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
920 return RUN_ALL_TESTS();
921}