blob: 9b2d88d5bc1e08b8f8dc8010438c985fe85f31b9 [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 Morelandd7302072021-05-15 01:32:04 +0000197 Status useKernelBinderCallingId() override {
198 // this is WRONG! It does not make sense when using RPC binder, and
199 // because it is SO wrong, and so much code calls this, it should abort!
200
201 (void)IPCThreadState::self()->getCallingPid();
202 return Status::ok();
203 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000204};
205sp<IBinder> MyBinderRpcTest::mHeldBinder;
206
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700207class Pipe {
208public:
209 Pipe() { CHECK(android::base::Pipe(&mRead, &mWrite)); }
210 Pipe(Pipe&&) = default;
211 android::base::borrowed_fd readEnd() { return mRead; }
212 android::base::borrowed_fd writeEnd() { return mWrite; }
213
214private:
215 android::base::unique_fd mRead;
216 android::base::unique_fd mWrite;
217};
218
Steven Moreland5553ac42020-11-11 02:14:45 +0000219class Process {
220public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700221 Process(Process&&) = default;
222 Process(const std::function<void(Pipe*)>& f) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000223 if (0 == (mPid = fork())) {
224 // racey: assume parent doesn't crash before this is set
225 prctl(PR_SET_PDEATHSIG, SIGHUP);
226
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700227 f(&mPipe);
Steven Moreland5553ac42020-11-11 02:14:45 +0000228 }
229 }
230 ~Process() {
231 if (mPid != 0) {
232 kill(mPid, SIGKILL);
233 }
234 }
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700235 Pipe* getPipe() { return &mPipe; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000236
237private:
238 pid_t mPid = 0;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700239 Pipe mPipe;
Steven Moreland5553ac42020-11-11 02:14:45 +0000240};
241
242static std::string allocateSocketAddress() {
243 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000244 std::string temp = getenv("TMPDIR") ?: "/tmp";
245 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000246};
247
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000248struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000249 // reference to process hosting a socket server
250 Process host;
251
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000252 struct SessionInfo {
253 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000254 sp<IBinder> root;
255 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000256
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000257 // client session objects associated with other process
258 // each one represents a separate session
259 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000260
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000261 ProcessSession(ProcessSession&&) = default;
262 ~ProcessSession() {
263 for (auto& session : sessions) {
264 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000265 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000266
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000267 for (auto& info : sessions) {
268 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000269
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000270 EXPECT_NE(nullptr, session);
271 EXPECT_NE(nullptr, session->state());
272 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000273
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000274 wp<RpcSession> weakSession = session;
275 session = nullptr;
276 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000277 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000278 }
279};
280
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000281// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000282// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000283struct BinderRpcTestProcessSession {
284 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000285
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000286 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000287 sp<IBinder> rootBinder;
288
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000289 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000290 sp<IBinderRpcTest> rootIface;
291
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000292 // whether session should be invalidated by end of run
Steven Moreland736664b2021-05-01 04:27:25 +0000293 bool expectInvalid = false;
294
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000295 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
296 ~BinderRpcTestProcessSession() {
Steven Moreland736664b2021-05-01 04:27:25 +0000297 if (!expectInvalid) {
298 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000299 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000300 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000301 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000302 for (auto remoteCount : remoteCounts) {
303 EXPECT_EQ(remoteCount, 1);
304 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000305 }
306
307 rootIface = nullptr;
308 rootBinder = nullptr;
309 }
310};
311
Steven Morelandc1635952021-04-01 16:20:47 +0000312enum class SocketType {
313 UNIX,
314 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700315 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000316};
317static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
318 switch (info.param) {
319 case SocketType::UNIX:
320 return "unix_domain_socket";
321 case SocketType::VSOCK:
322 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700323 case SocketType::INET:
324 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000325 default:
326 LOG_ALWAYS_FATAL("Unknown socket type");
327 return "";
328 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000329}
Steven Morelandc1635952021-04-01 16:20:47 +0000330class BinderRpc : public ::testing::TestWithParam<SocketType> {
331public:
332 // This creates a new process serving an interface on a certain number of
333 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000334 ProcessSession createRpcTestSocketServerProcess(
335 size_t numThreads, size_t numSessions,
Steven Moreland736664b2021-05-01 04:27:25 +0000336 const std::function<void(const sp<RpcServer>&)>& configure) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000337 CHECK_GE(numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000338
Steven Morelandc1635952021-04-01 16:20:47 +0000339 SocketType socketType = GetParam();
340
341 std::string addr = allocateSocketAddress();
342 unlink(addr.c_str());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700343 static unsigned int vsockPort = 3456;
344 vsockPort++;
Steven Morelandc1635952021-04-01 16:20:47 +0000345
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000346 auto ret = ProcessSession{
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700347 .host = Process([&](Pipe* pipe) {
Steven Morelandc1635952021-04-01 16:20:47 +0000348 sp<RpcServer> server = RpcServer::make();
349
350 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Morelandf137de92021-04-24 01:54:26 +0000351 server->setMaxThreads(numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000352
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000353 unsigned int outPort = 0;
354
Steven Morelandc1635952021-04-01 16:20:47 +0000355 switch (socketType) {
356 case SocketType::UNIX:
Steven Moreland611d15f2021-05-01 01:28:27 +0000357 CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000358 break;
359 case SocketType::VSOCK:
Steven Moreland611d15f2021-05-01 01:28:27 +0000360 CHECK(server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000361 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700362 case SocketType::INET: {
Steven Moreland611d15f2021-05-01 01:28:27 +0000363 CHECK(server->setupInetServer(0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700364 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700365 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700366 }
Steven Morelandc1635952021-04-01 16:20:47 +0000367 default:
368 LOG_ALWAYS_FATAL("Unknown socket type");
369 }
370
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000371 CHECK(android::base::WriteFully(pipe->writeEnd(), &outPort, sizeof(outPort)));
372
Steven Moreland611d15f2021-05-01 01:28:27 +0000373 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000374
Steven Morelandf137de92021-04-24 01:54:26 +0000375 server->join();
Steven Morelandc1635952021-04-01 16:20:47 +0000376 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000377 };
378
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000379 // always read socket, so that we have waited for the server to start
380 unsigned int outPort = 0;
381 CHECK(android::base::ReadFully(ret.host.getPipe()->readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700382 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000383 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700384 }
385
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000386 for (size_t i = 0; i < numSessions; i++) {
387 sp<RpcSession> session = RpcSession::make();
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000388 switch (socketType) {
389 case SocketType::UNIX:
390 if (session->setupUnixDomainClient(addr.c_str())) goto success;
391 break;
392 case SocketType::VSOCK:
393 if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
394 break;
395 case SocketType::INET:
396 if (session->setupInetClient("127.0.0.1", outPort)) goto success;
397 break;
398 default:
399 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000400 }
Steven Moreland736664b2021-05-01 04:27:25 +0000401 LOG_ALWAYS_FATAL("Could not connect");
402 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000403 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000404 }
Steven Morelandc1635952021-04-01 16:20:47 +0000405 return ret;
406 }
407
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000408 BinderRpcTestProcessSession createRpcTestSocketServerProcess(size_t numThreads,
409 size_t numSessions = 1) {
410 BinderRpcTestProcessSession ret{
411 .proc = createRpcTestSocketServerProcess(numThreads, numSessions,
Steven Moreland611d15f2021-05-01 01:28:27 +0000412 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000413 sp<MyBinderRpcTest> service =
414 new MyBinderRpcTest;
415 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000416 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000417 }),
418 };
419
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000421 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
422
423 return ret;
424 }
425};
426
427TEST_P(BinderRpc, RootObjectIsNull) {
Steven Moreland736664b2021-05-01 04:27:25 +0000428 auto proc = createRpcTestSocketServerProcess(1, 1, [](const sp<RpcServer>& server) {
Steven Moreland611d15f2021-05-01 01:28:27 +0000429 // this is the default, but to be explicit
430 server->setRootObject(nullptr);
431 });
Steven Moreland5553ac42020-11-11 02:14:45 +0000432
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000433 EXPECT_EQ(nullptr, proc.sessions.at(0).root);
Steven Moreland5553ac42020-11-11 02:14:45 +0000434}
435
Steven Morelandc1635952021-04-01 16:20:47 +0000436TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000437 auto proc = createRpcTestSocketServerProcess(1);
438 ASSERT_NE(proc.rootBinder, nullptr);
439 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
440}
441
Steven Moreland4cf688f2021-03-31 01:48:58 +0000442TEST_P(BinderRpc, GetInterfaceDescriptor) {
443 auto proc = createRpcTestSocketServerProcess(1);
444 ASSERT_NE(proc.rootBinder, nullptr);
445 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
446}
447
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000448TEST_P(BinderRpc, MultipleSessions) {
449 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 5 /*sessions*/);
450 for (auto session : proc.proc.sessions) {
451 ASSERT_NE(nullptr, session.root);
452 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000453 }
454}
455
Steven Morelandc1635952021-04-01 16:20:47 +0000456TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000457 auto proc = createRpcTestSocketServerProcess(1);
458 Parcel data;
459 Parcel reply;
460 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
461}
462
Steven Moreland67753c32021-04-02 18:45:19 +0000463TEST_P(BinderRpc, AppendSeparateFormats) {
464 auto proc = createRpcTestSocketServerProcess(1);
465
466 Parcel p1;
467 p1.markForBinder(proc.rootBinder);
468 p1.writeInt32(3);
469
470 Parcel p2;
471
472 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
473 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
474}
475
Steven Morelandc1635952021-04-01 16:20:47 +0000476TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000477 auto proc = createRpcTestSocketServerProcess(1);
478 Parcel data;
479 data.markForBinder(proc.rootBinder);
480 Parcel reply;
481 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
482}
483
Steven Morelandc1635952021-04-01 16:20:47 +0000484TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000485 auto proc = createRpcTestSocketServerProcess(1);
486 EXPECT_OK(proc.rootIface->sendString("asdf"));
487}
488
Steven Morelandc1635952021-04-01 16:20:47 +0000489TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000490 auto proc = createRpcTestSocketServerProcess(1);
491 std::string doubled;
492 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
493 EXPECT_EQ("cool cool ", doubled);
494}
495
Steven Morelandc1635952021-04-01 16:20:47 +0000496TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000497 auto proc = createRpcTestSocketServerProcess(1);
498 std::string single = std::string(1024, 'a');
499 std::string doubled;
500 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
501 EXPECT_EQ(single + single, doubled);
502}
503
Steven Morelandc1635952021-04-01 16:20:47 +0000504TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000505 auto proc = createRpcTestSocketServerProcess(1);
506
507 int32_t pingResult;
508 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
509 EXPECT_EQ(OK, pingResult);
510
511 EXPECT_EQ(0, MyBinderRpcSession::gNum);
512}
513
Steven Morelandc1635952021-04-01 16:20:47 +0000514TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000515 auto proc = createRpcTestSocketServerProcess(1);
516
517 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
518 sp<IBinder> outBinder;
519 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
520 EXPECT_EQ(inBinder, outBinder);
521
522 wp<IBinder> weak = inBinder;
523 inBinder = nullptr;
524 outBinder = nullptr;
525
526 // Force reading a reply, to process any pending dec refs from the other
527 // process (the other process will process dec refs there before processing
528 // the ping here).
529 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
530
531 EXPECT_EQ(nullptr, weak.promote());
532
533 EXPECT_EQ(0, MyBinderRpcSession::gNum);
534}
535
Steven Morelandc1635952021-04-01 16:20:47 +0000536TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000537 auto proc = createRpcTestSocketServerProcess(1);
538
539 sp<IBinderRpcSession> session;
540 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
541
542 sp<IBinder> inBinder = IInterface::asBinder(session);
543 sp<IBinder> outBinder;
544 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
545 EXPECT_EQ(inBinder, outBinder);
546
547 wp<IBinder> weak = inBinder;
548 session = nullptr;
549 inBinder = nullptr;
550 outBinder = nullptr;
551
552 // Force reading a reply, to process any pending dec refs from the other
553 // process (the other process will process dec refs there before processing
554 // the ping here).
555 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
556
557 EXPECT_EQ(nullptr, weak.promote());
558}
559
Steven Morelandc1635952021-04-01 16:20:47 +0000560TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000561 auto proc = createRpcTestSocketServerProcess(1);
562
563 sp<IBinder> outBinder;
564 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
565 EXPECT_EQ(nullptr, outBinder);
566}
567
Steven Morelandc1635952021-04-01 16:20:47 +0000568TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000569 auto proc = createRpcTestSocketServerProcess(1);
570
571 IBinder* ptr = nullptr;
572 {
573 sp<IBinder> binder = new BBinder();
574 ptr = binder.get();
575 EXPECT_OK(proc.rootIface->holdBinder(binder));
576 }
577
578 sp<IBinder> held;
579 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
580
581 EXPECT_EQ(held.get(), ptr);
582
583 // stop holding binder, because we test to make sure references are cleaned
584 // up
585 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
586 // and flush ref counts
587 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
588}
589
590// START TESTS FOR LIMITATIONS OF SOCKET BINDER
591// These are behavioral differences form regular binder, where certain usecases
592// aren't supported.
593
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000594TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000595 auto proc1 = createRpcTestSocketServerProcess(1);
596 auto proc2 = createRpcTestSocketServerProcess(1);
597
598 sp<IBinder> outBinder;
599 EXPECT_EQ(INVALID_OPERATION,
600 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
601}
602
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000603TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
604 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 2 /*sessions*/);
Steven Moreland736664b2021-05-01 04:27:25 +0000605
606 sp<IBinder> outBinder;
607 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000608 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000609 .transactionError());
610}
611
Steven Morelandc1635952021-04-01 16:20:47 +0000612TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000613 auto proc = createRpcTestSocketServerProcess(1);
614
615 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
616 sp<IBinder> outBinder;
617 EXPECT_EQ(INVALID_OPERATION,
618 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
619}
620
Steven Morelandc1635952021-04-01 16:20:47 +0000621TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000622 auto proc = createRpcTestSocketServerProcess(1);
623
624 // for historical reasons, IServiceManager interface only returns the
625 // exception code
626 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
627 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
628}
629
630// END TESTS FOR LIMITATIONS OF SOCKET BINDER
631
Steven Morelandc1635952021-04-01 16:20:47 +0000632TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000633 auto proc = createRpcTestSocketServerProcess(1);
634
635 sp<IBinder> outBinder;
636 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
637 EXPECT_EQ(proc.rootBinder, outBinder);
638}
639
Steven Morelandc1635952021-04-01 16:20:47 +0000640TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000641 auto proc = createRpcTestSocketServerProcess(1);
642
643 auto nastyNester = sp<MyBinderRpcTest>::make();
644 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
645
646 wp<IBinder> weak = nastyNester;
647 nastyNester = nullptr;
648 EXPECT_EQ(nullptr, weak.promote());
649}
650
Steven Morelandc1635952021-04-01 16:20:47 +0000651TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000652 auto proc = createRpcTestSocketServerProcess(1);
653
654 sp<IBinder> a;
655 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
656
657 sp<IBinder> b;
658 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
659
660 EXPECT_EQ(a, b);
661}
662
Steven Morelandc1635952021-04-01 16:20:47 +0000663TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000664 auto proc = createRpcTestSocketServerProcess(1);
665
666 sp<IBinder> a;
667 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
668 wp<IBinder> weak = a;
669 a = nullptr;
670
671 sp<IBinder> b;
672 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
673
674 // this is the wrong behavior, since BpBinder
675 // doesn't implement onIncStrongAttempted
676 // but make sure there is no crash
677 EXPECT_EQ(nullptr, weak.promote());
678
679 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
680
681 // In order to fix this:
682 // - need to have incStrongAttempted reflected across IPC boundary (wait for
683 // response to promote - round trip...)
684 // - sendOnLastWeakRef, to delete entries out of RpcState table
685 EXPECT_EQ(b, weak.promote());
686}
687
688#define expectSessions(expected, iface) \
689 do { \
690 int session; \
691 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
692 EXPECT_EQ(expected, session); \
693 } while (false)
694
Steven Morelandc1635952021-04-01 16:20:47 +0000695TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000696 auto proc = createRpcTestSocketServerProcess(1);
697
698 sp<IBinderRpcSession> session;
699 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
700 std::string out;
701 EXPECT_OK(session->getName(&out));
702 EXPECT_EQ("aoeu", out);
703
704 expectSessions(1, proc.rootIface);
705 session = nullptr;
706 expectSessions(0, proc.rootIface);
707}
708
Steven Morelandc1635952021-04-01 16:20:47 +0000709TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000710 auto proc = createRpcTestSocketServerProcess(1);
711
712 std::vector<sp<IBinderRpcSession>> sessions;
713
714 for (size_t i = 0; i < 15; i++) {
715 expectSessions(i, proc.rootIface);
716 sp<IBinderRpcSession> session;
717 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
718 sessions.push_back(session);
719 }
720 expectSessions(sessions.size(), proc.rootIface);
721 for (size_t i = 0; i < sessions.size(); i++) {
722 std::string out;
723 EXPECT_OK(sessions.at(i)->getName(&out));
724 EXPECT_EQ(std::to_string(i), out);
725 }
726 expectSessions(sessions.size(), proc.rootIface);
727
728 while (!sessions.empty()) {
729 sessions.pop_back();
730 expectSessions(sessions.size(), proc.rootIface);
731 }
732 expectSessions(0, proc.rootIface);
733}
734
735size_t epochMillis() {
736 using std::chrono::duration_cast;
737 using std::chrono::milliseconds;
738 using std::chrono::seconds;
739 using std::chrono::system_clock;
740 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
741}
742
Steven Morelandc1635952021-04-01 16:20:47 +0000743TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000744 constexpr size_t kNumThreads = 10;
745
746 auto proc = createRpcTestSocketServerProcess(kNumThreads);
747
748 EXPECT_OK(proc.rootIface->lock());
749
750 // block all but one thread taking locks
751 std::vector<std::thread> ts;
752 for (size_t i = 0; i < kNumThreads - 1; i++) {
753 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
754 }
755
756 usleep(100000); // give chance for calls on other threads
757
758 // other calls still work
759 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
760
761 constexpr size_t blockTimeMs = 500;
762 size_t epochMsBefore = epochMillis();
763 // after this, we should never see a response within this time
764 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
765
766 // this call should be blocked for blockTimeMs
767 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
768
769 size_t epochMsAfter = epochMillis();
770 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
771
772 for (auto& t : ts) t.join();
773}
774
Steven Morelandc1635952021-04-01 16:20:47 +0000775TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000776 constexpr size_t kNumThreads = 10;
777 constexpr size_t kNumCalls = kNumThreads + 3;
778 constexpr size_t kSleepMs = 500;
779
780 auto proc = createRpcTestSocketServerProcess(kNumThreads);
781
782 size_t epochMsBefore = epochMillis();
783
784 std::vector<std::thread> ts;
785 for (size_t i = 0; i < kNumCalls; i++) {
786 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
787 }
788
789 for (auto& t : ts) t.join();
790
791 size_t epochMsAfter = epochMillis();
792
793 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
794
795 // Potential flake, but make sure calls are handled in parallel.
796 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
797}
798
Steven Morelandc1635952021-04-01 16:20:47 +0000799TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000800 constexpr size_t kNumClientThreads = 10;
801 constexpr size_t kNumServerThreads = 10;
802 constexpr size_t kNumCalls = 100;
803
804 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
805
806 std::vector<std::thread> threads;
807 for (size_t i = 0; i < kNumClientThreads; i++) {
808 threads.push_back(std::thread([&] {
809 for (size_t j = 0; j < kNumCalls; j++) {
810 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000811 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000812 EXPECT_EQ(proc.rootBinder, out);
813 }
814 }));
815 }
816
817 for (auto& t : threads) t.join();
818}
819
Steven Morelandc6046982021-04-20 00:49:42 +0000820TEST_P(BinderRpc, OnewayStressTest) {
821 constexpr size_t kNumClientThreads = 10;
822 constexpr size_t kNumServerThreads = 10;
823 constexpr size_t kNumCalls = 100;
824
825 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
826
827 std::vector<std::thread> threads;
828 for (size_t i = 0; i < kNumClientThreads; i++) {
829 threads.push_back(std::thread([&] {
830 for (size_t j = 0; j < kNumCalls; j++) {
831 EXPECT_OK(proc.rootIface->sendString("a"));
832 }
833
834 // check threads are not stuck
835 EXPECT_OK(proc.rootIface->sleepMs(250));
836 }));
837 }
838
839 for (auto& t : threads) t.join();
840}
841
Steven Morelandc1635952021-04-01 16:20:47 +0000842TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000843 constexpr size_t kReallyLongTimeMs = 100;
844 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
845
Steven Morelandf5174272021-05-25 00:39:28 +0000846 auto proc = createRpcTestSocketServerProcess(1);
Steven Moreland5553ac42020-11-11 02:14:45 +0000847
848 size_t epochMsBefore = epochMillis();
849
850 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
851
852 size_t epochMsAfter = epochMillis();
853 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
854}
855
Steven Morelandc1635952021-04-01 16:20:47 +0000856TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000857 constexpr size_t kNumSleeps = 10;
858 constexpr size_t kNumExtraServerThreads = 4;
859 constexpr size_t kSleepMs = 50;
860
861 // make sure calls to the same object happen on the same thread
862 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
863
864 EXPECT_OK(proc.rootIface->lock());
865
866 for (size_t i = 0; i < kNumSleeps; i++) {
867 // these should be processed serially
868 proc.rootIface->sleepMsAsync(kSleepMs);
869 }
870 // should also be processesed serially
871 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
872
873 size_t epochMsBefore = epochMillis();
874 EXPECT_OK(proc.rootIface->lockUnlock());
875 size_t epochMsAfter = epochMillis();
876
877 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000878
879 // pending oneway transactions hold ref, make sure we read data on all
880 // sockets
881 std::vector<std::thread> threads;
882 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
883 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
884 }
885 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +0000886}
887
Steven Morelandc1635952021-04-01 16:20:47 +0000888TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000889 for (bool doDeathCleanup : {true, false}) {
890 auto proc = createRpcTestSocketServerProcess(1);
891
892 // make sure there is some state during crash
893 // 1. we hold their binder
894 sp<IBinderRpcSession> session;
895 EXPECT_OK(proc.rootIface->openSession("happy", &session));
896 // 2. they hold our binder
897 sp<IBinder> binder = new BBinder();
898 EXPECT_OK(proc.rootIface->holdBinder(binder));
899
900 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
901 << "Do death cleanup: " << doDeathCleanup;
902
Steven Moreland736664b2021-05-01 04:27:25 +0000903 proc.expectInvalid = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000904 }
905}
906
Steven Morelandd7302072021-05-15 01:32:04 +0000907TEST_P(BinderRpc, UseKernelBinderCallingId) {
908 auto proc = createRpcTestSocketServerProcess(1);
909
910 // we can't allocate IPCThreadState so actually the first time should
911 // succeed :(
912 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
913
914 // second time! we catch the error :)
915 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
916
917 proc.expectInvalid = true;
918}
919
Steven Moreland37aff182021-03-26 02:04:16 +0000920TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
921 auto proc = createRpcTestSocketServerProcess(1);
922
923 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
924 ASSERT_NE(binder, nullptr);
925
926 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
927}
928
929TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
930 auto proc = createRpcTestSocketServerProcess(1);
931
932 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
933 ASSERT_NE(binder, nullptr);
934
935 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
936 ASSERT_NE(ndkBinder, nullptr);
937
938 std::string out;
939 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
940 ASSERT_TRUE(status.isOk()) << status.getDescription();
941 ASSERT_EQ("aoeuaoeu", out);
942}
943
Steven Moreland5553ac42020-11-11 02:14:45 +0000944ssize_t countFds() {
945 DIR* dir = opendir("/proc/self/fd/");
946 if (dir == nullptr) return -1;
947 ssize_t ret = 0;
948 dirent* ent;
949 while ((ent = readdir(dir)) != nullptr) ret++;
950 closedir(dir);
951 return ret;
952}
953
Steven Morelandc1635952021-04-01 16:20:47 +0000954TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000955 ssize_t beforeFds = countFds();
956 ASSERT_GE(beforeFds, 0);
957 {
958 auto proc = createRpcTestSocketServerProcess(10);
959 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
960 }
961 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
962}
963
Steven Morelandc1635952021-04-01 16:20:47 +0000964INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700965 ::testing::ValuesIn({
966 SocketType::UNIX,
Steven Morelandbd5002b2021-05-04 23:12:56 +0000967// TODO(b/185269356): working on host
Steven Morelandf6ec4632021-04-01 16:20:47 +0000968#ifdef __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -0700969 SocketType::VSOCK,
Steven Morelandbd5002b2021-05-04 23:12:56 +0000970#endif
Yifan Hong0d2bd112021-04-13 17:38:36 -0700971 SocketType::INET,
972 }),
Steven Morelandf6ec4632021-04-01 16:20:47 +0000973 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +0000974
Yifan Hong4ffb0c72021-05-07 18:35:14 -0700975class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
976
977TEST_P(BinderRpcServerRootObject, WeakRootObject) {
978 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
979 auto setRootObject = [](bool isStrong) -> SetFn {
980 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
981 };
982
983 auto server = RpcServer::make();
984 auto [isStrong1, isStrong2] = GetParam();
985 auto binder1 = sp<BBinder>::make();
986 IBinder* binderRaw1 = binder1.get();
987 setRootObject(isStrong1)(server.get(), binder1);
988 EXPECT_EQ(binderRaw1, server->getRootObject());
989 binder1.clear();
990 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
991
992 auto binder2 = sp<BBinder>::make();
993 IBinder* binderRaw2 = binder2.get();
994 setRootObject(isStrong2)(server.get(), binder2);
995 EXPECT_EQ(binderRaw2, server->getRootObject());
996 binder2.clear();
997 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
998}
999
1000INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
1001 ::testing::Combine(::testing::Bool(), ::testing::Bool()));
1002
Yifan Hong1a235852021-05-13 16:07:47 -07001003class OneOffSignal {
1004public:
1005 // If notify() was previously called, or is called within |duration|, return true; else false.
1006 template <typename R, typename P>
1007 bool wait(std::chrono::duration<R, P> duration) {
1008 std::unique_lock<std::mutex> lock(mMutex);
1009 return mCv.wait_for(lock, duration, [this] { return mValue; });
1010 }
1011 void notify() {
1012 std::unique_lock<std::mutex> lock(mMutex);
1013 mValue = true;
1014 lock.unlock();
1015 mCv.notify_all();
1016 }
1017
1018private:
1019 std::mutex mMutex;
1020 std::condition_variable mCv;
1021 bool mValue = false;
1022};
1023
1024TEST(BinderRpc, Shutdown) {
1025 auto addr = allocateSocketAddress();
1026 unlink(addr.c_str());
1027 auto server = RpcServer::make();
1028 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1029 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1030 auto joinEnds = std::make_shared<OneOffSignal>();
1031
1032 // If things are broken and the thread never stops, don't block other tests. Because the thread
1033 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1034 // shared pointers are passed.
1035 std::thread([server, joinEnds] {
1036 server->join();
1037 joinEnds->notify();
1038 }).detach();
1039
1040 bool shutdown = false;
1041 for (int i = 0; i < 10 && !shutdown; i++) {
1042 usleep(300 * 1000); // 300ms; total 3s
1043 if (server->shutdown()) shutdown = true;
1044 }
1045 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1046
1047 ASSERT_TRUE(joinEnds->wait(2s))
1048 << "After server->shutdown() returns true, join() did not stop after 2s";
1049}
1050
Steven Morelandc1635952021-04-01 16:20:47 +00001051} // namespace android
1052
1053int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001054 ::testing::InitGoogleTest(&argc, argv);
1055 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1056 return RUN_ALL_TESTS();
1057}