blob: 7dfda25988de254411b075f2bb1d425de751c367 [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
258class Process {
259public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700260 Process(Process&&) = default;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700261 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */)>& f) {
262 android::base::unique_fd writeEnd;
263 CHECK(android::base::Pipe(&mReadEnd, &writeEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000264 if (0 == (mPid = fork())) {
265 // racey: assume parent doesn't crash before this is set
266 prctl(PR_SET_PDEATHSIG, SIGHUP);
267
Yifan Hong0f58fb92021-06-16 16:09:23 -0700268 f(writeEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000269
270 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000271 }
272 }
273 ~Process() {
274 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000275 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000276 }
277 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700278 android::base::borrowed_fd readEnd() { return mReadEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000279
280private:
281 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700282 android::base::unique_fd mReadEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000283};
284
285static std::string allocateSocketAddress() {
286 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000287 std::string temp = getenv("TMPDIR") ?: "/tmp";
288 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000289};
290
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000291struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000292 // reference to process hosting a socket server
293 Process host;
294
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000295 struct SessionInfo {
296 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000297 sp<IBinder> root;
298 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000299
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000300 // client session objects associated with other process
301 // each one represents a separate session
302 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000303
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000304 ProcessSession(ProcessSession&&) = default;
305 ~ProcessSession() {
306 for (auto& session : sessions) {
307 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000308 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000309
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000310 for (auto& info : sessions) {
311 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000312
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000313 EXPECT_NE(nullptr, session);
314 EXPECT_NE(nullptr, session->state());
315 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000316
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000317 wp<RpcSession> weakSession = session;
318 session = nullptr;
319 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000320 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000321 }
322};
323
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000324// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000325// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000326struct BinderRpcTestProcessSession {
327 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000328
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000329 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000330 sp<IBinder> rootBinder;
331
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000332 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000333 sp<IBinderRpcTest> rootIface;
334
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000335 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000336 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000337
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000338 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
339 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000340 EXPECT_NE(nullptr, rootIface);
341 if (rootIface == nullptr) return;
342
Steven Morelandaf4ca712021-05-24 23:22:08 +0000343 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000344 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000345 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000346 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000347 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000348 for (auto remoteCount : remoteCounts) {
349 EXPECT_EQ(remoteCount, 1);
350 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000351
352 EXPECT_OK(rootIface->scheduleShutdown());
Steven Moreland5553ac42020-11-11 02:14:45 +0000353 }
354
355 rootIface = nullptr;
356 rootBinder = nullptr;
357 }
358};
359
Steven Morelandc1635952021-04-01 16:20:47 +0000360enum class SocketType {
361 UNIX,
362 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700363 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000364};
365static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
366 switch (info.param) {
367 case SocketType::UNIX:
368 return "unix_domain_socket";
369 case SocketType::VSOCK:
370 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700371 case SocketType::INET:
372 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000373 default:
374 LOG_ALWAYS_FATAL("Unknown socket type");
375 return "";
376 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000377}
Steven Morelandc1635952021-04-01 16:20:47 +0000378class BinderRpc : public ::testing::TestWithParam<SocketType> {
379public:
380 // This creates a new process serving an interface on a certain number of
381 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000382 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland659416d2021-05-11 00:47:50 +0000383 size_t numThreads, size_t numSessions, size_t numReverseConnections,
Steven Moreland736664b2021-05-01 04:27:25 +0000384 const std::function<void(const sp<RpcServer>&)>& configure) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000385 CHECK_GE(numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000386
Steven Morelandc1635952021-04-01 16:20:47 +0000387 SocketType socketType = GetParam();
388
389 std::string addr = allocateSocketAddress();
390 unlink(addr.c_str());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700391 static unsigned int vsockPort = 3456;
392 vsockPort++;
Steven Morelandc1635952021-04-01 16:20:47 +0000393
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000394 auto ret = ProcessSession{
Yifan Hong0f58fb92021-06-16 16:09:23 -0700395 .host = Process([&](android::base::borrowed_fd writeEnd) {
Steven Morelandc1635952021-04-01 16:20:47 +0000396 sp<RpcServer> server = RpcServer::make();
397
398 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Morelandf137de92021-04-24 01:54:26 +0000399 server->setMaxThreads(numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000400
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000401 unsigned int outPort = 0;
402
Steven Morelandc1635952021-04-01 16:20:47 +0000403 switch (socketType) {
404 case SocketType::UNIX:
Steven Moreland611d15f2021-05-01 01:28:27 +0000405 CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000406 break;
407 case SocketType::VSOCK:
Steven Moreland611d15f2021-05-01 01:28:27 +0000408 CHECK(server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000409 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700410 case SocketType::INET: {
Steven Moreland611d15f2021-05-01 01:28:27 +0000411 CHECK(server->setupInetServer(0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700412 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700413 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700414 }
Steven Morelandc1635952021-04-01 16:20:47 +0000415 default:
416 LOG_ALWAYS_FATAL("Unknown socket type");
417 }
418
Yifan Hong0f58fb92021-06-16 16:09:23 -0700419 CHECK(android::base::WriteFully(writeEnd, &outPort, sizeof(outPort)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000420
Steven Moreland611d15f2021-05-01 01:28:27 +0000421 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000422
Steven Morelandf137de92021-04-24 01:54:26 +0000423 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000424
425 // Another thread calls shutdown. Wait for it to complete.
426 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000427 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000428 };
429
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000430 // always read socket, so that we have waited for the server to start
431 unsigned int outPort = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700432 CHECK(android::base::ReadFully(ret.host.readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700433 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000434 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700435 }
436
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000437 for (size_t i = 0; i < numSessions; i++) {
438 sp<RpcSession> session = RpcSession::make();
Steven Moreland103424e2021-06-02 18:16:19 +0000439 session->setMaxThreads(numReverseConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000440
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000441 switch (socketType) {
442 case SocketType::UNIX:
443 if (session->setupUnixDomainClient(addr.c_str())) goto success;
444 break;
445 case SocketType::VSOCK:
446 if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
447 break;
448 case SocketType::INET:
449 if (session->setupInetClient("127.0.0.1", outPort)) goto success;
450 break;
451 default:
452 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000453 }
Steven Moreland736664b2021-05-01 04:27:25 +0000454 LOG_ALWAYS_FATAL("Could not connect");
455 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000456 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000457 }
Steven Morelandc1635952021-04-01 16:20:47 +0000458 return ret;
459 }
460
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000461 BinderRpcTestProcessSession createRpcTestSocketServerProcess(size_t numThreads,
Steven Moreland659416d2021-05-11 00:47:50 +0000462 size_t numSessions = 1,
463 size_t numReverseConnections = 0) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000464 BinderRpcTestProcessSession ret{
465 .proc = createRpcTestSocketServerProcess(numThreads, numSessions,
Steven Moreland659416d2021-05-11 00:47:50 +0000466 numReverseConnections,
Steven Moreland611d15f2021-05-01 01:28:27 +0000467 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000468 sp<MyBinderRpcTest> service =
469 new MyBinderRpcTest;
470 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000471 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000472 }),
473 };
474
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000475 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000476 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
477
478 return ret;
479 }
480};
481
Steven Morelandc1635952021-04-01 16:20:47 +0000482TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000483 auto proc = createRpcTestSocketServerProcess(1);
484 ASSERT_NE(proc.rootBinder, nullptr);
485 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
486}
487
Steven Moreland4cf688f2021-03-31 01:48:58 +0000488TEST_P(BinderRpc, GetInterfaceDescriptor) {
489 auto proc = createRpcTestSocketServerProcess(1);
490 ASSERT_NE(proc.rootBinder, nullptr);
491 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
492}
493
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000494TEST_P(BinderRpc, MultipleSessions) {
495 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 5 /*sessions*/);
496 for (auto session : proc.proc.sessions) {
497 ASSERT_NE(nullptr, session.root);
498 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000499 }
500}
501
Steven Morelandc1635952021-04-01 16:20:47 +0000502TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000503 auto proc = createRpcTestSocketServerProcess(1);
504 Parcel data;
505 Parcel reply;
506 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
507}
508
Steven Moreland67753c32021-04-02 18:45:19 +0000509TEST_P(BinderRpc, AppendSeparateFormats) {
510 auto proc = createRpcTestSocketServerProcess(1);
511
512 Parcel p1;
513 p1.markForBinder(proc.rootBinder);
514 p1.writeInt32(3);
515
516 Parcel p2;
517
518 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
519 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
520}
521
Steven Morelandc1635952021-04-01 16:20:47 +0000522TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000523 auto proc = createRpcTestSocketServerProcess(1);
524 Parcel data;
525 data.markForBinder(proc.rootBinder);
526 Parcel reply;
527 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
528}
529
Steven Morelandc1635952021-04-01 16:20:47 +0000530TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000531 auto proc = createRpcTestSocketServerProcess(1);
532 EXPECT_OK(proc.rootIface->sendString("asdf"));
533}
534
Steven Morelandc1635952021-04-01 16:20:47 +0000535TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000536 auto proc = createRpcTestSocketServerProcess(1);
537 std::string doubled;
538 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
539 EXPECT_EQ("cool cool ", doubled);
540}
541
Steven Morelandc1635952021-04-01 16:20:47 +0000542TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000543 auto proc = createRpcTestSocketServerProcess(1);
544 std::string single = std::string(1024, 'a');
545 std::string doubled;
546 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
547 EXPECT_EQ(single + single, doubled);
548}
549
Steven Morelandc1635952021-04-01 16:20:47 +0000550TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000551 auto proc = createRpcTestSocketServerProcess(1);
552
553 int32_t pingResult;
554 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
555 EXPECT_EQ(OK, pingResult);
556
557 EXPECT_EQ(0, MyBinderRpcSession::gNum);
558}
559
Steven Morelandc1635952021-04-01 16:20:47 +0000560TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000561 auto proc = createRpcTestSocketServerProcess(1);
562
563 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
564 sp<IBinder> outBinder;
565 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
566 EXPECT_EQ(inBinder, outBinder);
567
568 wp<IBinder> weak = inBinder;
569 inBinder = nullptr;
570 outBinder = nullptr;
571
572 // Force reading a reply, to process any pending dec refs from the other
573 // process (the other process will process dec refs there before processing
574 // the ping here).
575 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
576
577 EXPECT_EQ(nullptr, weak.promote());
578
579 EXPECT_EQ(0, MyBinderRpcSession::gNum);
580}
581
Steven Morelandc1635952021-04-01 16:20:47 +0000582TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000583 auto proc = createRpcTestSocketServerProcess(1);
584
585 sp<IBinderRpcSession> session;
586 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
587
588 sp<IBinder> inBinder = IInterface::asBinder(session);
589 sp<IBinder> outBinder;
590 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
591 EXPECT_EQ(inBinder, outBinder);
592
593 wp<IBinder> weak = inBinder;
594 session = nullptr;
595 inBinder = nullptr;
596 outBinder = nullptr;
597
598 // Force reading a reply, to process any pending dec refs from the other
599 // process (the other process will process dec refs there before processing
600 // the ping here).
601 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
602
603 EXPECT_EQ(nullptr, weak.promote());
604}
605
Steven Morelandc1635952021-04-01 16:20:47 +0000606TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000607 auto proc = createRpcTestSocketServerProcess(1);
608
609 sp<IBinder> outBinder;
610 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
611 EXPECT_EQ(nullptr, outBinder);
612}
613
Steven Morelandc1635952021-04-01 16:20:47 +0000614TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000615 auto proc = createRpcTestSocketServerProcess(1);
616
617 IBinder* ptr = nullptr;
618 {
619 sp<IBinder> binder = new BBinder();
620 ptr = binder.get();
621 EXPECT_OK(proc.rootIface->holdBinder(binder));
622 }
623
624 sp<IBinder> held;
625 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
626
627 EXPECT_EQ(held.get(), ptr);
628
629 // stop holding binder, because we test to make sure references are cleaned
630 // up
631 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
632 // and flush ref counts
633 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
634}
635
636// START TESTS FOR LIMITATIONS OF SOCKET BINDER
637// These are behavioral differences form regular binder, where certain usecases
638// aren't supported.
639
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000640TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000641 auto proc1 = createRpcTestSocketServerProcess(1);
642 auto proc2 = createRpcTestSocketServerProcess(1);
643
644 sp<IBinder> outBinder;
645 EXPECT_EQ(INVALID_OPERATION,
646 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
647}
648
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000649TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
650 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 2 /*sessions*/);
Steven Moreland736664b2021-05-01 04:27:25 +0000651
652 sp<IBinder> outBinder;
653 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000654 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000655 .transactionError());
656}
657
Steven Morelandc1635952021-04-01 16:20:47 +0000658TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000659 auto proc = createRpcTestSocketServerProcess(1);
660
661 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
662 sp<IBinder> outBinder;
663 EXPECT_EQ(INVALID_OPERATION,
664 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
665}
666
Steven Morelandc1635952021-04-01 16:20:47 +0000667TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000668 auto proc = createRpcTestSocketServerProcess(1);
669
670 // for historical reasons, IServiceManager interface only returns the
671 // exception code
672 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
673 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
674}
675
676// END TESTS FOR LIMITATIONS OF SOCKET BINDER
677
Steven Morelandc1635952021-04-01 16:20:47 +0000678TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000679 auto proc = createRpcTestSocketServerProcess(1);
680
681 sp<IBinder> outBinder;
682 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
683 EXPECT_EQ(proc.rootBinder, outBinder);
684}
685
Steven Morelandc1635952021-04-01 16:20:47 +0000686TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000687 auto proc = createRpcTestSocketServerProcess(1);
688
689 auto nastyNester = sp<MyBinderRpcTest>::make();
690 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
691
692 wp<IBinder> weak = nastyNester;
693 nastyNester = nullptr;
694 EXPECT_EQ(nullptr, weak.promote());
695}
696
Steven Morelandc1635952021-04-01 16:20:47 +0000697TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000698 auto proc = createRpcTestSocketServerProcess(1);
699
700 sp<IBinder> a;
701 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
702
703 sp<IBinder> b;
704 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
705
706 EXPECT_EQ(a, b);
707}
708
Steven Morelandc1635952021-04-01 16:20:47 +0000709TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000710 auto proc = createRpcTestSocketServerProcess(1);
711
712 sp<IBinder> a;
713 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
714 wp<IBinder> weak = a;
715 a = nullptr;
716
717 sp<IBinder> b;
718 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
719
720 // this is the wrong behavior, since BpBinder
721 // doesn't implement onIncStrongAttempted
722 // but make sure there is no crash
723 EXPECT_EQ(nullptr, weak.promote());
724
725 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
726
727 // In order to fix this:
728 // - need to have incStrongAttempted reflected across IPC boundary (wait for
729 // response to promote - round trip...)
730 // - sendOnLastWeakRef, to delete entries out of RpcState table
731 EXPECT_EQ(b, weak.promote());
732}
733
734#define expectSessions(expected, iface) \
735 do { \
736 int session; \
737 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
738 EXPECT_EQ(expected, session); \
739 } while (false)
740
Steven Morelandc1635952021-04-01 16:20:47 +0000741TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000742 auto proc = createRpcTestSocketServerProcess(1);
743
744 sp<IBinderRpcSession> session;
745 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
746 std::string out;
747 EXPECT_OK(session->getName(&out));
748 EXPECT_EQ("aoeu", out);
749
750 expectSessions(1, proc.rootIface);
751 session = nullptr;
752 expectSessions(0, proc.rootIface);
753}
754
Steven Morelandc1635952021-04-01 16:20:47 +0000755TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000756 auto proc = createRpcTestSocketServerProcess(1);
757
758 std::vector<sp<IBinderRpcSession>> sessions;
759
760 for (size_t i = 0; i < 15; i++) {
761 expectSessions(i, proc.rootIface);
762 sp<IBinderRpcSession> session;
763 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
764 sessions.push_back(session);
765 }
766 expectSessions(sessions.size(), proc.rootIface);
767 for (size_t i = 0; i < sessions.size(); i++) {
768 std::string out;
769 EXPECT_OK(sessions.at(i)->getName(&out));
770 EXPECT_EQ(std::to_string(i), out);
771 }
772 expectSessions(sessions.size(), proc.rootIface);
773
774 while (!sessions.empty()) {
775 sessions.pop_back();
776 expectSessions(sessions.size(), proc.rootIface);
777 }
778 expectSessions(0, proc.rootIface);
779}
780
781size_t epochMillis() {
782 using std::chrono::duration_cast;
783 using std::chrono::milliseconds;
784 using std::chrono::seconds;
785 using std::chrono::system_clock;
786 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
787}
788
Steven Morelandc1635952021-04-01 16:20:47 +0000789TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000790 constexpr size_t kNumThreads = 10;
791
792 auto proc = createRpcTestSocketServerProcess(kNumThreads);
793
794 EXPECT_OK(proc.rootIface->lock());
795
796 // block all but one thread taking locks
797 std::vector<std::thread> ts;
798 for (size_t i = 0; i < kNumThreads - 1; i++) {
799 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
800 }
801
802 usleep(100000); // give chance for calls on other threads
803
804 // other calls still work
805 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
806
807 constexpr size_t blockTimeMs = 500;
808 size_t epochMsBefore = epochMillis();
809 // after this, we should never see a response within this time
810 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
811
812 // this call should be blocked for blockTimeMs
813 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
814
815 size_t epochMsAfter = epochMillis();
816 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
817
818 for (auto& t : ts) t.join();
819}
820
Steven Morelandc1635952021-04-01 16:20:47 +0000821TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000822 constexpr size_t kNumThreads = 10;
823 constexpr size_t kNumCalls = kNumThreads + 3;
824 constexpr size_t kSleepMs = 500;
825
826 auto proc = createRpcTestSocketServerProcess(kNumThreads);
827
828 size_t epochMsBefore = epochMillis();
829
830 std::vector<std::thread> ts;
831 for (size_t i = 0; i < kNumCalls; i++) {
832 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
833 }
834
835 for (auto& t : ts) t.join();
836
837 size_t epochMsAfter = epochMillis();
838
839 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
840
841 // Potential flake, but make sure calls are handled in parallel.
842 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
843}
844
Steven Morelandc1635952021-04-01 16:20:47 +0000845TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000846 constexpr size_t kNumClientThreads = 10;
847 constexpr size_t kNumServerThreads = 10;
848 constexpr size_t kNumCalls = 100;
849
850 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
851
852 std::vector<std::thread> threads;
853 for (size_t i = 0; i < kNumClientThreads; i++) {
854 threads.push_back(std::thread([&] {
855 for (size_t j = 0; j < kNumCalls; j++) {
856 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000857 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000858 EXPECT_EQ(proc.rootBinder, out);
859 }
860 }));
861 }
862
863 for (auto& t : threads) t.join();
864}
865
Steven Morelandc6046982021-04-20 00:49:42 +0000866TEST_P(BinderRpc, OnewayStressTest) {
867 constexpr size_t kNumClientThreads = 10;
868 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000869 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000870
871 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
872
873 std::vector<std::thread> threads;
874 for (size_t i = 0; i < kNumClientThreads; i++) {
875 threads.push_back(std::thread([&] {
876 for (size_t j = 0; j < kNumCalls; j++) {
877 EXPECT_OK(proc.rootIface->sendString("a"));
878 }
879
880 // check threads are not stuck
881 EXPECT_OK(proc.rootIface->sleepMs(250));
882 }));
883 }
884
885 for (auto& t : threads) t.join();
886}
887
Steven Morelandc1635952021-04-01 16:20:47 +0000888TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000889 constexpr size_t kReallyLongTimeMs = 100;
890 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
891
Steven Morelandf5174272021-05-25 00:39:28 +0000892 auto proc = createRpcTestSocketServerProcess(1);
Steven Moreland5553ac42020-11-11 02:14:45 +0000893
894 size_t epochMsBefore = epochMillis();
895
896 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
897
898 size_t epochMsAfter = epochMillis();
899 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
900}
901
Steven Morelandc1635952021-04-01 16:20:47 +0000902TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000903 constexpr size_t kNumSleeps = 10;
904 constexpr size_t kNumExtraServerThreads = 4;
905 constexpr size_t kSleepMs = 50;
906
907 // make sure calls to the same object happen on the same thread
908 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
909
910 EXPECT_OK(proc.rootIface->lock());
911
912 for (size_t i = 0; i < kNumSleeps; i++) {
913 // these should be processed serially
914 proc.rootIface->sleepMsAsync(kSleepMs);
915 }
916 // should also be processesed serially
917 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
918
919 size_t epochMsBefore = epochMillis();
920 EXPECT_OK(proc.rootIface->lockUnlock());
921 size_t epochMsAfter = epochMillis();
922
923 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000924
925 // pending oneway transactions hold ref, make sure we read data on all
926 // sockets
927 std::vector<std::thread> threads;
928 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
929 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
930 }
931 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +0000932}
933
Steven Morelandd45be622021-06-04 02:19:37 +0000934TEST_P(BinderRpc, OnewayCallExhaustion) {
935 constexpr size_t kNumClients = 2;
936 constexpr size_t kTooLongMs = 1000;
937
938 auto proc = createRpcTestSocketServerProcess(kNumClients /*threads*/, 2 /*sessions*/);
939
940 // Build up oneway calls on the second session to make sure it terminates
941 // and shuts down. The first session should be unaffected (proc destructor
942 // checks the first session).
943 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
944
945 std::vector<std::thread> threads;
946 for (size_t i = 0; i < kNumClients; i++) {
947 // one of these threads will get stuck queueing a transaction once the
948 // socket fills up, the other will be able to fill up transactions on
949 // this object
950 threads.push_back(std::thread([&] {
951 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
952 }
953 }));
954 }
955 for (auto& t : threads) t.join();
956
957 Status status = iface->sleepMsAsync(kTooLongMs);
958 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
959
960 // the second session should be shutdown in the other process by the time we
961 // are able to join above (it'll only be hung up once it finishes processing
962 // any pending commands). We need to erase this session from the record
963 // here, so that the destructor for our session won't check that this
964 // session is valid, but we still want it to test the other session.
965 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
966}
967
Steven Moreland659416d2021-05-11 00:47:50 +0000968TEST_P(BinderRpc, Callbacks) {
969 const static std::string kTestString = "good afternoon!";
970
971 for (bool oneway : {true, false}) {
972 for (bool delayed : {true, false}) {
973 auto proc = createRpcTestSocketServerProcess(1, 1, 1);
974 auto cb = sp<MyBinderRpcCallback>::make();
975
976 EXPECT_OK(proc.rootIface->doCallback(cb, oneway, delayed, kTestString));
977
978 using std::literals::chrono_literals::operator""s;
979 std::unique_lock<std::mutex> _l(cb->mMutex);
980 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
981
982 EXPECT_EQ(cb->mValues.size(), 1) << "oneway: " << oneway << "delayed: " << delayed;
983 if (cb->mValues.empty()) continue;
984 EXPECT_EQ(cb->mValues.at(0), kTestString)
985 << "oneway: " << oneway << "delayed: " << delayed;
986
987 // since we are severing the connection, we need to go ahead and
988 // tell the server to shutdown and exit so that waitpid won't hang
989 EXPECT_OK(proc.rootIface->scheduleShutdown());
990
991 // since this session has a reverse connection w/ a threadpool, we
992 // need to manually shut it down
Steven Morelandc9d7b532021-06-04 20:57:41 +0000993 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +0000994
995 proc.expectAlreadyShutdown = true;
996 }
997 }
998}
999
Steven Moreland195edb82021-06-08 02:44:39 +00001000TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
1001 auto proc = createRpcTestSocketServerProcess(1);
1002 auto cb = sp<MyBinderRpcCallback>::make();
1003
1004 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1005 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1006}
1007
Steven Morelandc1635952021-04-01 16:20:47 +00001008TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001009 for (bool doDeathCleanup : {true, false}) {
1010 auto proc = createRpcTestSocketServerProcess(1);
1011
1012 // make sure there is some state during crash
1013 // 1. we hold their binder
1014 sp<IBinderRpcSession> session;
1015 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1016 // 2. they hold our binder
1017 sp<IBinder> binder = new BBinder();
1018 EXPECT_OK(proc.rootIface->holdBinder(binder));
1019
1020 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1021 << "Do death cleanup: " << doDeathCleanup;
1022
Steven Morelandaf4ca712021-05-24 23:22:08 +00001023 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001024 }
1025}
1026
Steven Morelandd7302072021-05-15 01:32:04 +00001027TEST_P(BinderRpc, UseKernelBinderCallingId) {
1028 auto proc = createRpcTestSocketServerProcess(1);
1029
1030 // we can't allocate IPCThreadState so actually the first time should
1031 // succeed :(
1032 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1033
1034 // second time! we catch the error :)
1035 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1036
Steven Morelandaf4ca712021-05-24 23:22:08 +00001037 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001038}
1039
Steven Moreland37aff182021-03-26 02:04:16 +00001040TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
1041 auto proc = createRpcTestSocketServerProcess(1);
1042
1043 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1044 ASSERT_NE(binder, nullptr);
1045
1046 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1047}
1048
1049TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
1050 auto proc = createRpcTestSocketServerProcess(1);
1051
1052 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1053 ASSERT_NE(binder, nullptr);
1054
1055 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1056 ASSERT_NE(ndkBinder, nullptr);
1057
1058 std::string out;
1059 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1060 ASSERT_TRUE(status.isOk()) << status.getDescription();
1061 ASSERT_EQ("aoeuaoeu", out);
1062}
1063
Steven Moreland5553ac42020-11-11 02:14:45 +00001064ssize_t countFds() {
1065 DIR* dir = opendir("/proc/self/fd/");
1066 if (dir == nullptr) return -1;
1067 ssize_t ret = 0;
1068 dirent* ent;
1069 while ((ent = readdir(dir)) != nullptr) ret++;
1070 closedir(dir);
1071 return ret;
1072}
1073
Steven Morelandc1635952021-04-01 16:20:47 +00001074TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001075 ssize_t beforeFds = countFds();
1076 ASSERT_GE(beforeFds, 0);
1077 {
1078 auto proc = createRpcTestSocketServerProcess(10);
1079 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1080 }
1081 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1082}
1083
Steven Morelandc1635952021-04-01 16:20:47 +00001084INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Yifan Hong0d2bd112021-04-13 17:38:36 -07001085 ::testing::ValuesIn({
1086 SocketType::UNIX,
Steven Morelandbd5002b2021-05-04 23:12:56 +00001087// TODO(b/185269356): working on host
Steven Morelandf6ec4632021-04-01 16:20:47 +00001088#ifdef __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -07001089 SocketType::VSOCK,
Steven Morelandbd5002b2021-05-04 23:12:56 +00001090#endif
Yifan Hong0d2bd112021-04-13 17:38:36 -07001091 SocketType::INET,
1092 }),
Steven Morelandf6ec4632021-04-01 16:20:47 +00001093 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +00001094
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001095class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
1096
1097TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1098 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1099 auto setRootObject = [](bool isStrong) -> SetFn {
1100 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1101 };
1102
1103 auto server = RpcServer::make();
1104 auto [isStrong1, isStrong2] = GetParam();
1105 auto binder1 = sp<BBinder>::make();
1106 IBinder* binderRaw1 = binder1.get();
1107 setRootObject(isStrong1)(server.get(), binder1);
1108 EXPECT_EQ(binderRaw1, server->getRootObject());
1109 binder1.clear();
1110 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1111
1112 auto binder2 = sp<BBinder>::make();
1113 IBinder* binderRaw2 = binder2.get();
1114 setRootObject(isStrong2)(server.get(), binder2);
1115 EXPECT_EQ(binderRaw2, server->getRootObject());
1116 binder2.clear();
1117 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1118}
1119
1120INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
1121 ::testing::Combine(::testing::Bool(), ::testing::Bool()));
1122
Yifan Hong1a235852021-05-13 16:07:47 -07001123class OneOffSignal {
1124public:
1125 // If notify() was previously called, or is called within |duration|, return true; else false.
1126 template <typename R, typename P>
1127 bool wait(std::chrono::duration<R, P> duration) {
1128 std::unique_lock<std::mutex> lock(mMutex);
1129 return mCv.wait_for(lock, duration, [this] { return mValue; });
1130 }
1131 void notify() {
1132 std::unique_lock<std::mutex> lock(mMutex);
1133 mValue = true;
1134 lock.unlock();
1135 mCv.notify_all();
1136 }
1137
1138private:
1139 std::mutex mMutex;
1140 std::condition_variable mCv;
1141 bool mValue = false;
1142};
1143
1144TEST(BinderRpc, Shutdown) {
1145 auto addr = allocateSocketAddress();
1146 unlink(addr.c_str());
1147 auto server = RpcServer::make();
1148 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1149 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1150 auto joinEnds = std::make_shared<OneOffSignal>();
1151
1152 // If things are broken and the thread never stops, don't block other tests. Because the thread
1153 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1154 // shared pointers are passed.
1155 std::thread([server, joinEnds] {
1156 server->join();
1157 joinEnds->notify();
1158 }).detach();
1159
1160 bool shutdown = false;
1161 for (int i = 0; i < 10 && !shutdown; i++) {
1162 usleep(300 * 1000); // 300ms; total 3s
1163 if (server->shutdown()) shutdown = true;
1164 }
1165 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1166
1167 ASSERT_TRUE(joinEnds->wait(2s))
1168 << "After server->shutdown() returns true, join() did not stop after 2s";
1169}
1170
Steven Morelandc1635952021-04-01 16:20:47 +00001171} // namespace android
1172
1173int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001174 ::testing::InitGoogleTest(&argc, argv);
1175 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1176 return RUN_ALL_TESTS();
1177}