blob: 4d31673b6e5d10063c9295d9dc89b84e43159912 [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>
Steven Morelandd7302072021-05-15 01:32:04 +000026#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000027#include <binder/IServiceManager.h>
28#include <binder/ProcessState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000029#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000030#include <binder/RpcSession.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000031#include <gtest/gtest.h>
32
Steven Morelandc1635952021-04-01 16:20:47 +000033#include <chrono>
34#include <cstdlib>
35#include <iostream>
36#include <thread>
37
Steven Morelandc1635952021-04-01 16:20:47 +000038#include <sys/prctl.h>
39#include <unistd.h>
40
Steven Morelandbd5002b2021-05-04 23:12:56 +000041#include "../RpcState.h" // for debugging
42#include "../vm_sockets.h" // for VMADDR_*
Steven Moreland5553ac42020-11-11 02:14:45 +000043
Yifan Hong1a235852021-05-13 16:07:47 -070044using namespace std::chrono_literals;
45
Steven Moreland5553ac42020-11-11 02:14:45 +000046namespace 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
Yifan Hong00aeb762021-05-12 17:07:36 -070055TEST(BinderRpc, SetExternalServer) {
56 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
57 int sinkFd = sink.get();
58 auto server = RpcServer::make();
59 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
60 ASSERT_FALSE(server->hasServer());
61 ASSERT_TRUE(server->setupExternalServer(std::move(sink)));
62 ASSERT_TRUE(server->hasServer());
63 base::unique_fd retrieved = server->releaseServer();
64 ASSERT_FALSE(server->hasServer());
65 ASSERT_EQ(sinkFd, retrieved.get());
66}
67
Steven Moreland5553ac42020-11-11 02:14:45 +000068using android::binder::Status;
69
70#define EXPECT_OK(status) \
71 do { \
72 Status stat = (status); \
73 EXPECT_TRUE(stat.isOk()) << stat; \
74 } while (false)
75
76class MyBinderRpcSession : public BnBinderRpcSession {
77public:
78 static std::atomic<int32_t> gNum;
79
80 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
81 Status getName(std::string* name) override {
82 *name = mName;
83 return Status::ok();
84 }
85 ~MyBinderRpcSession() { gNum--; }
86
87private:
88 std::string mName;
89};
90std::atomic<int32_t> MyBinderRpcSession::gNum;
91
92class MyBinderRpcTest : public BnBinderRpcTest {
93public:
Steven Moreland611d15f2021-05-01 01:28:27 +000094 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +000095
96 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +000097 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +000098 return Status::ok();
99 }
100 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000101 *strstr = str + str;
102 return Status::ok();
103 }
Steven Moreland736664b2021-05-01 04:27:25 +0000104 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000105 sp<RpcServer> spServer = server.promote();
106 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000107 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
108 }
Steven Moreland736664b2021-05-01 04:27:25 +0000109 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000110 for (auto session : spServer->listSessions()) {
111 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000112 if (count != 1) {
113 // this is called when there is only one binder held remaining,
114 // so to aid debugging
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000115 session->state()->dump();
Steven Moreland611d15f2021-05-01 01:28:27 +0000116 }
Steven Moreland736664b2021-05-01 04:27:25 +0000117 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000118 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000119 return Status::ok();
120 }
121 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
122 if (binder == nullptr) {
123 std::cout << "Received null binder!" << std::endl;
124 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
125 }
126 *out = binder->pingBinder();
127 return Status::ok();
128 }
129 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
130 *out = binder;
131 return Status::ok();
132 }
133 static sp<IBinder> mHeldBinder;
134 Status holdBinder(const sp<IBinder>& binder) override {
135 mHeldBinder = binder;
136 return Status::ok();
137 }
138 Status getHeldBinder(sp<IBinder>* held) override {
139 *held = mHeldBinder;
140 return Status::ok();
141 }
142 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
143 if (count <= 0) return Status::ok();
144 return binder->nestMe(this, count - 1);
145 }
146 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
147 static sp<IBinder> binder = new BBinder;
148 *out = binder;
149 return Status::ok();
150 }
151 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
152 *out = new MyBinderRpcSession(name);
153 return Status::ok();
154 }
155 Status getNumOpenSessions(int32_t* out) override {
156 *out = MyBinderRpcSession::gNum;
157 return Status::ok();
158 }
159
160 std::mutex blockMutex;
161 Status lock() override {
162 blockMutex.lock();
163 return Status::ok();
164 }
165 Status unlockInMsAsync(int32_t ms) override {
166 usleep(ms * 1000);
167 blockMutex.unlock();
168 return Status::ok();
169 }
170 Status lockUnlock() override {
171 std::lock_guard<std::mutex> _l(blockMutex);
172 return Status::ok();
173 }
174
175 Status sleepMs(int32_t ms) override {
176 usleep(ms * 1000);
177 return Status::ok();
178 }
179
180 Status sleepMsAsync(int32_t ms) override {
181 // In-process binder calls are asynchronous, but the call to this method
182 // is synchronous wrt its client. This in/out-process threading model
183 // diffentiation is a classic binder leaky abstraction (for better or
184 // worse) and is preserved here the way binder sockets plugs itself
185 // into BpBinder, as nothing is changed at the higher levels
186 // (IInterface) which result in this behavior.
187 return sleepMs(ms);
188 }
189
190 Status die(bool cleanup) override {
191 if (cleanup) {
192 exit(1);
193 } else {
194 _exit(1);
195 }
196 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000197
198 Status scheduleShutdown() override {
199 sp<RpcServer> strongServer = server.promote();
200 if (strongServer == nullptr) {
201 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
202 }
203 std::thread([=] {
204 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
205 }).detach();
206 return Status::ok();
207 }
208
Steven Morelandd7302072021-05-15 01:32:04 +0000209 Status useKernelBinderCallingId() override {
210 // this is WRONG! It does not make sense when using RPC binder, and
211 // because it is SO wrong, and so much code calls this, it should abort!
212
213 (void)IPCThreadState::self()->getCallingPid();
214 return Status::ok();
215 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000216};
217sp<IBinder> MyBinderRpcTest::mHeldBinder;
218
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700219class Pipe {
220public:
221 Pipe() { CHECK(android::base::Pipe(&mRead, &mWrite)); }
222 Pipe(Pipe&&) = default;
223 android::base::borrowed_fd readEnd() { return mRead; }
224 android::base::borrowed_fd writeEnd() { return mWrite; }
225
226private:
227 android::base::unique_fd mRead;
228 android::base::unique_fd mWrite;
229};
230
Steven Moreland5553ac42020-11-11 02:14:45 +0000231class Process {
232public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700233 Process(Process&&) = default;
234 Process(const std::function<void(Pipe*)>& f) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000235 if (0 == (mPid = fork())) {
236 // racey: assume parent doesn't crash before this is set
237 prctl(PR_SET_PDEATHSIG, SIGHUP);
238
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700239 f(&mPipe);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000240
241 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000242 }
243 }
244 ~Process() {
245 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000246 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000247 }
248 }
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700249 Pipe* getPipe() { return &mPipe; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000250
251private:
252 pid_t mPid = 0;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700253 Pipe mPipe;
Steven Moreland5553ac42020-11-11 02:14:45 +0000254};
255
256static std::string allocateSocketAddress() {
257 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000258 std::string temp = getenv("TMPDIR") ?: "/tmp";
259 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000260};
261
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000262struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000263 // reference to process hosting a socket server
264 Process host;
265
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000266 struct SessionInfo {
267 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000268 sp<IBinder> root;
269 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000270
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000271 // client session objects associated with other process
272 // each one represents a separate session
273 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000274
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000275 ProcessSession(ProcessSession&&) = default;
276 ~ProcessSession() {
277 for (auto& session : sessions) {
278 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000279 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000280
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000281 for (auto& info : sessions) {
282 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000283
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000284 EXPECT_NE(nullptr, session);
285 EXPECT_NE(nullptr, session->state());
286 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000287
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000288 wp<RpcSession> weakSession = session;
289 session = nullptr;
290 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000291 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000292 }
293};
294
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000295// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000296// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000297struct BinderRpcTestProcessSession {
298 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000299
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000300 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000301 sp<IBinder> rootBinder;
302
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000303 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000304 sp<IBinderRpcTest> rootIface;
305
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000306 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000307 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000308
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000309 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
310 ~BinderRpcTestProcessSession() {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000311 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000312 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000313 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000314 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000315 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000316 for (auto remoteCount : remoteCounts) {
317 EXPECT_EQ(remoteCount, 1);
318 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000319
320 EXPECT_OK(rootIface->scheduleShutdown());
Steven Moreland5553ac42020-11-11 02:14:45 +0000321 }
322
323 rootIface = nullptr;
324 rootBinder = nullptr;
325 }
326};
327
Steven Morelandc1635952021-04-01 16:20:47 +0000328enum class SocketType {
329 UNIX,
330 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700331 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000332};
333static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
334 switch (info.param) {
335 case SocketType::UNIX:
336 return "unix_domain_socket";
337 case SocketType::VSOCK:
338 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700339 case SocketType::INET:
340 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000341 default:
342 LOG_ALWAYS_FATAL("Unknown socket type");
343 return "";
344 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000345}
Steven Morelandc1635952021-04-01 16:20:47 +0000346class BinderRpc : public ::testing::TestWithParam<SocketType> {
347public:
348 // This creates a new process serving an interface on a certain number of
349 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000350 ProcessSession createRpcTestSocketServerProcess(
351 size_t numThreads, size_t numSessions,
Steven Moreland736664b2021-05-01 04:27:25 +0000352 const std::function<void(const sp<RpcServer>&)>& configure) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000353 CHECK_GE(numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000354
Steven Morelandc1635952021-04-01 16:20:47 +0000355 SocketType socketType = GetParam();
356
357 std::string addr = allocateSocketAddress();
358 unlink(addr.c_str());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700359 static unsigned int vsockPort = 3456;
360 vsockPort++;
Steven Morelandc1635952021-04-01 16:20:47 +0000361
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000362 auto ret = ProcessSession{
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700363 .host = Process([&](Pipe* pipe) {
Steven Morelandc1635952021-04-01 16:20:47 +0000364 sp<RpcServer> server = RpcServer::make();
365
366 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Morelandf137de92021-04-24 01:54:26 +0000367 server->setMaxThreads(numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000368
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000369 unsigned int outPort = 0;
370
Steven Morelandc1635952021-04-01 16:20:47 +0000371 switch (socketType) {
372 case SocketType::UNIX:
Steven Moreland611d15f2021-05-01 01:28:27 +0000373 CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000374 break;
375 case SocketType::VSOCK:
Steven Moreland611d15f2021-05-01 01:28:27 +0000376 CHECK(server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000377 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700378 case SocketType::INET: {
Steven Moreland611d15f2021-05-01 01:28:27 +0000379 CHECK(server->setupInetServer(0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700380 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700381 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700382 }
Steven Morelandc1635952021-04-01 16:20:47 +0000383 default:
384 LOG_ALWAYS_FATAL("Unknown socket type");
385 }
386
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000387 CHECK(android::base::WriteFully(pipe->writeEnd(), &outPort, sizeof(outPort)));
388
Steven Moreland611d15f2021-05-01 01:28:27 +0000389 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000390
Steven Morelandf137de92021-04-24 01:54:26 +0000391 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000392
393 // Another thread calls shutdown. Wait for it to complete.
394 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000395 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000396 };
397
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000398 // always read socket, so that we have waited for the server to start
399 unsigned int outPort = 0;
400 CHECK(android::base::ReadFully(ret.host.getPipe()->readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700401 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000402 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700403 }
404
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000405 for (size_t i = 0; i < numSessions; i++) {
406 sp<RpcSession> session = RpcSession::make();
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000407 switch (socketType) {
408 case SocketType::UNIX:
409 if (session->setupUnixDomainClient(addr.c_str())) goto success;
410 break;
411 case SocketType::VSOCK:
412 if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
413 break;
414 case SocketType::INET:
415 if (session->setupInetClient("127.0.0.1", outPort)) goto success;
416 break;
417 default:
418 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000419 }
Steven Moreland736664b2021-05-01 04:27:25 +0000420 LOG_ALWAYS_FATAL("Could not connect");
421 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000422 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000423 }
Steven Morelandc1635952021-04-01 16:20:47 +0000424 return ret;
425 }
426
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000427 BinderRpcTestProcessSession createRpcTestSocketServerProcess(size_t numThreads,
428 size_t numSessions = 1) {
429 BinderRpcTestProcessSession ret{
430 .proc = createRpcTestSocketServerProcess(numThreads, numSessions,
Steven Moreland611d15f2021-05-01 01:28:27 +0000431 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000432 sp<MyBinderRpcTest> service =
433 new MyBinderRpcTest;
434 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000435 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000436 }),
437 };
438
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000439 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000440 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
441
442 return ret;
443 }
444};
445
Steven Morelandc1635952021-04-01 16:20:47 +0000446TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000447 auto proc = createRpcTestSocketServerProcess(1);
448 ASSERT_NE(proc.rootBinder, nullptr);
449 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
450}
451
Steven Moreland4cf688f2021-03-31 01:48:58 +0000452TEST_P(BinderRpc, GetInterfaceDescriptor) {
453 auto proc = createRpcTestSocketServerProcess(1);
454 ASSERT_NE(proc.rootBinder, nullptr);
455 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
456}
457
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000458TEST_P(BinderRpc, MultipleSessions) {
459 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 5 /*sessions*/);
460 for (auto session : proc.proc.sessions) {
461 ASSERT_NE(nullptr, session.root);
462 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000463 }
464}
465
Steven Morelandc1635952021-04-01 16:20:47 +0000466TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000467 auto proc = createRpcTestSocketServerProcess(1);
468 Parcel data;
469 Parcel reply;
470 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
471}
472
Steven Moreland67753c32021-04-02 18:45:19 +0000473TEST_P(BinderRpc, AppendSeparateFormats) {
474 auto proc = createRpcTestSocketServerProcess(1);
475
476 Parcel p1;
477 p1.markForBinder(proc.rootBinder);
478 p1.writeInt32(3);
479
480 Parcel p2;
481
482 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
483 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
484}
485
Steven Morelandc1635952021-04-01 16:20:47 +0000486TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000487 auto proc = createRpcTestSocketServerProcess(1);
488 Parcel data;
489 data.markForBinder(proc.rootBinder);
490 Parcel reply;
491 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
492}
493
Steven Morelandc1635952021-04-01 16:20:47 +0000494TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000495 auto proc = createRpcTestSocketServerProcess(1);
496 EXPECT_OK(proc.rootIface->sendString("asdf"));
497}
498
Steven Morelandc1635952021-04-01 16:20:47 +0000499TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000500 auto proc = createRpcTestSocketServerProcess(1);
501 std::string doubled;
502 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
503 EXPECT_EQ("cool cool ", doubled);
504}
505
Steven Morelandc1635952021-04-01 16:20:47 +0000506TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000507 auto proc = createRpcTestSocketServerProcess(1);
508 std::string single = std::string(1024, 'a');
509 std::string doubled;
510 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
511 EXPECT_EQ(single + single, doubled);
512}
513
Steven Morelandc1635952021-04-01 16:20:47 +0000514TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000515 auto proc = createRpcTestSocketServerProcess(1);
516
517 int32_t pingResult;
518 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
519 EXPECT_EQ(OK, pingResult);
520
521 EXPECT_EQ(0, MyBinderRpcSession::gNum);
522}
523
Steven Morelandc1635952021-04-01 16:20:47 +0000524TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000525 auto proc = createRpcTestSocketServerProcess(1);
526
527 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
528 sp<IBinder> outBinder;
529 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
530 EXPECT_EQ(inBinder, outBinder);
531
532 wp<IBinder> weak = inBinder;
533 inBinder = nullptr;
534 outBinder = nullptr;
535
536 // Force reading a reply, to process any pending dec refs from the other
537 // process (the other process will process dec refs there before processing
538 // the ping here).
539 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
540
541 EXPECT_EQ(nullptr, weak.promote());
542
543 EXPECT_EQ(0, MyBinderRpcSession::gNum);
544}
545
Steven Morelandc1635952021-04-01 16:20:47 +0000546TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000547 auto proc = createRpcTestSocketServerProcess(1);
548
549 sp<IBinderRpcSession> session;
550 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
551
552 sp<IBinder> inBinder = IInterface::asBinder(session);
553 sp<IBinder> outBinder;
554 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
555 EXPECT_EQ(inBinder, outBinder);
556
557 wp<IBinder> weak = inBinder;
558 session = nullptr;
559 inBinder = nullptr;
560 outBinder = nullptr;
561
562 // Force reading a reply, to process any pending dec refs from the other
563 // process (the other process will process dec refs there before processing
564 // the ping here).
565 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
566
567 EXPECT_EQ(nullptr, weak.promote());
568}
569
Steven Morelandc1635952021-04-01 16:20:47 +0000570TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000571 auto proc = createRpcTestSocketServerProcess(1);
572
573 sp<IBinder> outBinder;
574 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
575 EXPECT_EQ(nullptr, outBinder);
576}
577
Steven Morelandc1635952021-04-01 16:20:47 +0000578TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000579 auto proc = createRpcTestSocketServerProcess(1);
580
581 IBinder* ptr = nullptr;
582 {
583 sp<IBinder> binder = new BBinder();
584 ptr = binder.get();
585 EXPECT_OK(proc.rootIface->holdBinder(binder));
586 }
587
588 sp<IBinder> held;
589 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
590
591 EXPECT_EQ(held.get(), ptr);
592
593 // stop holding binder, because we test to make sure references are cleaned
594 // up
595 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
596 // and flush ref counts
597 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
598}
599
600// START TESTS FOR LIMITATIONS OF SOCKET BINDER
601// These are behavioral differences form regular binder, where certain usecases
602// aren't supported.
603
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000604TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000605 auto proc1 = createRpcTestSocketServerProcess(1);
606 auto proc2 = createRpcTestSocketServerProcess(1);
607
608 sp<IBinder> outBinder;
609 EXPECT_EQ(INVALID_OPERATION,
610 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
611}
612
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000613TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
614 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 2 /*sessions*/);
Steven Moreland736664b2021-05-01 04:27:25 +0000615
616 sp<IBinder> outBinder;
617 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000618 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000619 .transactionError());
620}
621
Steven Morelandc1635952021-04-01 16:20:47 +0000622TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000623 auto proc = createRpcTestSocketServerProcess(1);
624
625 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
626 sp<IBinder> outBinder;
627 EXPECT_EQ(INVALID_OPERATION,
628 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
629}
630
Steven Morelandc1635952021-04-01 16:20:47 +0000631TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000632 auto proc = createRpcTestSocketServerProcess(1);
633
634 // for historical reasons, IServiceManager interface only returns the
635 // exception code
636 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
637 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
638}
639
640// END TESTS FOR LIMITATIONS OF SOCKET BINDER
641
Steven Morelandc1635952021-04-01 16:20:47 +0000642TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000643 auto proc = createRpcTestSocketServerProcess(1);
644
645 sp<IBinder> outBinder;
646 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
647 EXPECT_EQ(proc.rootBinder, outBinder);
648}
649
Steven Morelandc1635952021-04-01 16:20:47 +0000650TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000651 auto proc = createRpcTestSocketServerProcess(1);
652
653 auto nastyNester = sp<MyBinderRpcTest>::make();
654 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
655
656 wp<IBinder> weak = nastyNester;
657 nastyNester = nullptr;
658 EXPECT_EQ(nullptr, weak.promote());
659}
660
Steven Morelandc1635952021-04-01 16:20:47 +0000661TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000662 auto proc = createRpcTestSocketServerProcess(1);
663
664 sp<IBinder> a;
665 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
666
667 sp<IBinder> b;
668 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
669
670 EXPECT_EQ(a, b);
671}
672
Steven Morelandc1635952021-04-01 16:20:47 +0000673TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000674 auto proc = createRpcTestSocketServerProcess(1);
675
676 sp<IBinder> a;
677 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
678 wp<IBinder> weak = a;
679 a = nullptr;
680
681 sp<IBinder> b;
682 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
683
684 // this is the wrong behavior, since BpBinder
685 // doesn't implement onIncStrongAttempted
686 // but make sure there is no crash
687 EXPECT_EQ(nullptr, weak.promote());
688
689 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
690
691 // In order to fix this:
692 // - need to have incStrongAttempted reflected across IPC boundary (wait for
693 // response to promote - round trip...)
694 // - sendOnLastWeakRef, to delete entries out of RpcState table
695 EXPECT_EQ(b, weak.promote());
696}
697
698#define expectSessions(expected, iface) \
699 do { \
700 int session; \
701 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
702 EXPECT_EQ(expected, session); \
703 } while (false)
704
Steven Morelandc1635952021-04-01 16:20:47 +0000705TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000706 auto proc = createRpcTestSocketServerProcess(1);
707
708 sp<IBinderRpcSession> session;
709 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
710 std::string out;
711 EXPECT_OK(session->getName(&out));
712 EXPECT_EQ("aoeu", out);
713
714 expectSessions(1, proc.rootIface);
715 session = nullptr;
716 expectSessions(0, proc.rootIface);
717}
718
Steven Morelandc1635952021-04-01 16:20:47 +0000719TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000720 auto proc = createRpcTestSocketServerProcess(1);
721
722 std::vector<sp<IBinderRpcSession>> sessions;
723
724 for (size_t i = 0; i < 15; i++) {
725 expectSessions(i, proc.rootIface);
726 sp<IBinderRpcSession> session;
727 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
728 sessions.push_back(session);
729 }
730 expectSessions(sessions.size(), proc.rootIface);
731 for (size_t i = 0; i < sessions.size(); i++) {
732 std::string out;
733 EXPECT_OK(sessions.at(i)->getName(&out));
734 EXPECT_EQ(std::to_string(i), out);
735 }
736 expectSessions(sessions.size(), proc.rootIface);
737
738 while (!sessions.empty()) {
739 sessions.pop_back();
740 expectSessions(sessions.size(), proc.rootIface);
741 }
742 expectSessions(0, proc.rootIface);
743}
744
745size_t epochMillis() {
746 using std::chrono::duration_cast;
747 using std::chrono::milliseconds;
748 using std::chrono::seconds;
749 using std::chrono::system_clock;
750 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
751}
752
Steven Morelandc1635952021-04-01 16:20:47 +0000753TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000754 constexpr size_t kNumThreads = 10;
755
756 auto proc = createRpcTestSocketServerProcess(kNumThreads);
757
758 EXPECT_OK(proc.rootIface->lock());
759
760 // block all but one thread taking locks
761 std::vector<std::thread> ts;
762 for (size_t i = 0; i < kNumThreads - 1; i++) {
763 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
764 }
765
766 usleep(100000); // give chance for calls on other threads
767
768 // other calls still work
769 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
770
771 constexpr size_t blockTimeMs = 500;
772 size_t epochMsBefore = epochMillis();
773 // after this, we should never see a response within this time
774 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
775
776 // this call should be blocked for blockTimeMs
777 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
778
779 size_t epochMsAfter = epochMillis();
780 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
781
782 for (auto& t : ts) t.join();
783}
784
Steven Morelandc1635952021-04-01 16:20:47 +0000785TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000786 constexpr size_t kNumThreads = 10;
787 constexpr size_t kNumCalls = kNumThreads + 3;
788 constexpr size_t kSleepMs = 500;
789
790 auto proc = createRpcTestSocketServerProcess(kNumThreads);
791
792 size_t epochMsBefore = epochMillis();
793
794 std::vector<std::thread> ts;
795 for (size_t i = 0; i < kNumCalls; i++) {
796 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
797 }
798
799 for (auto& t : ts) t.join();
800
801 size_t epochMsAfter = epochMillis();
802
803 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
804
805 // Potential flake, but make sure calls are handled in parallel.
806 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
807}
808
Steven Morelandc1635952021-04-01 16:20:47 +0000809TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000810 constexpr size_t kNumClientThreads = 10;
811 constexpr size_t kNumServerThreads = 10;
812 constexpr size_t kNumCalls = 100;
813
814 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
815
816 std::vector<std::thread> threads;
817 for (size_t i = 0; i < kNumClientThreads; i++) {
818 threads.push_back(std::thread([&] {
819 for (size_t j = 0; j < kNumCalls; j++) {
820 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000821 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000822 EXPECT_EQ(proc.rootBinder, out);
823 }
824 }));
825 }
826
827 for (auto& t : threads) t.join();
828}
829
Steven Morelandc6046982021-04-20 00:49:42 +0000830TEST_P(BinderRpc, OnewayStressTest) {
831 constexpr size_t kNumClientThreads = 10;
832 constexpr size_t kNumServerThreads = 10;
833 constexpr size_t kNumCalls = 100;
834
835 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
836
837 std::vector<std::thread> threads;
838 for (size_t i = 0; i < kNumClientThreads; i++) {
839 threads.push_back(std::thread([&] {
840 for (size_t j = 0; j < kNumCalls; j++) {
841 EXPECT_OK(proc.rootIface->sendString("a"));
842 }
843
844 // check threads are not stuck
845 EXPECT_OK(proc.rootIface->sleepMs(250));
846 }));
847 }
848
849 for (auto& t : threads) t.join();
850}
851
Steven Morelandc1635952021-04-01 16:20:47 +0000852TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000853 constexpr size_t kReallyLongTimeMs = 100;
854 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
855
Steven Morelandf5174272021-05-25 00:39:28 +0000856 auto proc = createRpcTestSocketServerProcess(1);
Steven Moreland5553ac42020-11-11 02:14:45 +0000857
858 size_t epochMsBefore = epochMillis();
859
860 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
861
862 size_t epochMsAfter = epochMillis();
863 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
864}
865
Steven Morelandc1635952021-04-01 16:20:47 +0000866TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000867 constexpr size_t kNumSleeps = 10;
868 constexpr size_t kNumExtraServerThreads = 4;
869 constexpr size_t kSleepMs = 50;
870
871 // make sure calls to the same object happen on the same thread
872 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
873
874 EXPECT_OK(proc.rootIface->lock());
875
876 for (size_t i = 0; i < kNumSleeps; i++) {
877 // these should be processed serially
878 proc.rootIface->sleepMsAsync(kSleepMs);
879 }
880 // should also be processesed serially
881 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
882
883 size_t epochMsBefore = epochMillis();
884 EXPECT_OK(proc.rootIface->lockUnlock());
885 size_t epochMsAfter = epochMillis();
886
887 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000888
889 // pending oneway transactions hold ref, make sure we read data on all
890 // sockets
891 std::vector<std::thread> threads;
892 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
893 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
894 }
895 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +0000896}
897
Steven Morelandc1635952021-04-01 16:20:47 +0000898TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000899 for (bool doDeathCleanup : {true, false}) {
900 auto proc = createRpcTestSocketServerProcess(1);
901
902 // make sure there is some state during crash
903 // 1. we hold their binder
904 sp<IBinderRpcSession> session;
905 EXPECT_OK(proc.rootIface->openSession("happy", &session));
906 // 2. they hold our binder
907 sp<IBinder> binder = new BBinder();
908 EXPECT_OK(proc.rootIface->holdBinder(binder));
909
910 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
911 << "Do death cleanup: " << doDeathCleanup;
912
Steven Morelandaf4ca712021-05-24 23:22:08 +0000913 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000914 }
915}
916
Steven Morelandd7302072021-05-15 01:32:04 +0000917TEST_P(BinderRpc, UseKernelBinderCallingId) {
918 auto proc = createRpcTestSocketServerProcess(1);
919
920 // we can't allocate IPCThreadState so actually the first time should
921 // succeed :(
922 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
923
924 // second time! we catch the error :)
925 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
926
Steven Morelandaf4ca712021-05-24 23:22:08 +0000927 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +0000928}
929
Steven Moreland37aff182021-03-26 02:04:16 +0000930TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
931 auto proc = createRpcTestSocketServerProcess(1);
932
933 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
934 ASSERT_NE(binder, nullptr);
935
936 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
937}
938
939TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
940 auto proc = createRpcTestSocketServerProcess(1);
941
942 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
943 ASSERT_NE(binder, nullptr);
944
945 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
946 ASSERT_NE(ndkBinder, nullptr);
947
948 std::string out;
949 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
950 ASSERT_TRUE(status.isOk()) << status.getDescription();
951 ASSERT_EQ("aoeuaoeu", out);
952}
953
Steven Moreland5553ac42020-11-11 02:14:45 +0000954ssize_t countFds() {
955 DIR* dir = opendir("/proc/self/fd/");
956 if (dir == nullptr) return -1;
957 ssize_t ret = 0;
958 dirent* ent;
959 while ((ent = readdir(dir)) != nullptr) ret++;
960 closedir(dir);
961 return ret;
962}
963
Steven Morelandc1635952021-04-01 16:20:47 +0000964TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000965 ssize_t beforeFds = countFds();
966 ASSERT_GE(beforeFds, 0);
967 {
968 auto proc = createRpcTestSocketServerProcess(10);
969 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
970 }
971 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
972}
973
Steven Morelandc1635952021-04-01 16:20:47 +0000974INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700975 ::testing::ValuesIn({
976 SocketType::UNIX,
Steven Morelandbd5002b2021-05-04 23:12:56 +0000977// TODO(b/185269356): working on host
Steven Morelandf6ec4632021-04-01 16:20:47 +0000978#ifdef __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700979 SocketType::VSOCK,
Steven Morelandbd5002b2021-05-04 23:12:56 +0000980#endif
Yifan Hong0d2bd112021-04-13 17:38:36 -0700981 SocketType::INET,
982 }),
Steven Morelandf6ec4632021-04-01 16:20:47 +0000983 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +0000984
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700985class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
986
987TEST_P(BinderRpcServerRootObject, WeakRootObject) {
988 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
989 auto setRootObject = [](bool isStrong) -> SetFn {
990 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
991 };
992
993 auto server = RpcServer::make();
994 auto [isStrong1, isStrong2] = GetParam();
995 auto binder1 = sp<BBinder>::make();
996 IBinder* binderRaw1 = binder1.get();
997 setRootObject(isStrong1)(server.get(), binder1);
998 EXPECT_EQ(binderRaw1, server->getRootObject());
999 binder1.clear();
1000 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1001
1002 auto binder2 = sp<BBinder>::make();
1003 IBinder* binderRaw2 = binder2.get();
1004 setRootObject(isStrong2)(server.get(), binder2);
1005 EXPECT_EQ(binderRaw2, server->getRootObject());
1006 binder2.clear();
1007 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1008}
1009
1010INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
1011 ::testing::Combine(::testing::Bool(), ::testing::Bool()));
1012
Yifan Hong1a235852021-05-13 16:07:47 -07001013class OneOffSignal {
1014public:
1015 // If notify() was previously called, or is called within |duration|, return true; else false.
1016 template <typename R, typename P>
1017 bool wait(std::chrono::duration<R, P> duration) {
1018 std::unique_lock<std::mutex> lock(mMutex);
1019 return mCv.wait_for(lock, duration, [this] { return mValue; });
1020 }
1021 void notify() {
1022 std::unique_lock<std::mutex> lock(mMutex);
1023 mValue = true;
1024 lock.unlock();
1025 mCv.notify_all();
1026 }
1027
1028private:
1029 std::mutex mMutex;
1030 std::condition_variable mCv;
1031 bool mValue = false;
1032};
1033
1034TEST(BinderRpc, Shutdown) {
1035 auto addr = allocateSocketAddress();
1036 unlink(addr.c_str());
1037 auto server = RpcServer::make();
1038 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1039 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1040 auto joinEnds = std::make_shared<OneOffSignal>();
1041
1042 // If things are broken and the thread never stops, don't block other tests. Because the thread
1043 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1044 // shared pointers are passed.
1045 std::thread([server, joinEnds] {
1046 server->join();
1047 joinEnds->notify();
1048 }).detach();
1049
1050 bool shutdown = false;
1051 for (int i = 0; i < 10 && !shutdown; i++) {
1052 usleep(300 * 1000); // 300ms; total 3s
1053 if (server->shutdown()) shutdown = true;
1054 }
1055 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1056
1057 ASSERT_TRUE(joinEnds->wait(2s))
1058 << "After server->shutdown() returns true, join() did not stop after 2s";
1059}
1060
Steven Morelandc1635952021-04-01 16:20:47 +00001061} // namespace android
1062
1063int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001064 ::testing::InitGoogleTest(&argc, argv);
1065 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1066 return RUN_ALL_TESTS();
1067}