blob: cda0fc96e4e08d03970cae8efe34349038f2302e [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 Moreland659416d2021-05-11 00:47:50 +000017#include <BnBinderRpcCallback.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000018#include <BnBinderRpcSession.h>
19#include <BnBinderRpcTest.h>
Steven Moreland37aff182021-03-26 02:04:16 +000020#include <aidl/IBinderRpcTest.h>
Yifan Hong6d82c8a2021-04-26 20:26:45 -070021#include <android-base/file.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000022#include <android-base/logging.h>
Steven Moreland37aff182021-03-26 02:04:16 +000023#include <android/binder_auto_utils.h>
24#include <android/binder_libbinder.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000025#include <binder/Binder.h>
26#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000027#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000028#include <binder/IServiceManager.h>
29#include <binder/ProcessState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000030#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000031#include <binder/RpcSession.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000032#include <gtest/gtest.h>
33
Steven Morelandc1635952021-04-01 16:20:47 +000034#include <chrono>
35#include <cstdlib>
36#include <iostream>
37#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000038#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000039
Steven Morelandc1635952021-04-01 16:20:47 +000040#include <sys/prctl.h>
41#include <unistd.h>
42
Steven Morelandbd5002b2021-05-04 23:12:56 +000043#include "../RpcState.h" // for debugging
44#include "../vm_sockets.h" // for VMADDR_*
Steven Moreland5553ac42020-11-11 02:14:45 +000045
Yifan Hong1a235852021-05-13 16:07:47 -070046using namespace std::chrono_literals;
47
Steven Moreland5553ac42020-11-11 02:14:45 +000048namespace android {
49
Steven Moreland1fda67b2021-04-02 18:35:50 +000050TEST(BinderRpcParcel, EntireParcelFormatted) {
51 Parcel p;
52 p.writeInt32(3);
53
54 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
55}
56
Yifan Hong00aeb762021-05-12 17:07:36 -070057TEST(BinderRpc, SetExternalServer) {
58 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
59 int sinkFd = sink.get();
60 auto server = RpcServer::make();
61 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
62 ASSERT_FALSE(server->hasServer());
63 ASSERT_TRUE(server->setupExternalServer(std::move(sink)));
64 ASSERT_TRUE(server->hasServer());
65 base::unique_fd retrieved = server->releaseServer();
66 ASSERT_FALSE(server->hasServer());
67 ASSERT_EQ(sinkFd, retrieved.get());
68}
69
Steven Moreland5553ac42020-11-11 02:14:45 +000070using android::binder::Status;
71
72#define EXPECT_OK(status) \
73 do { \
74 Status stat = (status); \
75 EXPECT_TRUE(stat.isOk()) << stat; \
76 } while (false)
77
78class MyBinderRpcSession : public BnBinderRpcSession {
79public:
80 static std::atomic<int32_t> gNum;
81
82 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
83 Status getName(std::string* name) override {
84 *name = mName;
85 return Status::ok();
86 }
87 ~MyBinderRpcSession() { gNum--; }
88
89private:
90 std::string mName;
91};
92std::atomic<int32_t> MyBinderRpcSession::gNum;
93
Steven Moreland659416d2021-05-11 00:47:50 +000094class MyBinderRpcCallback : public BnBinderRpcCallback {
95 Status sendCallback(const std::string& value) {
96 std::unique_lock _l(mMutex);
97 mValues.push_back(value);
98 _l.unlock();
99 mCv.notify_one();
100 return Status::ok();
101 }
102 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
103
104public:
105 std::mutex mMutex;
106 std::condition_variable mCv;
107 std::vector<std::string> mValues;
108};
109
Steven Moreland5553ac42020-11-11 02:14:45 +0000110class MyBinderRpcTest : public BnBinderRpcTest {
111public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000112 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +0000113
114 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000115 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000116 return Status::ok();
117 }
118 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000119 *strstr = str + str;
120 return Status::ok();
121 }
Steven Moreland736664b2021-05-01 04:27:25 +0000122 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000123 sp<RpcServer> spServer = server.promote();
124 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000125 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
126 }
Steven Moreland736664b2021-05-01 04:27:25 +0000127 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000128 for (auto session : spServer->listSessions()) {
129 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000130 if (count != 1) {
131 // this is called when there is only one binder held remaining,
132 // so to aid debugging
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000133 session->state()->dump();
Steven Moreland611d15f2021-05-01 01:28:27 +0000134 }
Steven Moreland736664b2021-05-01 04:27:25 +0000135 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000136 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000137 return Status::ok();
138 }
139 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
140 if (binder == nullptr) {
141 std::cout << "Received null binder!" << std::endl;
142 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
143 }
144 *out = binder->pingBinder();
145 return Status::ok();
146 }
147 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
148 *out = binder;
149 return Status::ok();
150 }
151 static sp<IBinder> mHeldBinder;
152 Status holdBinder(const sp<IBinder>& binder) override {
153 mHeldBinder = binder;
154 return Status::ok();
155 }
156 Status getHeldBinder(sp<IBinder>* held) override {
157 *held = mHeldBinder;
158 return Status::ok();
159 }
160 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
161 if (count <= 0) return Status::ok();
162 return binder->nestMe(this, count - 1);
163 }
164 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
165 static sp<IBinder> binder = new BBinder;
166 *out = binder;
167 return Status::ok();
168 }
169 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
170 *out = new MyBinderRpcSession(name);
171 return Status::ok();
172 }
173 Status getNumOpenSessions(int32_t* out) override {
174 *out = MyBinderRpcSession::gNum;
175 return Status::ok();
176 }
177
178 std::mutex blockMutex;
179 Status lock() override {
180 blockMutex.lock();
181 return Status::ok();
182 }
183 Status unlockInMsAsync(int32_t ms) override {
184 usleep(ms * 1000);
185 blockMutex.unlock();
186 return Status::ok();
187 }
188 Status lockUnlock() override {
189 std::lock_guard<std::mutex> _l(blockMutex);
190 return Status::ok();
191 }
192
193 Status sleepMs(int32_t ms) override {
194 usleep(ms * 1000);
195 return Status::ok();
196 }
197
198 Status sleepMsAsync(int32_t ms) override {
199 // In-process binder calls are asynchronous, but the call to this method
200 // is synchronous wrt its client. This in/out-process threading model
201 // diffentiation is a classic binder leaky abstraction (for better or
202 // worse) and is preserved here the way binder sockets plugs itself
203 // into BpBinder, as nothing is changed at the higher levels
204 // (IInterface) which result in this behavior.
205 return sleepMs(ms);
206 }
207
Steven Moreland659416d2021-05-11 00:47:50 +0000208 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
209 const std::string& value) override {
210 if (callback == nullptr) {
211 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
212 }
213
214 if (delayed) {
215 std::thread([=]() {
216 ALOGE("Executing delayed callback: '%s'", value.c_str());
217 (void)doCallback(callback, oneway, false, value);
218 }).detach();
219 return Status::ok();
220 }
221
222 if (oneway) {
223 return callback->sendOnewayCallback(value);
224 }
225
226 return callback->sendCallback(value);
227 }
228
Steven Moreland5553ac42020-11-11 02:14:45 +0000229 Status die(bool cleanup) override {
230 if (cleanup) {
231 exit(1);
232 } else {
233 _exit(1);
234 }
235 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000236
237 Status scheduleShutdown() override {
238 sp<RpcServer> strongServer = server.promote();
239 if (strongServer == nullptr) {
240 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
241 }
242 std::thread([=] {
243 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
244 }).detach();
245 return Status::ok();
246 }
247
Steven Morelandd7302072021-05-15 01:32:04 +0000248 Status useKernelBinderCallingId() override {
249 // this is WRONG! It does not make sense when using RPC binder, and
250 // because it is SO wrong, and so much code calls this, it should abort!
251
252 (void)IPCThreadState::self()->getCallingPid();
253 return Status::ok();
254 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000255};
256sp<IBinder> MyBinderRpcTest::mHeldBinder;
257
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700258class Pipe {
259public:
260 Pipe() { CHECK(android::base::Pipe(&mRead, &mWrite)); }
261 Pipe(Pipe&&) = default;
262 android::base::borrowed_fd readEnd() { return mRead; }
263 android::base::borrowed_fd writeEnd() { return mWrite; }
264
265private:
266 android::base::unique_fd mRead;
267 android::base::unique_fd mWrite;
268};
269
Steven Moreland5553ac42020-11-11 02:14:45 +0000270class Process {
271public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700272 Process(Process&&) = default;
273 Process(const std::function<void(Pipe*)>& f) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000274 if (0 == (mPid = fork())) {
275 // racey: assume parent doesn't crash before this is set
276 prctl(PR_SET_PDEATHSIG, SIGHUP);
277
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700278 f(&mPipe);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000279
280 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000281 }
282 }
283 ~Process() {
284 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000285 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000286 }
287 }
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700288 Pipe* getPipe() { return &mPipe; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000289
290private:
291 pid_t mPid = 0;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700292 Pipe mPipe;
Steven Moreland5553ac42020-11-11 02:14:45 +0000293};
294
295static std::string allocateSocketAddress() {
296 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000297 std::string temp = getenv("TMPDIR") ?: "/tmp";
298 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000299};
300
Steven Morelandda573042021-06-12 01:13:45 +0000301static unsigned int allocateVsockPort() {
302 static unsigned int vsockPort = 3456;
303 return vsockPort++;
304}
305
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000306struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000307 // reference to process hosting a socket server
308 Process host;
309
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000310 struct SessionInfo {
311 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000312 sp<IBinder> root;
313 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000314
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000315 // client session objects associated with other process
316 // each one represents a separate session
317 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000318
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000319 ProcessSession(ProcessSession&&) = default;
320 ~ProcessSession() {
321 for (auto& session : sessions) {
322 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000323 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000324
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000325 for (auto& info : sessions) {
326 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000327
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000328 EXPECT_NE(nullptr, session);
329 EXPECT_NE(nullptr, session->state());
330 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000331
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000332 wp<RpcSession> weakSession = session;
333 session = nullptr;
334 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000335 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000336 }
337};
338
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000339// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000340// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000341struct BinderRpcTestProcessSession {
342 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000343
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000344 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000345 sp<IBinder> rootBinder;
346
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000347 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000348 sp<IBinderRpcTest> rootIface;
349
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000350 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000351 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000352
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000353 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
354 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000355 EXPECT_NE(nullptr, rootIface);
356 if (rootIface == nullptr) return;
357
Steven Morelandaf4ca712021-05-24 23:22:08 +0000358 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000359 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000360 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000361 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000362 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000363 for (auto remoteCount : remoteCounts) {
364 EXPECT_EQ(remoteCount, 1);
365 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000366
367 EXPECT_OK(rootIface->scheduleShutdown());
Steven Moreland5553ac42020-11-11 02:14:45 +0000368 }
369
370 rootIface = nullptr;
371 rootBinder = nullptr;
372 }
373};
374
Steven Morelandc1635952021-04-01 16:20:47 +0000375enum class SocketType {
376 UNIX,
377 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700378 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000379};
380static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
381 switch (info.param) {
382 case SocketType::UNIX:
383 return "unix_domain_socket";
384 case SocketType::VSOCK:
385 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700386 case SocketType::INET:
387 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000388 default:
389 LOG_ALWAYS_FATAL("Unknown socket type");
390 return "";
391 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000392}
Steven Morelandda573042021-06-12 01:13:45 +0000393
Steven Morelandc1635952021-04-01 16:20:47 +0000394class BinderRpc : public ::testing::TestWithParam<SocketType> {
395public:
396 // This creates a new process serving an interface on a certain number of
397 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000398 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland659416d2021-05-11 00:47:50 +0000399 size_t numThreads, size_t numSessions, size_t numReverseConnections,
Steven Moreland736664b2021-05-01 04:27:25 +0000400 const std::function<void(const sp<RpcServer>&)>& configure) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000401 CHECK_GE(numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000402
Steven Morelandc1635952021-04-01 16:20:47 +0000403 SocketType socketType = GetParam();
404
Steven Morelandda573042021-06-12 01:13:45 +0000405 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000406 std::string addr = allocateSocketAddress();
407 unlink(addr.c_str());
Steven Morelandc1635952021-04-01 16:20:47 +0000408
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409 auto ret = ProcessSession{
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700410 .host = Process([&](Pipe* pipe) {
Steven Morelandc1635952021-04-01 16:20:47 +0000411 sp<RpcServer> server = RpcServer::make();
412
413 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Morelandf137de92021-04-24 01:54:26 +0000414 server->setMaxThreads(numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000415
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000416 unsigned int outPort = 0;
417
Steven Morelandc1635952021-04-01 16:20:47 +0000418 switch (socketType) {
419 case SocketType::UNIX:
Steven Moreland611d15f2021-05-01 01:28:27 +0000420 CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000421 break;
422 case SocketType::VSOCK:
Steven Moreland611d15f2021-05-01 01:28:27 +0000423 CHECK(server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000424 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700425 case SocketType::INET: {
Steven Moreland611d15f2021-05-01 01:28:27 +0000426 CHECK(server->setupInetServer(0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700427 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700428 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700429 }
Steven Morelandc1635952021-04-01 16:20:47 +0000430 default:
431 LOG_ALWAYS_FATAL("Unknown socket type");
432 }
433
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000434 CHECK(android::base::WriteFully(pipe->writeEnd(), &outPort, sizeof(outPort)));
435
Steven Moreland611d15f2021-05-01 01:28:27 +0000436 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000437
Steven Morelandf137de92021-04-24 01:54:26 +0000438 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000439
440 // Another thread calls shutdown. Wait for it to complete.
441 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000442 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000443 };
444
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000445 // always read socket, so that we have waited for the server to start
446 unsigned int outPort = 0;
447 CHECK(android::base::ReadFully(ret.host.getPipe()->readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700448 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000449 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700450 }
451
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000452 for (size_t i = 0; i < numSessions; i++) {
453 sp<RpcSession> session = RpcSession::make();
Steven Moreland103424e2021-06-02 18:16:19 +0000454 session->setMaxThreads(numReverseConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000455
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000456 switch (socketType) {
457 case SocketType::UNIX:
458 if (session->setupUnixDomainClient(addr.c_str())) goto success;
459 break;
460 case SocketType::VSOCK:
461 if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
462 break;
463 case SocketType::INET:
464 if (session->setupInetClient("127.0.0.1", outPort)) goto success;
465 break;
466 default:
467 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000468 }
Steven Moreland736664b2021-05-01 04:27:25 +0000469 LOG_ALWAYS_FATAL("Could not connect");
470 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000471 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000472 }
Steven Morelandc1635952021-04-01 16:20:47 +0000473 return ret;
474 }
475
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000476 BinderRpcTestProcessSession createRpcTestSocketServerProcess(size_t numThreads,
Steven Moreland659416d2021-05-11 00:47:50 +0000477 size_t numSessions = 1,
478 size_t numReverseConnections = 0) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000479 BinderRpcTestProcessSession ret{
480 .proc = createRpcTestSocketServerProcess(numThreads, numSessions,
Steven Moreland659416d2021-05-11 00:47:50 +0000481 numReverseConnections,
Steven Moreland611d15f2021-05-01 01:28:27 +0000482 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000483 sp<MyBinderRpcTest> service =
484 new MyBinderRpcTest;
485 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000486 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000487 }),
488 };
489
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000490 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000491 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
492
493 return ret;
494 }
495};
496
Steven Morelandc1635952021-04-01 16:20:47 +0000497TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000498 auto proc = createRpcTestSocketServerProcess(1);
499 ASSERT_NE(proc.rootBinder, nullptr);
500 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
501}
502
Steven Moreland4cf688f2021-03-31 01:48:58 +0000503TEST_P(BinderRpc, GetInterfaceDescriptor) {
504 auto proc = createRpcTestSocketServerProcess(1);
505 ASSERT_NE(proc.rootBinder, nullptr);
506 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
507}
508
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000509TEST_P(BinderRpc, MultipleSessions) {
510 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 5 /*sessions*/);
511 for (auto session : proc.proc.sessions) {
512 ASSERT_NE(nullptr, session.root);
513 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000514 }
515}
516
Steven Morelandc1635952021-04-01 16:20:47 +0000517TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000518 auto proc = createRpcTestSocketServerProcess(1);
519 Parcel data;
520 Parcel reply;
521 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
522}
523
Steven Moreland67753c32021-04-02 18:45:19 +0000524TEST_P(BinderRpc, AppendSeparateFormats) {
525 auto proc = createRpcTestSocketServerProcess(1);
526
527 Parcel p1;
528 p1.markForBinder(proc.rootBinder);
529 p1.writeInt32(3);
530
531 Parcel p2;
532
533 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
534 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
535}
536
Steven Morelandc1635952021-04-01 16:20:47 +0000537TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000538 auto proc = createRpcTestSocketServerProcess(1);
539 Parcel data;
540 data.markForBinder(proc.rootBinder);
541 Parcel reply;
542 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
543}
544
Steven Morelandc1635952021-04-01 16:20:47 +0000545TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000546 auto proc = createRpcTestSocketServerProcess(1);
547 EXPECT_OK(proc.rootIface->sendString("asdf"));
548}
549
Steven Morelandc1635952021-04-01 16:20:47 +0000550TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000551 auto proc = createRpcTestSocketServerProcess(1);
552 std::string doubled;
553 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
554 EXPECT_EQ("cool cool ", doubled);
555}
556
Steven Morelandc1635952021-04-01 16:20:47 +0000557TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000558 auto proc = createRpcTestSocketServerProcess(1);
559 std::string single = std::string(1024, 'a');
560 std::string doubled;
561 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
562 EXPECT_EQ(single + single, doubled);
563}
564
Steven Morelandc1635952021-04-01 16:20:47 +0000565TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000566 auto proc = createRpcTestSocketServerProcess(1);
567
568 int32_t pingResult;
569 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
570 EXPECT_EQ(OK, pingResult);
571
572 EXPECT_EQ(0, MyBinderRpcSession::gNum);
573}
574
Steven Morelandc1635952021-04-01 16:20:47 +0000575TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000576 auto proc = createRpcTestSocketServerProcess(1);
577
578 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
579 sp<IBinder> outBinder;
580 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
581 EXPECT_EQ(inBinder, outBinder);
582
583 wp<IBinder> weak = inBinder;
584 inBinder = nullptr;
585 outBinder = nullptr;
586
587 // Force reading a reply, to process any pending dec refs from the other
588 // process (the other process will process dec refs there before processing
589 // the ping here).
590 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
591
592 EXPECT_EQ(nullptr, weak.promote());
593
594 EXPECT_EQ(0, MyBinderRpcSession::gNum);
595}
596
Steven Morelandc1635952021-04-01 16:20:47 +0000597TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000598 auto proc = createRpcTestSocketServerProcess(1);
599
600 sp<IBinderRpcSession> session;
601 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
602
603 sp<IBinder> inBinder = IInterface::asBinder(session);
604 sp<IBinder> outBinder;
605 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
606 EXPECT_EQ(inBinder, outBinder);
607
608 wp<IBinder> weak = inBinder;
609 session = nullptr;
610 inBinder = nullptr;
611 outBinder = nullptr;
612
613 // Force reading a reply, to process any pending dec refs from the other
614 // process (the other process will process dec refs there before processing
615 // the ping here).
616 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
617
618 EXPECT_EQ(nullptr, weak.promote());
619}
620
Steven Morelandc1635952021-04-01 16:20:47 +0000621TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000622 auto proc = createRpcTestSocketServerProcess(1);
623
624 sp<IBinder> outBinder;
625 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
626 EXPECT_EQ(nullptr, outBinder);
627}
628
Steven Morelandc1635952021-04-01 16:20:47 +0000629TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000630 auto proc = createRpcTestSocketServerProcess(1);
631
632 IBinder* ptr = nullptr;
633 {
634 sp<IBinder> binder = new BBinder();
635 ptr = binder.get();
636 EXPECT_OK(proc.rootIface->holdBinder(binder));
637 }
638
639 sp<IBinder> held;
640 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
641
642 EXPECT_EQ(held.get(), ptr);
643
644 // stop holding binder, because we test to make sure references are cleaned
645 // up
646 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
647 // and flush ref counts
648 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
649}
650
651// START TESTS FOR LIMITATIONS OF SOCKET BINDER
652// These are behavioral differences form regular binder, where certain usecases
653// aren't supported.
654
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000655TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000656 auto proc1 = createRpcTestSocketServerProcess(1);
657 auto proc2 = createRpcTestSocketServerProcess(1);
658
659 sp<IBinder> outBinder;
660 EXPECT_EQ(INVALID_OPERATION,
661 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
662}
663
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000664TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
665 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 2 /*sessions*/);
Steven Moreland736664b2021-05-01 04:27:25 +0000666
667 sp<IBinder> outBinder;
668 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000669 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000670 .transactionError());
671}
672
Steven Morelandc1635952021-04-01 16:20:47 +0000673TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000674 auto proc = createRpcTestSocketServerProcess(1);
675
676 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
677 sp<IBinder> outBinder;
678 EXPECT_EQ(INVALID_OPERATION,
679 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
680}
681
Steven Morelandc1635952021-04-01 16:20:47 +0000682TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000683 auto proc = createRpcTestSocketServerProcess(1);
684
685 // for historical reasons, IServiceManager interface only returns the
686 // exception code
687 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
688 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
689}
690
691// END TESTS FOR LIMITATIONS OF SOCKET BINDER
692
Steven Morelandc1635952021-04-01 16:20:47 +0000693TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000694 auto proc = createRpcTestSocketServerProcess(1);
695
696 sp<IBinder> outBinder;
697 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
698 EXPECT_EQ(proc.rootBinder, outBinder);
699}
700
Steven Morelandc1635952021-04-01 16:20:47 +0000701TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000702 auto proc = createRpcTestSocketServerProcess(1);
703
704 auto nastyNester = sp<MyBinderRpcTest>::make();
705 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
706
707 wp<IBinder> weak = nastyNester;
708 nastyNester = nullptr;
709 EXPECT_EQ(nullptr, weak.promote());
710}
711
Steven Morelandc1635952021-04-01 16:20:47 +0000712TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000713 auto proc = createRpcTestSocketServerProcess(1);
714
715 sp<IBinder> a;
716 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
717
718 sp<IBinder> b;
719 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
720
721 EXPECT_EQ(a, b);
722}
723
Steven Morelandc1635952021-04-01 16:20:47 +0000724TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000725 auto proc = createRpcTestSocketServerProcess(1);
726
727 sp<IBinder> a;
728 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
729 wp<IBinder> weak = a;
730 a = nullptr;
731
732 sp<IBinder> b;
733 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
734
735 // this is the wrong behavior, since BpBinder
736 // doesn't implement onIncStrongAttempted
737 // but make sure there is no crash
738 EXPECT_EQ(nullptr, weak.promote());
739
740 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
741
742 // In order to fix this:
743 // - need to have incStrongAttempted reflected across IPC boundary (wait for
744 // response to promote - round trip...)
745 // - sendOnLastWeakRef, to delete entries out of RpcState table
746 EXPECT_EQ(b, weak.promote());
747}
748
749#define expectSessions(expected, iface) \
750 do { \
751 int session; \
752 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
753 EXPECT_EQ(expected, session); \
754 } while (false)
755
Steven Morelandc1635952021-04-01 16:20:47 +0000756TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000757 auto proc = createRpcTestSocketServerProcess(1);
758
759 sp<IBinderRpcSession> session;
760 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
761 std::string out;
762 EXPECT_OK(session->getName(&out));
763 EXPECT_EQ("aoeu", out);
764
765 expectSessions(1, proc.rootIface);
766 session = nullptr;
767 expectSessions(0, proc.rootIface);
768}
769
Steven Morelandc1635952021-04-01 16:20:47 +0000770TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000771 auto proc = createRpcTestSocketServerProcess(1);
772
773 std::vector<sp<IBinderRpcSession>> sessions;
774
775 for (size_t i = 0; i < 15; i++) {
776 expectSessions(i, proc.rootIface);
777 sp<IBinderRpcSession> session;
778 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
779 sessions.push_back(session);
780 }
781 expectSessions(sessions.size(), proc.rootIface);
782 for (size_t i = 0; i < sessions.size(); i++) {
783 std::string out;
784 EXPECT_OK(sessions.at(i)->getName(&out));
785 EXPECT_EQ(std::to_string(i), out);
786 }
787 expectSessions(sessions.size(), proc.rootIface);
788
789 while (!sessions.empty()) {
790 sessions.pop_back();
791 expectSessions(sessions.size(), proc.rootIface);
792 }
793 expectSessions(0, proc.rootIface);
794}
795
796size_t epochMillis() {
797 using std::chrono::duration_cast;
798 using std::chrono::milliseconds;
799 using std::chrono::seconds;
800 using std::chrono::system_clock;
801 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
802}
803
Steven Morelandc1635952021-04-01 16:20:47 +0000804TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000805 constexpr size_t kNumThreads = 10;
806
807 auto proc = createRpcTestSocketServerProcess(kNumThreads);
808
809 EXPECT_OK(proc.rootIface->lock());
810
811 // block all but one thread taking locks
812 std::vector<std::thread> ts;
813 for (size_t i = 0; i < kNumThreads - 1; i++) {
814 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
815 }
816
817 usleep(100000); // give chance for calls on other threads
818
819 // other calls still work
820 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
821
822 constexpr size_t blockTimeMs = 500;
823 size_t epochMsBefore = epochMillis();
824 // after this, we should never see a response within this time
825 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
826
827 // this call should be blocked for blockTimeMs
828 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
829
830 size_t epochMsAfter = epochMillis();
831 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
832
833 for (auto& t : ts) t.join();
834}
835
Steven Morelandc1635952021-04-01 16:20:47 +0000836TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000837 constexpr size_t kNumThreads = 10;
838 constexpr size_t kNumCalls = kNumThreads + 3;
839 constexpr size_t kSleepMs = 500;
840
841 auto proc = createRpcTestSocketServerProcess(kNumThreads);
842
843 size_t epochMsBefore = epochMillis();
844
845 std::vector<std::thread> ts;
846 for (size_t i = 0; i < kNumCalls; i++) {
847 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
848 }
849
850 for (auto& t : ts) t.join();
851
852 size_t epochMsAfter = epochMillis();
853
854 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
855
856 // Potential flake, but make sure calls are handled in parallel.
857 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
858}
859
Steven Morelandc1635952021-04-01 16:20:47 +0000860TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000861 constexpr size_t kNumClientThreads = 10;
862 constexpr size_t kNumServerThreads = 10;
863 constexpr size_t kNumCalls = 100;
864
865 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
866
867 std::vector<std::thread> threads;
868 for (size_t i = 0; i < kNumClientThreads; i++) {
869 threads.push_back(std::thread([&] {
870 for (size_t j = 0; j < kNumCalls; j++) {
871 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000872 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000873 EXPECT_EQ(proc.rootBinder, out);
874 }
875 }));
876 }
877
878 for (auto& t : threads) t.join();
879}
880
Steven Morelandc6046982021-04-20 00:49:42 +0000881TEST_P(BinderRpc, OnewayStressTest) {
882 constexpr size_t kNumClientThreads = 10;
883 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000884 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000885
886 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
887
888 std::vector<std::thread> threads;
889 for (size_t i = 0; i < kNumClientThreads; i++) {
890 threads.push_back(std::thread([&] {
891 for (size_t j = 0; j < kNumCalls; j++) {
892 EXPECT_OK(proc.rootIface->sendString("a"));
893 }
894
895 // check threads are not stuck
896 EXPECT_OK(proc.rootIface->sleepMs(250));
897 }));
898 }
899
900 for (auto& t : threads) t.join();
901}
902
Steven Morelandc1635952021-04-01 16:20:47 +0000903TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000904 constexpr size_t kReallyLongTimeMs = 100;
905 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
906
Steven Morelandf5174272021-05-25 00:39:28 +0000907 auto proc = createRpcTestSocketServerProcess(1);
Steven Moreland5553ac42020-11-11 02:14:45 +0000908
909 size_t epochMsBefore = epochMillis();
910
911 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
912
913 size_t epochMsAfter = epochMillis();
914 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
915}
916
Steven Morelandc1635952021-04-01 16:20:47 +0000917TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000918 constexpr size_t kNumSleeps = 10;
919 constexpr size_t kNumExtraServerThreads = 4;
920 constexpr size_t kSleepMs = 50;
921
922 // make sure calls to the same object happen on the same thread
923 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
924
925 EXPECT_OK(proc.rootIface->lock());
926
927 for (size_t i = 0; i < kNumSleeps; i++) {
928 // these should be processed serially
929 proc.rootIface->sleepMsAsync(kSleepMs);
930 }
931 // should also be processesed serially
932 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
933
934 size_t epochMsBefore = epochMillis();
935 EXPECT_OK(proc.rootIface->lockUnlock());
936 size_t epochMsAfter = epochMillis();
937
938 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000939
940 // pending oneway transactions hold ref, make sure we read data on all
941 // sockets
942 std::vector<std::thread> threads;
943 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
944 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
945 }
946 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +0000947}
948
Steven Morelandd45be622021-06-04 02:19:37 +0000949TEST_P(BinderRpc, OnewayCallExhaustion) {
950 constexpr size_t kNumClients = 2;
951 constexpr size_t kTooLongMs = 1000;
952
953 auto proc = createRpcTestSocketServerProcess(kNumClients /*threads*/, 2 /*sessions*/);
954
955 // Build up oneway calls on the second session to make sure it terminates
956 // and shuts down. The first session should be unaffected (proc destructor
957 // checks the first session).
958 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
959
960 std::vector<std::thread> threads;
961 for (size_t i = 0; i < kNumClients; i++) {
962 // one of these threads will get stuck queueing a transaction once the
963 // socket fills up, the other will be able to fill up transactions on
964 // this object
965 threads.push_back(std::thread([&] {
966 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
967 }
968 }));
969 }
970 for (auto& t : threads) t.join();
971
972 Status status = iface->sleepMsAsync(kTooLongMs);
973 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
974
975 // the second session should be shutdown in the other process by the time we
976 // are able to join above (it'll only be hung up once it finishes processing
977 // any pending commands). We need to erase this session from the record
978 // here, so that the destructor for our session won't check that this
979 // session is valid, but we still want it to test the other session.
980 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
981}
982
Steven Moreland659416d2021-05-11 00:47:50 +0000983TEST_P(BinderRpc, Callbacks) {
984 const static std::string kTestString = "good afternoon!";
985
986 for (bool oneway : {true, false}) {
987 for (bool delayed : {true, false}) {
988 auto proc = createRpcTestSocketServerProcess(1, 1, 1);
989 auto cb = sp<MyBinderRpcCallback>::make();
990
991 EXPECT_OK(proc.rootIface->doCallback(cb, oneway, delayed, kTestString));
992
993 using std::literals::chrono_literals::operator""s;
994 std::unique_lock<std::mutex> _l(cb->mMutex);
995 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
996
997 EXPECT_EQ(cb->mValues.size(), 1) << "oneway: " << oneway << "delayed: " << delayed;
998 if (cb->mValues.empty()) continue;
999 EXPECT_EQ(cb->mValues.at(0), kTestString)
1000 << "oneway: " << oneway << "delayed: " << delayed;
1001
1002 // since we are severing the connection, we need to go ahead and
1003 // tell the server to shutdown and exit so that waitpid won't hang
1004 EXPECT_OK(proc.rootIface->scheduleShutdown());
1005
1006 // since this session has a reverse connection w/ a threadpool, we
1007 // need to manually shut it down
Steven Morelandc9d7b532021-06-04 20:57:41 +00001008 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001009
1010 proc.expectAlreadyShutdown = true;
1011 }
1012 }
1013}
1014
Steven Moreland195edb82021-06-08 02:44:39 +00001015TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
1016 auto proc = createRpcTestSocketServerProcess(1);
1017 auto cb = sp<MyBinderRpcCallback>::make();
1018
1019 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1020 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1021}
1022
Steven Morelandc1635952021-04-01 16:20:47 +00001023TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001024 for (bool doDeathCleanup : {true, false}) {
1025 auto proc = createRpcTestSocketServerProcess(1);
1026
1027 // make sure there is some state during crash
1028 // 1. we hold their binder
1029 sp<IBinderRpcSession> session;
1030 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1031 // 2. they hold our binder
1032 sp<IBinder> binder = new BBinder();
1033 EXPECT_OK(proc.rootIface->holdBinder(binder));
1034
1035 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1036 << "Do death cleanup: " << doDeathCleanup;
1037
Steven Morelandaf4ca712021-05-24 23:22:08 +00001038 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001039 }
1040}
1041
Steven Morelandd7302072021-05-15 01:32:04 +00001042TEST_P(BinderRpc, UseKernelBinderCallingId) {
1043 auto proc = createRpcTestSocketServerProcess(1);
1044
1045 // we can't allocate IPCThreadState so actually the first time should
1046 // succeed :(
1047 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1048
1049 // second time! we catch the error :)
1050 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1051
Steven Morelandaf4ca712021-05-24 23:22:08 +00001052 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001053}
1054
Steven Moreland37aff182021-03-26 02:04:16 +00001055TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
1056 auto proc = createRpcTestSocketServerProcess(1);
1057
1058 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1059 ASSERT_NE(binder, nullptr);
1060
1061 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1062}
1063
1064TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
1065 auto proc = createRpcTestSocketServerProcess(1);
1066
1067 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1068 ASSERT_NE(binder, nullptr);
1069
1070 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1071 ASSERT_NE(ndkBinder, nullptr);
1072
1073 std::string out;
1074 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1075 ASSERT_TRUE(status.isOk()) << status.getDescription();
1076 ASSERT_EQ("aoeuaoeu", out);
1077}
1078
Steven Moreland5553ac42020-11-11 02:14:45 +00001079ssize_t countFds() {
1080 DIR* dir = opendir("/proc/self/fd/");
1081 if (dir == nullptr) return -1;
1082 ssize_t ret = 0;
1083 dirent* ent;
1084 while ((ent = readdir(dir)) != nullptr) ret++;
1085 closedir(dir);
1086 return ret;
1087}
1088
Steven Morelandc1635952021-04-01 16:20:47 +00001089TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001090 ssize_t beforeFds = countFds();
1091 ASSERT_GE(beforeFds, 0);
1092 {
1093 auto proc = createRpcTestSocketServerProcess(10);
1094 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1095 }
1096 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1097}
1098
Steven Morelandda573042021-06-12 01:13:45 +00001099static bool testSupportVsockLoopback() {
1100 unsigned int vsockPort = allocateVsockPort();
1101 sp<RpcServer> server = RpcServer::make();
1102 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1103 CHECK(server->setupVsockServer(vsockPort));
1104 server->start();
1105
1106 sp<RpcSession> session = RpcSession::make();
1107 bool okay = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
1108 CHECK(server->shutdown());
1109 ALOGE("Detected vsock loopback supported: %d", okay);
1110 return okay;
1111}
1112
1113static std::vector<SocketType> testSocketTypes() {
1114 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1115
1116 static bool hasVsockLoopback = testSupportVsockLoopback();
1117
1118 if (hasVsockLoopback) {
1119 ret.push_back(SocketType::VSOCK);
1120 }
1121
1122 return ret;
1123}
1124
1125INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc, ::testing::ValuesIn(testSocketTypes()),
Steven Morelandf6ec4632021-04-01 16:20:47 +00001126 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +00001127
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001128class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
1129
1130TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1131 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1132 auto setRootObject = [](bool isStrong) -> SetFn {
1133 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1134 };
1135
1136 auto server = RpcServer::make();
1137 auto [isStrong1, isStrong2] = GetParam();
1138 auto binder1 = sp<BBinder>::make();
1139 IBinder* binderRaw1 = binder1.get();
1140 setRootObject(isStrong1)(server.get(), binder1);
1141 EXPECT_EQ(binderRaw1, server->getRootObject());
1142 binder1.clear();
1143 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1144
1145 auto binder2 = sp<BBinder>::make();
1146 IBinder* binderRaw2 = binder2.get();
1147 setRootObject(isStrong2)(server.get(), binder2);
1148 EXPECT_EQ(binderRaw2, server->getRootObject());
1149 binder2.clear();
1150 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1151}
1152
1153INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
1154 ::testing::Combine(::testing::Bool(), ::testing::Bool()));
1155
Yifan Hong1a235852021-05-13 16:07:47 -07001156class OneOffSignal {
1157public:
1158 // If notify() was previously called, or is called within |duration|, return true; else false.
1159 template <typename R, typename P>
1160 bool wait(std::chrono::duration<R, P> duration) {
1161 std::unique_lock<std::mutex> lock(mMutex);
1162 return mCv.wait_for(lock, duration, [this] { return mValue; });
1163 }
1164 void notify() {
1165 std::unique_lock<std::mutex> lock(mMutex);
1166 mValue = true;
1167 lock.unlock();
1168 mCv.notify_all();
1169 }
1170
1171private:
1172 std::mutex mMutex;
1173 std::condition_variable mCv;
1174 bool mValue = false;
1175};
1176
1177TEST(BinderRpc, Shutdown) {
1178 auto addr = allocateSocketAddress();
1179 unlink(addr.c_str());
1180 auto server = RpcServer::make();
1181 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1182 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1183 auto joinEnds = std::make_shared<OneOffSignal>();
1184
1185 // If things are broken and the thread never stops, don't block other tests. Because the thread
1186 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1187 // shared pointers are passed.
1188 std::thread([server, joinEnds] {
1189 server->join();
1190 joinEnds->notify();
1191 }).detach();
1192
1193 bool shutdown = false;
1194 for (int i = 0; i < 10 && !shutdown; i++) {
1195 usleep(300 * 1000); // 300ms; total 3s
1196 if (server->shutdown()) shutdown = true;
1197 }
1198 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1199
1200 ASSERT_TRUE(joinEnds->wait(2s))
1201 << "After server->shutdown() returns true, join() did not stop after 2s";
1202}
1203
Steven Morelandc1635952021-04-01 16:20:47 +00001204} // namespace android
1205
1206int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001207 ::testing::InitGoogleTest(&argc, argv);
1208 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1209 return RUN_ALL_TESTS();
1210}