blob: d23df8eaecd412256b7b12bc1bf8f90ba29a23c1 [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:
Steven Moreland611d15f2021-05-01 01:28:27 +000081 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +000082
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 {
Steven Moreland611d15f2021-05-01 01:28:27 +000092 sp<RpcServer> spServer = server.promote();
93 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +000094 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
95 }
Steven Moreland611d15f2021-05-01 01:28:27 +000096 size_t count = 0;
97 for (auto connection : spServer->listConnections()) {
98 count += connection->state()->countBinders();
Steven Moreland5553ac42020-11-11 02:14:45 +000099 }
Steven Moreland611d15f2021-05-01 01:28:27 +0000100 // help debugging if we don't have one binder (this call is always made
101 // in this test when exactly one binder is held, which is held only to
102 // call this method - all other binders should be cleaned up)
103 if (count != 1) {
104 for (auto connection : spServer->listConnections()) {
105 connection->state()->dump();
106 }
107 }
108 *out = count;
Steven Moreland5553ac42020-11-11 02:14:45 +0000109 return Status::ok();
110 }
111 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
112 if (binder == nullptr) {
113 std::cout << "Received null binder!" << std::endl;
114 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
115 }
116 *out = binder->pingBinder();
117 return Status::ok();
118 }
119 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
120 *out = binder;
121 return Status::ok();
122 }
123 static sp<IBinder> mHeldBinder;
124 Status holdBinder(const sp<IBinder>& binder) override {
125 mHeldBinder = binder;
126 return Status::ok();
127 }
128 Status getHeldBinder(sp<IBinder>* held) override {
129 *held = mHeldBinder;
130 return Status::ok();
131 }
132 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
133 if (count <= 0) return Status::ok();
134 return binder->nestMe(this, count - 1);
135 }
136 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
137 static sp<IBinder> binder = new BBinder;
138 *out = binder;
139 return Status::ok();
140 }
141 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
142 *out = new MyBinderRpcSession(name);
143 return Status::ok();
144 }
145 Status getNumOpenSessions(int32_t* out) override {
146 *out = MyBinderRpcSession::gNum;
147 return Status::ok();
148 }
149
150 std::mutex blockMutex;
151 Status lock() override {
152 blockMutex.lock();
153 return Status::ok();
154 }
155 Status unlockInMsAsync(int32_t ms) override {
156 usleep(ms * 1000);
157 blockMutex.unlock();
158 return Status::ok();
159 }
160 Status lockUnlock() override {
161 std::lock_guard<std::mutex> _l(blockMutex);
162 return Status::ok();
163 }
164
165 Status sleepMs(int32_t ms) override {
166 usleep(ms * 1000);
167 return Status::ok();
168 }
169
170 Status sleepMsAsync(int32_t ms) override {
171 // In-process binder calls are asynchronous, but the call to this method
172 // is synchronous wrt its client. This in/out-process threading model
173 // diffentiation is a classic binder leaky abstraction (for better or
174 // worse) and is preserved here the way binder sockets plugs itself
175 // into BpBinder, as nothing is changed at the higher levels
176 // (IInterface) which result in this behavior.
177 return sleepMs(ms);
178 }
179
180 Status die(bool cleanup) override {
181 if (cleanup) {
182 exit(1);
183 } else {
184 _exit(1);
185 }
186 }
187};
188sp<IBinder> MyBinderRpcTest::mHeldBinder;
189
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700190class Pipe {
191public:
192 Pipe() { CHECK(android::base::Pipe(&mRead, &mWrite)); }
193 Pipe(Pipe&&) = default;
194 android::base::borrowed_fd readEnd() { return mRead; }
195 android::base::borrowed_fd writeEnd() { return mWrite; }
196
197private:
198 android::base::unique_fd mRead;
199 android::base::unique_fd mWrite;
200};
201
Steven Moreland5553ac42020-11-11 02:14:45 +0000202class Process {
203public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700204 Process(Process&&) = default;
205 Process(const std::function<void(Pipe*)>& f) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000206 if (0 == (mPid = fork())) {
207 // racey: assume parent doesn't crash before this is set
208 prctl(PR_SET_PDEATHSIG, SIGHUP);
209
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700210 f(&mPipe);
Steven Moreland5553ac42020-11-11 02:14:45 +0000211 }
212 }
213 ~Process() {
214 if (mPid != 0) {
215 kill(mPid, SIGKILL);
216 }
217 }
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700218 Pipe* getPipe() { return &mPipe; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000219
220private:
221 pid_t mPid = 0;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700222 Pipe mPipe;
Steven Moreland5553ac42020-11-11 02:14:45 +0000223};
224
225static std::string allocateSocketAddress() {
226 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000227 std::string temp = getenv("TMPDIR") ?: "/tmp";
228 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000229};
230
231struct ProcessConnection {
232 // reference to process hosting a socket server
233 Process host;
234
235 // client connection object associated with other process
236 sp<RpcConnection> connection;
237
238 // pre-fetched root object
239 sp<IBinder> rootBinder;
240
241 // whether connection should be invalidated by end of run
242 bool expectInvalid = false;
243
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700244 ProcessConnection(ProcessConnection&&) = default;
Steven Moreland5553ac42020-11-11 02:14:45 +0000245 ~ProcessConnection() {
246 rootBinder = nullptr;
247 EXPECT_NE(nullptr, connection);
248 EXPECT_NE(nullptr, connection->state());
249 EXPECT_EQ(0, connection->state()->countBinders()) << (connection->state()->dump(), "dump:");
250
251 wp<RpcConnection> weakConnection = connection;
252 connection = nullptr;
253 EXPECT_EQ(nullptr, weakConnection.promote()) << "Leaked connection";
254 }
255};
256
Steven Moreland5553ac42020-11-11 02:14:45 +0000257// Process connection where the process hosts IBinderRpcTest, the server used
258// for most testing here
259struct BinderRpcTestProcessConnection {
260 ProcessConnection proc;
261
262 // pre-fetched root object
263 sp<IBinder> rootBinder;
264
265 // pre-casted root object
266 sp<IBinderRpcTest> rootIface;
267
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700268 BinderRpcTestProcessConnection(BinderRpcTestProcessConnection&&) = default;
Steven Moreland5553ac42020-11-11 02:14:45 +0000269 ~BinderRpcTestProcessConnection() {
270 if (!proc.expectInvalid) {
271 int32_t remoteBinders = 0;
272 EXPECT_OK(rootIface->countBinders(&remoteBinders));
273 // should only be the root binder object, iface
274 EXPECT_EQ(remoteBinders, 1);
275 }
276
277 rootIface = nullptr;
278 rootBinder = nullptr;
279 }
280};
281
Steven Morelandc1635952021-04-01 16:20:47 +0000282enum class SocketType {
283 UNIX,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000284#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000285 VSOCK,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000286#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700287 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000288};
289static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
290 switch (info.param) {
291 case SocketType::UNIX:
292 return "unix_domain_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000293#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000294 case SocketType::VSOCK:
295 return "vm_socket";
Steven Morelandf6ec4632021-04-01 16:20:47 +0000296#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700297 case SocketType::INET:
298 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000299 default:
300 LOG_ALWAYS_FATAL("Unknown socket type");
301 return "";
302 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000303}
Steven Morelandc1635952021-04-01 16:20:47 +0000304class BinderRpc : public ::testing::TestWithParam<SocketType> {
305public:
306 // This creates a new process serving an interface on a certain number of
307 // threads.
308 ProcessConnection createRpcTestSocketServerProcess(
Steven Moreland611d15f2021-05-01 01:28:27 +0000309 size_t numThreads, const std::function<void(const sp<RpcServer>&)>& configure) {
Steven Morelandc1635952021-04-01 16:20:47 +0000310 SocketType socketType = GetParam();
311
312 std::string addr = allocateSocketAddress();
313 unlink(addr.c_str());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700314 static unsigned int vsockPort = 3456;
315 vsockPort++;
Steven Morelandc1635952021-04-01 16:20:47 +0000316
317 auto ret = ProcessConnection{
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700318 .host = Process([&](Pipe* pipe) {
Steven Morelandc1635952021-04-01 16:20:47 +0000319 sp<RpcServer> server = RpcServer::make();
320
321 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Morelandf137de92021-04-24 01:54:26 +0000322 server->setMaxThreads(numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000323
Steven Morelandc1635952021-04-01 16:20:47 +0000324 switch (socketType) {
325 case SocketType::UNIX:
Steven Moreland611d15f2021-05-01 01:28:27 +0000326 CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000327 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000328#ifdef __BIONIC__
Steven Morelandc1635952021-04-01 16:20:47 +0000329 case SocketType::VSOCK:
Steven Moreland611d15f2021-05-01 01:28:27 +0000330 CHECK(server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000331 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000332#endif // __BIONIC__
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700333 case SocketType::INET: {
334 unsigned int outPort = 0;
Steven Moreland611d15f2021-05-01 01:28:27 +0000335 CHECK(server->setupInetServer(0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700336 CHECK_NE(0, outPort);
337 CHECK(android::base::WriteFully(pipe->writeEnd(), &outPort,
338 sizeof(outPort)));
Yifan Hong0d2bd112021-04-13 17:38:36 -0700339 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700340 }
Steven Morelandc1635952021-04-01 16:20:47 +0000341 default:
342 LOG_ALWAYS_FATAL("Unknown socket type");
343 }
344
Steven Moreland611d15f2021-05-01 01:28:27 +0000345 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000346
Steven Morelandf137de92021-04-24 01:54:26 +0000347 server->join();
Steven Morelandc1635952021-04-01 16:20:47 +0000348 }),
349 .connection = RpcConnection::make(),
350 };
351
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700352 unsigned int inetPort = 0;
353 if (socketType == SocketType::INET) {
354 CHECK(android::base::ReadFully(ret.host.getPipe()->readEnd(), &inetPort,
355 sizeof(inetPort)));
356 CHECK_NE(0, inetPort);
357 }
358
Steven Morelandc1635952021-04-01 16:20:47 +0000359 // create remainder of connections
Steven Morelandf137de92021-04-24 01:54:26 +0000360 for (size_t tries = 0; tries < 10; tries++) {
361 usleep(10000);
362 switch (socketType) {
363 case SocketType::UNIX:
364 if (ret.connection->setupUnixDomainClient(addr.c_str())) goto success;
365 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000366#ifdef __BIONIC__
Steven Morelandf137de92021-04-24 01:54:26 +0000367 case SocketType::VSOCK:
368 if (ret.connection->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
369 break;
Steven Morelandf6ec4632021-04-01 16:20:47 +0000370#endif // __BIONIC__
Steven Morelandf137de92021-04-24 01:54:26 +0000371 case SocketType::INET:
372 if (ret.connection->setupInetClient("127.0.0.1", inetPort)) goto success;
373 break;
374 default:
375 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000376 }
Steven Morelandc1635952021-04-01 16:20:47 +0000377 }
Steven Morelandf137de92021-04-24 01:54:26 +0000378 LOG_ALWAYS_FATAL("Could not connect");
379 success:
Steven Morelandc1635952021-04-01 16:20:47 +0000380
381 ret.rootBinder = ret.connection->getRootObject();
382 return ret;
383 }
384
385 BinderRpcTestProcessConnection createRpcTestSocketServerProcess(size_t numThreads) {
386 BinderRpcTestProcessConnection ret{
387 .proc = createRpcTestSocketServerProcess(numThreads,
Steven Moreland611d15f2021-05-01 01:28:27 +0000388 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000389 sp<MyBinderRpcTest> service =
390 new MyBinderRpcTest;
391 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000392 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000393 }),
394 };
395
396 ret.rootBinder = ret.proc.rootBinder;
397 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
398
399 return ret;
400 }
401};
402
403TEST_P(BinderRpc, RootObjectIsNull) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000404 auto proc = createRpcTestSocketServerProcess(1, [](const sp<RpcServer>& server) {
405 // this is the default, but to be explicit
406 server->setRootObject(nullptr);
407 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000408
409 // retrieved by getRootObject when process is created above
410 EXPECT_EQ(nullptr, proc.rootBinder);
411
412 // make sure we can retrieve it again (process doesn't crash)
413 EXPECT_EQ(nullptr, proc.connection->getRootObject());
414}
415
Steven Morelandc1635952021-04-01 16:20:47 +0000416TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000417 auto proc = createRpcTestSocketServerProcess(1);
418 ASSERT_NE(proc.rootBinder, nullptr);
419 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
420}
421
Steven Moreland4cf688f2021-03-31 01:48:58 +0000422TEST_P(BinderRpc, GetInterfaceDescriptor) {
423 auto proc = createRpcTestSocketServerProcess(1);
424 ASSERT_NE(proc.rootBinder, nullptr);
425 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
426}
427
Steven Morelandc1635952021-04-01 16:20:47 +0000428TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000429 auto proc = createRpcTestSocketServerProcess(1);
430 Parcel data;
431 Parcel reply;
432 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
433}
434
Steven Moreland67753c32021-04-02 18:45:19 +0000435TEST_P(BinderRpc, AppendSeparateFormats) {
436 auto proc = createRpcTestSocketServerProcess(1);
437
438 Parcel p1;
439 p1.markForBinder(proc.rootBinder);
440 p1.writeInt32(3);
441
442 Parcel p2;
443
444 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
445 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
446}
447
Steven Morelandc1635952021-04-01 16:20:47 +0000448TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000449 auto proc = createRpcTestSocketServerProcess(1);
450 Parcel data;
451 data.markForBinder(proc.rootBinder);
452 Parcel reply;
453 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
454}
455
Steven Morelandc1635952021-04-01 16:20:47 +0000456TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000457 auto proc = createRpcTestSocketServerProcess(1);
458 EXPECT_OK(proc.rootIface->sendString("asdf"));
459}
460
Steven Morelandc1635952021-04-01 16:20:47 +0000461TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000462 auto proc = createRpcTestSocketServerProcess(1);
463 std::string doubled;
464 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
465 EXPECT_EQ("cool cool ", doubled);
466}
467
Steven Morelandc1635952021-04-01 16:20:47 +0000468TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000469 auto proc = createRpcTestSocketServerProcess(1);
470 std::string single = std::string(1024, 'a');
471 std::string doubled;
472 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
473 EXPECT_EQ(single + single, doubled);
474}
475
Steven Morelandc1635952021-04-01 16:20:47 +0000476TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000477 auto proc = createRpcTestSocketServerProcess(1);
478
479 int32_t pingResult;
480 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
481 EXPECT_EQ(OK, pingResult);
482
483 EXPECT_EQ(0, MyBinderRpcSession::gNum);
484}
485
Steven Morelandc1635952021-04-01 16:20:47 +0000486TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000487 auto proc = createRpcTestSocketServerProcess(1);
488
489 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
490 sp<IBinder> outBinder;
491 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
492 EXPECT_EQ(inBinder, outBinder);
493
494 wp<IBinder> weak = inBinder;
495 inBinder = nullptr;
496 outBinder = nullptr;
497
498 // Force reading a reply, to process any pending dec refs from the other
499 // process (the other process will process dec refs there before processing
500 // the ping here).
501 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
502
503 EXPECT_EQ(nullptr, weak.promote());
504
505 EXPECT_EQ(0, MyBinderRpcSession::gNum);
506}
507
Steven Morelandc1635952021-04-01 16:20:47 +0000508TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000509 auto proc = createRpcTestSocketServerProcess(1);
510
511 sp<IBinderRpcSession> session;
512 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
513
514 sp<IBinder> inBinder = IInterface::asBinder(session);
515 sp<IBinder> outBinder;
516 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
517 EXPECT_EQ(inBinder, outBinder);
518
519 wp<IBinder> weak = inBinder;
520 session = nullptr;
521 inBinder = nullptr;
522 outBinder = nullptr;
523
524 // Force reading a reply, to process any pending dec refs from the other
525 // process (the other process will process dec refs there before processing
526 // the ping here).
527 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
528
529 EXPECT_EQ(nullptr, weak.promote());
530}
531
Steven Morelandc1635952021-04-01 16:20:47 +0000532TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000533 auto proc = createRpcTestSocketServerProcess(1);
534
535 sp<IBinder> outBinder;
536 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
537 EXPECT_EQ(nullptr, outBinder);
538}
539
Steven Morelandc1635952021-04-01 16:20:47 +0000540TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000541 auto proc = createRpcTestSocketServerProcess(1);
542
543 IBinder* ptr = nullptr;
544 {
545 sp<IBinder> binder = new BBinder();
546 ptr = binder.get();
547 EXPECT_OK(proc.rootIface->holdBinder(binder));
548 }
549
550 sp<IBinder> held;
551 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
552
553 EXPECT_EQ(held.get(), ptr);
554
555 // stop holding binder, because we test to make sure references are cleaned
556 // up
557 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
558 // and flush ref counts
559 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
560}
561
562// START TESTS FOR LIMITATIONS OF SOCKET BINDER
563// These are behavioral differences form regular binder, where certain usecases
564// aren't supported.
565
Steven Morelandc1635952021-04-01 16:20:47 +0000566TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketConnections) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000567 auto proc1 = createRpcTestSocketServerProcess(1);
568 auto proc2 = createRpcTestSocketServerProcess(1);
569
570 sp<IBinder> outBinder;
571 EXPECT_EQ(INVALID_OPERATION,
572 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
573}
574
Steven Morelandc1635952021-04-01 16:20:47 +0000575TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000576 auto proc = createRpcTestSocketServerProcess(1);
577
578 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
579 sp<IBinder> outBinder;
580 EXPECT_EQ(INVALID_OPERATION,
581 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
582}
583
Steven Morelandc1635952021-04-01 16:20:47 +0000584TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000585 auto proc = createRpcTestSocketServerProcess(1);
586
587 // for historical reasons, IServiceManager interface only returns the
588 // exception code
589 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
590 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
591}
592
593// END TESTS FOR LIMITATIONS OF SOCKET BINDER
594
Steven Morelandc1635952021-04-01 16:20:47 +0000595TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000596 auto proc = createRpcTestSocketServerProcess(1);
597
598 sp<IBinder> outBinder;
599 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
600 EXPECT_EQ(proc.rootBinder, outBinder);
601}
602
Steven Morelandc1635952021-04-01 16:20:47 +0000603TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000604 auto proc = createRpcTestSocketServerProcess(1);
605
606 auto nastyNester = sp<MyBinderRpcTest>::make();
607 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
608
609 wp<IBinder> weak = nastyNester;
610 nastyNester = nullptr;
611 EXPECT_EQ(nullptr, weak.promote());
612}
613
Steven Morelandc1635952021-04-01 16:20:47 +0000614TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000615 auto proc = createRpcTestSocketServerProcess(1);
616
617 sp<IBinder> a;
618 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
619
620 sp<IBinder> b;
621 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
622
623 EXPECT_EQ(a, b);
624}
625
Steven Morelandc1635952021-04-01 16:20:47 +0000626TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000627 auto proc = createRpcTestSocketServerProcess(1);
628
629 sp<IBinder> a;
630 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
631 wp<IBinder> weak = a;
632 a = nullptr;
633
634 sp<IBinder> b;
635 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
636
637 // this is the wrong behavior, since BpBinder
638 // doesn't implement onIncStrongAttempted
639 // but make sure there is no crash
640 EXPECT_EQ(nullptr, weak.promote());
641
642 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
643
644 // In order to fix this:
645 // - need to have incStrongAttempted reflected across IPC boundary (wait for
646 // response to promote - round trip...)
647 // - sendOnLastWeakRef, to delete entries out of RpcState table
648 EXPECT_EQ(b, weak.promote());
649}
650
651#define expectSessions(expected, iface) \
652 do { \
653 int session; \
654 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
655 EXPECT_EQ(expected, session); \
656 } while (false)
657
Steven Morelandc1635952021-04-01 16:20:47 +0000658TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000659 auto proc = createRpcTestSocketServerProcess(1);
660
661 sp<IBinderRpcSession> session;
662 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
663 std::string out;
664 EXPECT_OK(session->getName(&out));
665 EXPECT_EQ("aoeu", out);
666
667 expectSessions(1, proc.rootIface);
668 session = nullptr;
669 expectSessions(0, proc.rootIface);
670}
671
Steven Morelandc1635952021-04-01 16:20:47 +0000672TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000673 auto proc = createRpcTestSocketServerProcess(1);
674
675 std::vector<sp<IBinderRpcSession>> sessions;
676
677 for (size_t i = 0; i < 15; i++) {
678 expectSessions(i, proc.rootIface);
679 sp<IBinderRpcSession> session;
680 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
681 sessions.push_back(session);
682 }
683 expectSessions(sessions.size(), proc.rootIface);
684 for (size_t i = 0; i < sessions.size(); i++) {
685 std::string out;
686 EXPECT_OK(sessions.at(i)->getName(&out));
687 EXPECT_EQ(std::to_string(i), out);
688 }
689 expectSessions(sessions.size(), proc.rootIface);
690
691 while (!sessions.empty()) {
692 sessions.pop_back();
693 expectSessions(sessions.size(), proc.rootIface);
694 }
695 expectSessions(0, proc.rootIface);
696}
697
698size_t epochMillis() {
699 using std::chrono::duration_cast;
700 using std::chrono::milliseconds;
701 using std::chrono::seconds;
702 using std::chrono::system_clock;
703 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
704}
705
Steven Morelandc1635952021-04-01 16:20:47 +0000706TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000707 constexpr size_t kNumThreads = 10;
708
709 auto proc = createRpcTestSocketServerProcess(kNumThreads);
710
711 EXPECT_OK(proc.rootIface->lock());
712
713 // block all but one thread taking locks
714 std::vector<std::thread> ts;
715 for (size_t i = 0; i < kNumThreads - 1; i++) {
716 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
717 }
718
719 usleep(100000); // give chance for calls on other threads
720
721 // other calls still work
722 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
723
724 constexpr size_t blockTimeMs = 500;
725 size_t epochMsBefore = epochMillis();
726 // after this, we should never see a response within this time
727 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
728
729 // this call should be blocked for blockTimeMs
730 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
731
732 size_t epochMsAfter = epochMillis();
733 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
734
735 for (auto& t : ts) t.join();
736}
737
Steven Morelandc1635952021-04-01 16:20:47 +0000738TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000739 constexpr size_t kNumThreads = 10;
740 constexpr size_t kNumCalls = kNumThreads + 3;
741 constexpr size_t kSleepMs = 500;
742
743 auto proc = createRpcTestSocketServerProcess(kNumThreads);
744
745 size_t epochMsBefore = epochMillis();
746
747 std::vector<std::thread> ts;
748 for (size_t i = 0; i < kNumCalls; i++) {
749 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
750 }
751
752 for (auto& t : ts) t.join();
753
754 size_t epochMsAfter = epochMillis();
755
756 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
757
758 // Potential flake, but make sure calls are handled in parallel.
759 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
760}
761
Steven Morelandc1635952021-04-01 16:20:47 +0000762TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000763 constexpr size_t kNumClientThreads = 10;
764 constexpr size_t kNumServerThreads = 10;
765 constexpr size_t kNumCalls = 100;
766
767 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
768
769 std::vector<std::thread> threads;
770 for (size_t i = 0; i < kNumClientThreads; i++) {
771 threads.push_back(std::thread([&] {
772 for (size_t j = 0; j < kNumCalls; j++) {
773 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000774 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000775 EXPECT_EQ(proc.rootBinder, out);
776 }
777 }));
778 }
779
780 for (auto& t : threads) t.join();
781}
782
Steven Morelandc6046982021-04-20 00:49:42 +0000783TEST_P(BinderRpc, OnewayStressTest) {
784 constexpr size_t kNumClientThreads = 10;
785 constexpr size_t kNumServerThreads = 10;
786 constexpr size_t kNumCalls = 100;
787
788 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
789
790 std::vector<std::thread> threads;
791 for (size_t i = 0; i < kNumClientThreads; i++) {
792 threads.push_back(std::thread([&] {
793 for (size_t j = 0; j < kNumCalls; j++) {
794 EXPECT_OK(proc.rootIface->sendString("a"));
795 }
796
797 // check threads are not stuck
798 EXPECT_OK(proc.rootIface->sleepMs(250));
799 }));
800 }
801
802 for (auto& t : threads) t.join();
803}
804
Steven Morelandc1635952021-04-01 16:20:47 +0000805TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000806 constexpr size_t kReallyLongTimeMs = 100;
807 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
808
809 // more than one thread, just so this doesn't deadlock
810 auto proc = createRpcTestSocketServerProcess(2);
811
812 size_t epochMsBefore = epochMillis();
813
814 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
815
816 size_t epochMsAfter = epochMillis();
817 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
818}
819
Steven Morelandc1635952021-04-01 16:20:47 +0000820TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000821 constexpr size_t kNumSleeps = 10;
822 constexpr size_t kNumExtraServerThreads = 4;
823 constexpr size_t kSleepMs = 50;
824
825 // make sure calls to the same object happen on the same thread
826 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
827
828 EXPECT_OK(proc.rootIface->lock());
829
830 for (size_t i = 0; i < kNumSleeps; i++) {
831 // these should be processed serially
832 proc.rootIface->sleepMsAsync(kSleepMs);
833 }
834 // should also be processesed serially
835 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
836
837 size_t epochMsBefore = epochMillis();
838 EXPECT_OK(proc.rootIface->lockUnlock());
839 size_t epochMsAfter = epochMillis();
840
841 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
842}
843
Steven Morelandc1635952021-04-01 16:20:47 +0000844TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000845 for (bool doDeathCleanup : {true, false}) {
846 auto proc = createRpcTestSocketServerProcess(1);
847
848 // make sure there is some state during crash
849 // 1. we hold their binder
850 sp<IBinderRpcSession> session;
851 EXPECT_OK(proc.rootIface->openSession("happy", &session));
852 // 2. they hold our binder
853 sp<IBinder> binder = new BBinder();
854 EXPECT_OK(proc.rootIface->holdBinder(binder));
855
856 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
857 << "Do death cleanup: " << doDeathCleanup;
858
859 proc.proc.expectInvalid = true;
860 }
861}
862
Steven Moreland37aff182021-03-26 02:04:16 +0000863TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
864 auto proc = createRpcTestSocketServerProcess(1);
865
866 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
867 ASSERT_NE(binder, nullptr);
868
869 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
870}
871
872TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
873 auto proc = createRpcTestSocketServerProcess(1);
874
875 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
876 ASSERT_NE(binder, nullptr);
877
878 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
879 ASSERT_NE(ndkBinder, nullptr);
880
881 std::string out;
882 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
883 ASSERT_TRUE(status.isOk()) << status.getDescription();
884 ASSERT_EQ("aoeuaoeu", out);
885}
886
Steven Moreland5553ac42020-11-11 02:14:45 +0000887ssize_t countFds() {
888 DIR* dir = opendir("/proc/self/fd/");
889 if (dir == nullptr) return -1;
890 ssize_t ret = 0;
891 dirent* ent;
892 while ((ent = readdir(dir)) != nullptr) ret++;
893 closedir(dir);
894 return ret;
895}
896
Steven Morelandc1635952021-04-01 16:20:47 +0000897TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000898 ssize_t beforeFds = countFds();
899 ASSERT_GE(beforeFds, 0);
900 {
901 auto proc = createRpcTestSocketServerProcess(10);
902 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
903 }
904 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
905}
906
Steven Morelandc1635952021-04-01 16:20:47 +0000907INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700908 ::testing::ValuesIn({
909 SocketType::UNIX,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000910#ifdef __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700911 SocketType::VSOCK,
Steven Morelandf6ec4632021-04-01 16:20:47 +0000912#endif // __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700913 SocketType::INET,
914 }),
Steven Morelandf6ec4632021-04-01 16:20:47 +0000915 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +0000916
917} // namespace android
918
919int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000920 ::testing::InitGoogleTest(&argc, argv);
921 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
922 return RUN_ALL_TESTS();
923}