blob: fb0ffdb19cd1977e40d2c6a739379253340685dd [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>
Steven Moreland5553ac42020-11-11 02:14:45 +000028#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000029#include <binder/RpcSession.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000030#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 Morelandc1635952021-04-01 16:20:47 +000037#include <sys/prctl.h>
38#include <unistd.h>
39
Steven Morelandbd5002b2021-05-04 23:12:56 +000040#include "../RpcState.h" // for debugging
41#include "../vm_sockets.h" // for VMADDR_*
Steven Moreland5553ac42020-11-11 02:14:45 +000042
Yifan Hong1a235852021-05-13 16:07:47 -070043using namespace std::chrono_literals;
44
Steven Moreland5553ac42020-11-11 02:14:45 +000045namespace android {
46
Steven Moreland1fda67b2021-04-02 18:35:50 +000047TEST(BinderRpcParcel, EntireParcelFormatted) {
48 Parcel p;
49 p.writeInt32(3);
50
51 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
52}
53
Yifan Hong00aeb762021-05-12 17:07:36 -070054TEST(BinderRpc, SetExternalServer) {
55 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
56 int sinkFd = sink.get();
57 auto server = RpcServer::make();
58 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
59 ASSERT_FALSE(server->hasServer());
60 ASSERT_TRUE(server->setupExternalServer(std::move(sink)));
61 ASSERT_TRUE(server->hasServer());
62 base::unique_fd retrieved = server->releaseServer();
63 ASSERT_FALSE(server->hasServer());
64 ASSERT_EQ(sinkFd, retrieved.get());
65}
66
Steven Moreland5553ac42020-11-11 02:14:45 +000067using android::binder::Status;
68
69#define EXPECT_OK(status) \
70 do { \
71 Status stat = (status); \
72 EXPECT_TRUE(stat.isOk()) << stat; \
73 } while (false)
74
75class MyBinderRpcSession : public BnBinderRpcSession {
76public:
77 static std::atomic<int32_t> gNum;
78
79 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
80 Status getName(std::string* name) override {
81 *name = mName;
82 return Status::ok();
83 }
84 ~MyBinderRpcSession() { gNum--; }
85
86private:
87 std::string mName;
88};
89std::atomic<int32_t> MyBinderRpcSession::gNum;
90
91class MyBinderRpcTest : public BnBinderRpcTest {
92public:
Steven Moreland611d15f2021-05-01 01:28:27 +000093 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +000094
95 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +000096 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +000097 return Status::ok();
98 }
99 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000100 *strstr = str + str;
101 return Status::ok();
102 }
Steven Moreland736664b2021-05-01 04:27:25 +0000103 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000104 sp<RpcServer> spServer = server.promote();
105 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000106 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
107 }
Steven Moreland736664b2021-05-01 04:27:25 +0000108 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000109 for (auto session : spServer->listSessions()) {
110 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000111 if (count != 1) {
112 // this is called when there is only one binder held remaining,
113 // so to aid debugging
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000114 session->state()->dump();
Steven Moreland611d15f2021-05-01 01:28:27 +0000115 }
Steven Moreland736664b2021-05-01 04:27:25 +0000116 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000117 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000118 return Status::ok();
119 }
120 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
121 if (binder == nullptr) {
122 std::cout << "Received null binder!" << std::endl;
123 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
124 }
125 *out = binder->pingBinder();
126 return Status::ok();
127 }
128 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
129 *out = binder;
130 return Status::ok();
131 }
132 static sp<IBinder> mHeldBinder;
133 Status holdBinder(const sp<IBinder>& binder) override {
134 mHeldBinder = binder;
135 return Status::ok();
136 }
137 Status getHeldBinder(sp<IBinder>* held) override {
138 *held = mHeldBinder;
139 return Status::ok();
140 }
141 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
142 if (count <= 0) return Status::ok();
143 return binder->nestMe(this, count - 1);
144 }
145 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
146 static sp<IBinder> binder = new BBinder;
147 *out = binder;
148 return Status::ok();
149 }
150 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
151 *out = new MyBinderRpcSession(name);
152 return Status::ok();
153 }
154 Status getNumOpenSessions(int32_t* out) override {
155 *out = MyBinderRpcSession::gNum;
156 return Status::ok();
157 }
158
159 std::mutex blockMutex;
160 Status lock() override {
161 blockMutex.lock();
162 return Status::ok();
163 }
164 Status unlockInMsAsync(int32_t ms) override {
165 usleep(ms * 1000);
166 blockMutex.unlock();
167 return Status::ok();
168 }
169 Status lockUnlock() override {
170 std::lock_guard<std::mutex> _l(blockMutex);
171 return Status::ok();
172 }
173
174 Status sleepMs(int32_t ms) override {
175 usleep(ms * 1000);
176 return Status::ok();
177 }
178
179 Status sleepMsAsync(int32_t ms) override {
180 // In-process binder calls are asynchronous, but the call to this method
181 // is synchronous wrt its client. This in/out-process threading model
182 // diffentiation is a classic binder leaky abstraction (for better or
183 // worse) and is preserved here the way binder sockets plugs itself
184 // into BpBinder, as nothing is changed at the higher levels
185 // (IInterface) which result in this behavior.
186 return sleepMs(ms);
187 }
188
189 Status die(bool cleanup) override {
190 if (cleanup) {
191 exit(1);
192 } else {
193 _exit(1);
194 }
195 }
196};
197sp<IBinder> MyBinderRpcTest::mHeldBinder;
198
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700199class Pipe {
200public:
201 Pipe() { CHECK(android::base::Pipe(&mRead, &mWrite)); }
202 Pipe(Pipe&&) = default;
203 android::base::borrowed_fd readEnd() { return mRead; }
204 android::base::borrowed_fd writeEnd() { return mWrite; }
205
206private:
207 android::base::unique_fd mRead;
208 android::base::unique_fd mWrite;
209};
210
Steven Moreland5553ac42020-11-11 02:14:45 +0000211class Process {
212public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700213 Process(Process&&) = default;
214 Process(const std::function<void(Pipe*)>& f) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000215 if (0 == (mPid = fork())) {
216 // racey: assume parent doesn't crash before this is set
217 prctl(PR_SET_PDEATHSIG, SIGHUP);
218
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700219 f(&mPipe);
Steven Moreland5553ac42020-11-11 02:14:45 +0000220 }
221 }
222 ~Process() {
223 if (mPid != 0) {
224 kill(mPid, SIGKILL);
225 }
226 }
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700227 Pipe* getPipe() { return &mPipe; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000228
229private:
230 pid_t mPid = 0;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700231 Pipe mPipe;
Steven Moreland5553ac42020-11-11 02:14:45 +0000232};
233
234static std::string allocateSocketAddress() {
235 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000236 std::string temp = getenv("TMPDIR") ?: "/tmp";
237 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000238};
239
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000240struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000241 // reference to process hosting a socket server
242 Process host;
243
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000244 struct SessionInfo {
245 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000246 sp<IBinder> root;
247 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000248
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000249 // client session objects associated with other process
250 // each one represents a separate session
251 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000252
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000253 ProcessSession(ProcessSession&&) = default;
254 ~ProcessSession() {
255 for (auto& session : sessions) {
256 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000257 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000258
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000259 for (auto& info : sessions) {
260 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000261
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000262 EXPECT_NE(nullptr, session);
263 EXPECT_NE(nullptr, session->state());
264 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000265
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000266 wp<RpcSession> weakSession = session;
267 session = nullptr;
268 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000269 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000270 }
271};
272
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000273// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000274// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000275struct BinderRpcTestProcessSession {
276 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000277
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000278 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000279 sp<IBinder> rootBinder;
280
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000281 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000282 sp<IBinderRpcTest> rootIface;
283
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000284 // whether session should be invalidated by end of run
Steven Moreland736664b2021-05-01 04:27:25 +0000285 bool expectInvalid = false;
286
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000287 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
288 ~BinderRpcTestProcessSession() {
Steven Moreland736664b2021-05-01 04:27:25 +0000289 if (!expectInvalid) {
290 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000291 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000292 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000293 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000294 for (auto remoteCount : remoteCounts) {
295 EXPECT_EQ(remoteCount, 1);
296 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000297 }
298
299 rootIface = nullptr;
300 rootBinder = nullptr;
301 }
302};
303
Steven Morelandc1635952021-04-01 16:20:47 +0000304enum class SocketType {
305 UNIX,
306 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700307 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000308};
309static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
310 switch (info.param) {
311 case SocketType::UNIX:
312 return "unix_domain_socket";
313 case SocketType::VSOCK:
314 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700315 case SocketType::INET:
316 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000317 default:
318 LOG_ALWAYS_FATAL("Unknown socket type");
319 return "";
320 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000321}
Steven Morelandc1635952021-04-01 16:20:47 +0000322class BinderRpc : public ::testing::TestWithParam<SocketType> {
323public:
324 // This creates a new process serving an interface on a certain number of
325 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000326 ProcessSession createRpcTestSocketServerProcess(
327 size_t numThreads, size_t numSessions,
Steven Moreland736664b2021-05-01 04:27:25 +0000328 const std::function<void(const sp<RpcServer>&)>& configure) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000329 CHECK_GE(numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000330
Steven Morelandc1635952021-04-01 16:20:47 +0000331 SocketType socketType = GetParam();
332
333 std::string addr = allocateSocketAddress();
334 unlink(addr.c_str());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700335 static unsigned int vsockPort = 3456;
336 vsockPort++;
Steven Morelandc1635952021-04-01 16:20:47 +0000337
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000338 auto ret = ProcessSession{
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700339 .host = Process([&](Pipe* pipe) {
Steven Morelandc1635952021-04-01 16:20:47 +0000340 sp<RpcServer> server = RpcServer::make();
341
342 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Morelandf137de92021-04-24 01:54:26 +0000343 server->setMaxThreads(numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000344
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000345 unsigned int outPort = 0;
346
Steven Morelandc1635952021-04-01 16:20:47 +0000347 switch (socketType) {
348 case SocketType::UNIX:
Steven Moreland611d15f2021-05-01 01:28:27 +0000349 CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000350 break;
351 case SocketType::VSOCK:
Steven Moreland611d15f2021-05-01 01:28:27 +0000352 CHECK(server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000353 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700354 case SocketType::INET: {
Steven Moreland611d15f2021-05-01 01:28:27 +0000355 CHECK(server->setupInetServer(0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700356 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700357 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700358 }
Steven Morelandc1635952021-04-01 16:20:47 +0000359 default:
360 LOG_ALWAYS_FATAL("Unknown socket type");
361 }
362
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000363 CHECK(android::base::WriteFully(pipe->writeEnd(), &outPort, sizeof(outPort)));
364
Steven Moreland611d15f2021-05-01 01:28:27 +0000365 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000366
Steven Morelandf137de92021-04-24 01:54:26 +0000367 server->join();
Steven Morelandc1635952021-04-01 16:20:47 +0000368 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000369 };
370
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000371 // always read socket, so that we have waited for the server to start
372 unsigned int outPort = 0;
373 CHECK(android::base::ReadFully(ret.host.getPipe()->readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700374 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000375 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700376 }
377
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000378 for (size_t i = 0; i < numSessions; i++) {
379 sp<RpcSession> session = RpcSession::make();
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000380 switch (socketType) {
381 case SocketType::UNIX:
382 if (session->setupUnixDomainClient(addr.c_str())) goto success;
383 break;
384 case SocketType::VSOCK:
385 if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
386 break;
387 case SocketType::INET:
388 if (session->setupInetClient("127.0.0.1", outPort)) goto success;
389 break;
390 default:
391 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000392 }
Steven Moreland736664b2021-05-01 04:27:25 +0000393 LOG_ALWAYS_FATAL("Could not connect");
394 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000396 }
Steven Morelandc1635952021-04-01 16:20:47 +0000397 return ret;
398 }
399
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000400 BinderRpcTestProcessSession createRpcTestSocketServerProcess(size_t numThreads,
401 size_t numSessions = 1) {
402 BinderRpcTestProcessSession ret{
403 .proc = createRpcTestSocketServerProcess(numThreads, numSessions,
Steven Moreland611d15f2021-05-01 01:28:27 +0000404 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000405 sp<MyBinderRpcTest> service =
406 new MyBinderRpcTest;
407 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000408 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000409 }),
410 };
411
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000412 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000413 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
414
415 return ret;
416 }
417};
418
419TEST_P(BinderRpc, RootObjectIsNull) {
Steven Moreland736664b2021-05-01 04:27:25 +0000420 auto proc = createRpcTestSocketServerProcess(1, 1, [](const sp<RpcServer>& server) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000421 // this is the default, but to be explicit
422 server->setRootObject(nullptr);
423 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000424
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000425 EXPECT_EQ(nullptr, proc.sessions.at(0).root);
Steven Moreland5553ac42020-11-11 02:14:45 +0000426}
427
Steven Morelandc1635952021-04-01 16:20:47 +0000428TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000429 auto proc = createRpcTestSocketServerProcess(1);
430 ASSERT_NE(proc.rootBinder, nullptr);
431 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
432}
433
Steven Moreland4cf688f2021-03-31 01:48:58 +0000434TEST_P(BinderRpc, GetInterfaceDescriptor) {
435 auto proc = createRpcTestSocketServerProcess(1);
436 ASSERT_NE(proc.rootBinder, nullptr);
437 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
438}
439
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000440TEST_P(BinderRpc, MultipleSessions) {
441 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 5 /*sessions*/);
442 for (auto session : proc.proc.sessions) {
443 ASSERT_NE(nullptr, session.root);
444 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000445 }
446}
447
Steven Morelandc1635952021-04-01 16:20:47 +0000448TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000449 auto proc = createRpcTestSocketServerProcess(1);
450 Parcel data;
451 Parcel reply;
452 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
453}
454
Steven Moreland67753c32021-04-02 18:45:19 +0000455TEST_P(BinderRpc, AppendSeparateFormats) {
456 auto proc = createRpcTestSocketServerProcess(1);
457
458 Parcel p1;
459 p1.markForBinder(proc.rootBinder);
460 p1.writeInt32(3);
461
462 Parcel p2;
463
464 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
465 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
466}
467
Steven Morelandc1635952021-04-01 16:20:47 +0000468TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000469 auto proc = createRpcTestSocketServerProcess(1);
470 Parcel data;
471 data.markForBinder(proc.rootBinder);
472 Parcel reply;
473 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
474}
475
Steven Morelandc1635952021-04-01 16:20:47 +0000476TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000477 auto proc = createRpcTestSocketServerProcess(1);
478 EXPECT_OK(proc.rootIface->sendString("asdf"));
479}
480
Steven Morelandc1635952021-04-01 16:20:47 +0000481TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000482 auto proc = createRpcTestSocketServerProcess(1);
483 std::string doubled;
484 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
485 EXPECT_EQ("cool cool ", doubled);
486}
487
Steven Morelandc1635952021-04-01 16:20:47 +0000488TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000489 auto proc = createRpcTestSocketServerProcess(1);
490 std::string single = std::string(1024, 'a');
491 std::string doubled;
492 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
493 EXPECT_EQ(single + single, doubled);
494}
495
Steven Morelandc1635952021-04-01 16:20:47 +0000496TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000497 auto proc = createRpcTestSocketServerProcess(1);
498
499 int32_t pingResult;
500 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
501 EXPECT_EQ(OK, pingResult);
502
503 EXPECT_EQ(0, MyBinderRpcSession::gNum);
504}
505
Steven Morelandc1635952021-04-01 16:20:47 +0000506TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000507 auto proc = createRpcTestSocketServerProcess(1);
508
509 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
510 sp<IBinder> outBinder;
511 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
512 EXPECT_EQ(inBinder, outBinder);
513
514 wp<IBinder> weak = inBinder;
515 inBinder = nullptr;
516 outBinder = nullptr;
517
518 // Force reading a reply, to process any pending dec refs from the other
519 // process (the other process will process dec refs there before processing
520 // the ping here).
521 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
522
523 EXPECT_EQ(nullptr, weak.promote());
524
525 EXPECT_EQ(0, MyBinderRpcSession::gNum);
526}
527
Steven Morelandc1635952021-04-01 16:20:47 +0000528TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000529 auto proc = createRpcTestSocketServerProcess(1);
530
531 sp<IBinderRpcSession> session;
532 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
533
534 sp<IBinder> inBinder = IInterface::asBinder(session);
535 sp<IBinder> outBinder;
536 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
537 EXPECT_EQ(inBinder, outBinder);
538
539 wp<IBinder> weak = inBinder;
540 session = nullptr;
541 inBinder = nullptr;
542 outBinder = nullptr;
543
544 // Force reading a reply, to process any pending dec refs from the other
545 // process (the other process will process dec refs there before processing
546 // the ping here).
547 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
548
549 EXPECT_EQ(nullptr, weak.promote());
550}
551
Steven Morelandc1635952021-04-01 16:20:47 +0000552TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000553 auto proc = createRpcTestSocketServerProcess(1);
554
555 sp<IBinder> outBinder;
556 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
557 EXPECT_EQ(nullptr, outBinder);
558}
559
Steven Morelandc1635952021-04-01 16:20:47 +0000560TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000561 auto proc = createRpcTestSocketServerProcess(1);
562
563 IBinder* ptr = nullptr;
564 {
565 sp<IBinder> binder = new BBinder();
566 ptr = binder.get();
567 EXPECT_OK(proc.rootIface->holdBinder(binder));
568 }
569
570 sp<IBinder> held;
571 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
572
573 EXPECT_EQ(held.get(), ptr);
574
575 // stop holding binder, because we test to make sure references are cleaned
576 // up
577 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
578 // and flush ref counts
579 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
580}
581
582// START TESTS FOR LIMITATIONS OF SOCKET BINDER
583// These are behavioral differences form regular binder, where certain usecases
584// aren't supported.
585
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000586TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000587 auto proc1 = createRpcTestSocketServerProcess(1);
588 auto proc2 = createRpcTestSocketServerProcess(1);
589
590 sp<IBinder> outBinder;
591 EXPECT_EQ(INVALID_OPERATION,
592 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
593}
594
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000595TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
596 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 2 /*sessions*/);
Steven Moreland736664b2021-05-01 04:27:25 +0000597
598 sp<IBinder> outBinder;
599 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000600 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000601 .transactionError());
602}
603
Steven Morelandc1635952021-04-01 16:20:47 +0000604TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000605 auto proc = createRpcTestSocketServerProcess(1);
606
607 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
608 sp<IBinder> outBinder;
609 EXPECT_EQ(INVALID_OPERATION,
610 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
611}
612
Steven Morelandc1635952021-04-01 16:20:47 +0000613TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000614 auto proc = createRpcTestSocketServerProcess(1);
615
616 // for historical reasons, IServiceManager interface only returns the
617 // exception code
618 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
619 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
620}
621
622// END TESTS FOR LIMITATIONS OF SOCKET BINDER
623
Steven Morelandc1635952021-04-01 16:20:47 +0000624TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000625 auto proc = createRpcTestSocketServerProcess(1);
626
627 sp<IBinder> outBinder;
628 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
629 EXPECT_EQ(proc.rootBinder, outBinder);
630}
631
Steven Morelandc1635952021-04-01 16:20:47 +0000632TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000633 auto proc = createRpcTestSocketServerProcess(1);
634
635 auto nastyNester = sp<MyBinderRpcTest>::make();
636 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
637
638 wp<IBinder> weak = nastyNester;
639 nastyNester = nullptr;
640 EXPECT_EQ(nullptr, weak.promote());
641}
642
Steven Morelandc1635952021-04-01 16:20:47 +0000643TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000644 auto proc = createRpcTestSocketServerProcess(1);
645
646 sp<IBinder> a;
647 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
648
649 sp<IBinder> b;
650 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
651
652 EXPECT_EQ(a, b);
653}
654
Steven Morelandc1635952021-04-01 16:20:47 +0000655TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000656 auto proc = createRpcTestSocketServerProcess(1);
657
658 sp<IBinder> a;
659 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
660 wp<IBinder> weak = a;
661 a = nullptr;
662
663 sp<IBinder> b;
664 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
665
666 // this is the wrong behavior, since BpBinder
667 // doesn't implement onIncStrongAttempted
668 // but make sure there is no crash
669 EXPECT_EQ(nullptr, weak.promote());
670
671 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
672
673 // In order to fix this:
674 // - need to have incStrongAttempted reflected across IPC boundary (wait for
675 // response to promote - round trip...)
676 // - sendOnLastWeakRef, to delete entries out of RpcState table
677 EXPECT_EQ(b, weak.promote());
678}
679
680#define expectSessions(expected, iface) \
681 do { \
682 int session; \
683 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
684 EXPECT_EQ(expected, session); \
685 } while (false)
686
Steven Morelandc1635952021-04-01 16:20:47 +0000687TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000688 auto proc = createRpcTestSocketServerProcess(1);
689
690 sp<IBinderRpcSession> session;
691 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
692 std::string out;
693 EXPECT_OK(session->getName(&out));
694 EXPECT_EQ("aoeu", out);
695
696 expectSessions(1, proc.rootIface);
697 session = nullptr;
698 expectSessions(0, proc.rootIface);
699}
700
Steven Morelandc1635952021-04-01 16:20:47 +0000701TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000702 auto proc = createRpcTestSocketServerProcess(1);
703
704 std::vector<sp<IBinderRpcSession>> sessions;
705
706 for (size_t i = 0; i < 15; i++) {
707 expectSessions(i, proc.rootIface);
708 sp<IBinderRpcSession> session;
709 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
710 sessions.push_back(session);
711 }
712 expectSessions(sessions.size(), proc.rootIface);
713 for (size_t i = 0; i < sessions.size(); i++) {
714 std::string out;
715 EXPECT_OK(sessions.at(i)->getName(&out));
716 EXPECT_EQ(std::to_string(i), out);
717 }
718 expectSessions(sessions.size(), proc.rootIface);
719
720 while (!sessions.empty()) {
721 sessions.pop_back();
722 expectSessions(sessions.size(), proc.rootIface);
723 }
724 expectSessions(0, proc.rootIface);
725}
726
727size_t epochMillis() {
728 using std::chrono::duration_cast;
729 using std::chrono::milliseconds;
730 using std::chrono::seconds;
731 using std::chrono::system_clock;
732 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
733}
734
Steven Morelandc1635952021-04-01 16:20:47 +0000735TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000736 constexpr size_t kNumThreads = 10;
737
738 auto proc = createRpcTestSocketServerProcess(kNumThreads);
739
740 EXPECT_OK(proc.rootIface->lock());
741
742 // block all but one thread taking locks
743 std::vector<std::thread> ts;
744 for (size_t i = 0; i < kNumThreads - 1; i++) {
745 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
746 }
747
748 usleep(100000); // give chance for calls on other threads
749
750 // other calls still work
751 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
752
753 constexpr size_t blockTimeMs = 500;
754 size_t epochMsBefore = epochMillis();
755 // after this, we should never see a response within this time
756 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
757
758 // this call should be blocked for blockTimeMs
759 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
760
761 size_t epochMsAfter = epochMillis();
762 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
763
764 for (auto& t : ts) t.join();
765}
766
Steven Morelandc1635952021-04-01 16:20:47 +0000767TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000768 constexpr size_t kNumThreads = 10;
769 constexpr size_t kNumCalls = kNumThreads + 3;
770 constexpr size_t kSleepMs = 500;
771
772 auto proc = createRpcTestSocketServerProcess(kNumThreads);
773
774 size_t epochMsBefore = epochMillis();
775
776 std::vector<std::thread> ts;
777 for (size_t i = 0; i < kNumCalls; i++) {
778 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
779 }
780
781 for (auto& t : ts) t.join();
782
783 size_t epochMsAfter = epochMillis();
784
785 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
786
787 // Potential flake, but make sure calls are handled in parallel.
788 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
789}
790
Steven Morelandc1635952021-04-01 16:20:47 +0000791TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000792 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 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000803 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000804 EXPECT_EQ(proc.rootBinder, out);
805 }
806 }));
807 }
808
809 for (auto& t : threads) t.join();
810}
811
Steven Morelandc6046982021-04-20 00:49:42 +0000812TEST_P(BinderRpc, OnewayStressTest) {
813 constexpr size_t kNumClientThreads = 10;
814 constexpr size_t kNumServerThreads = 10;
815 constexpr size_t kNumCalls = 100;
816
817 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
818
819 std::vector<std::thread> threads;
820 for (size_t i = 0; i < kNumClientThreads; i++) {
821 threads.push_back(std::thread([&] {
822 for (size_t j = 0; j < kNumCalls; j++) {
823 EXPECT_OK(proc.rootIface->sendString("a"));
824 }
825
826 // check threads are not stuck
827 EXPECT_OK(proc.rootIface->sleepMs(250));
828 }));
829 }
830
831 for (auto& t : threads) t.join();
832}
833
Steven Morelandc1635952021-04-01 16:20:47 +0000834TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000835 constexpr size_t kReallyLongTimeMs = 100;
836 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
837
838 // more than one thread, just so this doesn't deadlock
839 auto proc = createRpcTestSocketServerProcess(2);
840
841 size_t epochMsBefore = epochMillis();
842
843 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
844
845 size_t epochMsAfter = epochMillis();
846 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
847}
848
Steven Morelandc1635952021-04-01 16:20:47 +0000849TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000850 constexpr size_t kNumSleeps = 10;
851 constexpr size_t kNumExtraServerThreads = 4;
852 constexpr size_t kSleepMs = 50;
853
854 // make sure calls to the same object happen on the same thread
855 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
856
857 EXPECT_OK(proc.rootIface->lock());
858
859 for (size_t i = 0; i < kNumSleeps; i++) {
860 // these should be processed serially
861 proc.rootIface->sleepMsAsync(kSleepMs);
862 }
863 // should also be processesed serially
864 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
865
866 size_t epochMsBefore = epochMillis();
867 EXPECT_OK(proc.rootIface->lockUnlock());
868 size_t epochMsAfter = epochMillis();
869
870 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
871}
872
Steven Morelandc1635952021-04-01 16:20:47 +0000873TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000874 for (bool doDeathCleanup : {true, false}) {
875 auto proc = createRpcTestSocketServerProcess(1);
876
877 // make sure there is some state during crash
878 // 1. we hold their binder
879 sp<IBinderRpcSession> session;
880 EXPECT_OK(proc.rootIface->openSession("happy", &session));
881 // 2. they hold our binder
882 sp<IBinder> binder = new BBinder();
883 EXPECT_OK(proc.rootIface->holdBinder(binder));
884
885 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
886 << "Do death cleanup: " << doDeathCleanup;
887
Steven Moreland736664b2021-05-01 04:27:25 +0000888 proc.expectInvalid = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000889 }
890}
891
Steven Moreland37aff182021-03-26 02:04:16 +0000892TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
893 auto proc = createRpcTestSocketServerProcess(1);
894
895 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
896 ASSERT_NE(binder, nullptr);
897
898 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
899}
900
901TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
902 auto proc = createRpcTestSocketServerProcess(1);
903
904 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
905 ASSERT_NE(binder, nullptr);
906
907 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
908 ASSERT_NE(ndkBinder, nullptr);
909
910 std::string out;
911 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
912 ASSERT_TRUE(status.isOk()) << status.getDescription();
913 ASSERT_EQ("aoeuaoeu", out);
914}
915
Steven Moreland5553ac42020-11-11 02:14:45 +0000916ssize_t countFds() {
917 DIR* dir = opendir("/proc/self/fd/");
918 if (dir == nullptr) return -1;
919 ssize_t ret = 0;
920 dirent* ent;
921 while ((ent = readdir(dir)) != nullptr) ret++;
922 closedir(dir);
923 return ret;
924}
925
Steven Morelandc1635952021-04-01 16:20:47 +0000926TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000927 ssize_t beforeFds = countFds();
928 ASSERT_GE(beforeFds, 0);
929 {
930 auto proc = createRpcTestSocketServerProcess(10);
931 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
932 }
933 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
934}
935
Steven Morelandc1635952021-04-01 16:20:47 +0000936INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700937 ::testing::ValuesIn({
938 SocketType::UNIX,
Steven Morelandbd5002b2021-05-04 23:12:56 +0000939// TODO(b/185269356): working on host
Steven Morelandf6ec4632021-04-01 16:20:47 +0000940#ifdef __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700941 SocketType::VSOCK,
Steven Morelandbd5002b2021-05-04 23:12:56 +0000942#endif
Yifan Hong0d2bd112021-04-13 17:38:36 -0700943 SocketType::INET,
944 }),
Steven Morelandf6ec4632021-04-01 16:20:47 +0000945 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +0000946
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700947class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
948
949TEST_P(BinderRpcServerRootObject, WeakRootObject) {
950 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
951 auto setRootObject = [](bool isStrong) -> SetFn {
952 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
953 };
954
955 auto server = RpcServer::make();
956 auto [isStrong1, isStrong2] = GetParam();
957 auto binder1 = sp<BBinder>::make();
958 IBinder* binderRaw1 = binder1.get();
959 setRootObject(isStrong1)(server.get(), binder1);
960 EXPECT_EQ(binderRaw1, server->getRootObject());
961 binder1.clear();
962 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
963
964 auto binder2 = sp<BBinder>::make();
965 IBinder* binderRaw2 = binder2.get();
966 setRootObject(isStrong2)(server.get(), binder2);
967 EXPECT_EQ(binderRaw2, server->getRootObject());
968 binder2.clear();
969 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
970}
971
972INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
973 ::testing::Combine(::testing::Bool(), ::testing::Bool()));
974
Yifan Hong1a235852021-05-13 16:07:47 -0700975class OneOffSignal {
976public:
977 // If notify() was previously called, or is called within |duration|, return true; else false.
978 template <typename R, typename P>
979 bool wait(std::chrono::duration<R, P> duration) {
980 std::unique_lock<std::mutex> lock(mMutex);
981 return mCv.wait_for(lock, duration, [this] { return mValue; });
982 }
983 void notify() {
984 std::unique_lock<std::mutex> lock(mMutex);
985 mValue = true;
986 lock.unlock();
987 mCv.notify_all();
988 }
989
990private:
991 std::mutex mMutex;
992 std::condition_variable mCv;
993 bool mValue = false;
994};
995
996TEST(BinderRpc, Shutdown) {
997 auto addr = allocateSocketAddress();
998 unlink(addr.c_str());
999 auto server = RpcServer::make();
1000 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1001 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1002 auto joinEnds = std::make_shared<OneOffSignal>();
1003
1004 // If things are broken and the thread never stops, don't block other tests. Because the thread
1005 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1006 // shared pointers are passed.
1007 std::thread([server, joinEnds] {
1008 server->join();
1009 joinEnds->notify();
1010 }).detach();
1011
1012 bool shutdown = false;
1013 for (int i = 0; i < 10 && !shutdown; i++) {
1014 usleep(300 * 1000); // 300ms; total 3s
1015 if (server->shutdown()) shutdown = true;
1016 }
1017 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1018
1019 ASSERT_TRUE(joinEnds->wait(2s))
1020 << "After server->shutdown() returns true, join() did not stop after 2s";
1021}
1022
Steven Morelandc1635952021-04-01 16:20:47 +00001023} // namespace android
1024
1025int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001026 ::testing::InitGoogleTest(&argc, argv);
1027 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1028 return RUN_ALL_TESTS();
1029}