blob: 29bde340a1e7b1493f60ca6bf5df3faeef150f73 [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());
Steven Morelandc7d40132021-06-10 03:42:11 +0000217 Status status = doCallback(callback, oneway, false, value);
218 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000219 }).detach();
220 return Status::ok();
221 }
222
223 if (oneway) {
224 return callback->sendOnewayCallback(value);
225 }
226
227 return callback->sendCallback(value);
228 }
229
Steven Morelandc7d40132021-06-10 03:42:11 +0000230 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
231 const std::string& value) override {
232 return doCallback(callback, oneway, delayed, value);
233 }
234
Steven Moreland5553ac42020-11-11 02:14:45 +0000235 Status die(bool cleanup) override {
236 if (cleanup) {
237 exit(1);
238 } else {
239 _exit(1);
240 }
241 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000242
243 Status scheduleShutdown() override {
244 sp<RpcServer> strongServer = server.promote();
245 if (strongServer == nullptr) {
246 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
247 }
248 std::thread([=] {
249 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
250 }).detach();
251 return Status::ok();
252 }
253
Steven Morelandd7302072021-05-15 01:32:04 +0000254 Status useKernelBinderCallingId() override {
255 // this is WRONG! It does not make sense when using RPC binder, and
256 // because it is SO wrong, and so much code calls this, it should abort!
257
258 (void)IPCThreadState::self()->getCallingPid();
259 return Status::ok();
260 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000261};
262sp<IBinder> MyBinderRpcTest::mHeldBinder;
263
264class Process {
265public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700266 Process(Process&&) = default;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700267 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */)>& f) {
268 android::base::unique_fd writeEnd;
269 CHECK(android::base::Pipe(&mReadEnd, &writeEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000270 if (0 == (mPid = fork())) {
271 // racey: assume parent doesn't crash before this is set
272 prctl(PR_SET_PDEATHSIG, SIGHUP);
273
Yifan Hong0f58fb92021-06-16 16:09:23 -0700274 f(writeEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000275
276 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000277 }
278 }
279 ~Process() {
280 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000281 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000282 }
283 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700284 android::base::borrowed_fd readEnd() { return mReadEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000285
286private:
287 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700288 android::base::unique_fd mReadEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000289};
290
291static std::string allocateSocketAddress() {
292 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000293 std::string temp = getenv("TMPDIR") ?: "/tmp";
294 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000295};
296
Steven Morelandda573042021-06-12 01:13:45 +0000297static unsigned int allocateVsockPort() {
298 static unsigned int vsockPort = 3456;
299 return vsockPort++;
300}
301
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000302struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000303 // reference to process hosting a socket server
304 Process host;
305
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000306 struct SessionInfo {
307 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000308 sp<IBinder> root;
309 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000310
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000311 // client session objects associated with other process
312 // each one represents a separate session
313 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000314
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000315 ProcessSession(ProcessSession&&) = default;
316 ~ProcessSession() {
317 for (auto& session : sessions) {
318 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000319 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000320
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000321 for (auto& info : sessions) {
322 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000323
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000324 EXPECT_NE(nullptr, session);
325 EXPECT_NE(nullptr, session->state());
326 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000327
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000328 wp<RpcSession> weakSession = session;
329 session = nullptr;
330 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000331 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000332 }
333};
334
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000335// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000336// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000337struct BinderRpcTestProcessSession {
338 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000339
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000340 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000341 sp<IBinder> rootBinder;
342
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000343 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000344 sp<IBinderRpcTest> rootIface;
345
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000346 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000347 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000348
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000349 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
350 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000351 EXPECT_NE(nullptr, rootIface);
352 if (rootIface == nullptr) return;
353
Steven Morelandaf4ca712021-05-24 23:22:08 +0000354 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000355 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000356 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000357 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000358 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000359 for (auto remoteCount : remoteCounts) {
360 EXPECT_EQ(remoteCount, 1);
361 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000362
363 EXPECT_OK(rootIface->scheduleShutdown());
Steven Moreland5553ac42020-11-11 02:14:45 +0000364 }
365
366 rootIface = nullptr;
367 rootBinder = nullptr;
368 }
369};
370
Steven Morelandc1635952021-04-01 16:20:47 +0000371enum class SocketType {
372 UNIX,
373 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700374 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000375};
376static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
377 switch (info.param) {
378 case SocketType::UNIX:
379 return "unix_domain_socket";
380 case SocketType::VSOCK:
381 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700382 case SocketType::INET:
383 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000384 default:
385 LOG_ALWAYS_FATAL("Unknown socket type");
386 return "";
387 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000388}
Steven Morelandda573042021-06-12 01:13:45 +0000389
Steven Morelandc1635952021-04-01 16:20:47 +0000390class BinderRpc : public ::testing::TestWithParam<SocketType> {
391public:
392 // This creates a new process serving an interface on a certain number of
393 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000394 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland659416d2021-05-11 00:47:50 +0000395 size_t numThreads, size_t numSessions, size_t numReverseConnections,
Steven Moreland736664b2021-05-01 04:27:25 +0000396 const std::function<void(const sp<RpcServer>&)>& configure) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000397 CHECK_GE(numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000398
Steven Morelandc1635952021-04-01 16:20:47 +0000399 SocketType socketType = GetParam();
400
Steven Morelandda573042021-06-12 01:13:45 +0000401 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000402 std::string addr = allocateSocketAddress();
403 unlink(addr.c_str());
Steven Morelandc1635952021-04-01 16:20:47 +0000404
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000405 auto ret = ProcessSession{
Yifan Hong0f58fb92021-06-16 16:09:23 -0700406 .host = Process([&](android::base::borrowed_fd writeEnd) {
Steven Morelandc1635952021-04-01 16:20:47 +0000407 sp<RpcServer> server = RpcServer::make();
408
409 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Morelandf137de92021-04-24 01:54:26 +0000410 server->setMaxThreads(numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000411
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000412 unsigned int outPort = 0;
413
Steven Morelandc1635952021-04-01 16:20:47 +0000414 switch (socketType) {
415 case SocketType::UNIX:
Steven Moreland611d15f2021-05-01 01:28:27 +0000416 CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000417 break;
418 case SocketType::VSOCK:
Steven Moreland611d15f2021-05-01 01:28:27 +0000419 CHECK(server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000420 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700421 case SocketType::INET: {
Steven Moreland611d15f2021-05-01 01:28:27 +0000422 CHECK(server->setupInetServer(0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700423 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700424 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700425 }
Steven Morelandc1635952021-04-01 16:20:47 +0000426 default:
427 LOG_ALWAYS_FATAL("Unknown socket type");
428 }
429
Yifan Hong0f58fb92021-06-16 16:09:23 -0700430 CHECK(android::base::WriteFully(writeEnd, &outPort, sizeof(outPort)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000431
Steven Moreland611d15f2021-05-01 01:28:27 +0000432 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000433
Steven Morelandf137de92021-04-24 01:54:26 +0000434 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000435
436 // Another thread calls shutdown. Wait for it to complete.
437 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000438 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000439 };
440
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000441 // always read socket, so that we have waited for the server to start
442 unsigned int outPort = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700443 CHECK(android::base::ReadFully(ret.host.readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700444 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000445 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700446 }
447
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000448 for (size_t i = 0; i < numSessions; i++) {
449 sp<RpcSession> session = RpcSession::make();
Steven Moreland103424e2021-06-02 18:16:19 +0000450 session->setMaxThreads(numReverseConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000451
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000452 switch (socketType) {
453 case SocketType::UNIX:
454 if (session->setupUnixDomainClient(addr.c_str())) goto success;
455 break;
456 case SocketType::VSOCK:
457 if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
458 break;
459 case SocketType::INET:
460 if (session->setupInetClient("127.0.0.1", outPort)) goto success;
461 break;
462 default:
463 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000464 }
Steven Moreland736664b2021-05-01 04:27:25 +0000465 LOG_ALWAYS_FATAL("Could not connect");
466 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000467 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000468 }
Steven Morelandc1635952021-04-01 16:20:47 +0000469 return ret;
470 }
471
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000472 BinderRpcTestProcessSession createRpcTestSocketServerProcess(size_t numThreads,
Steven Moreland659416d2021-05-11 00:47:50 +0000473 size_t numSessions = 1,
474 size_t numReverseConnections = 0) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000475 BinderRpcTestProcessSession ret{
476 .proc = createRpcTestSocketServerProcess(numThreads, numSessions,
Steven Moreland659416d2021-05-11 00:47:50 +0000477 numReverseConnections,
Steven Moreland611d15f2021-05-01 01:28:27 +0000478 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000479 sp<MyBinderRpcTest> service =
480 new MyBinderRpcTest;
481 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000482 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000483 }),
484 };
485
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000486 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000487 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
488
489 return ret;
490 }
491};
492
Steven Morelandc1635952021-04-01 16:20:47 +0000493TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000494 auto proc = createRpcTestSocketServerProcess(1);
495 ASSERT_NE(proc.rootBinder, nullptr);
496 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
497}
498
Steven Moreland4cf688f2021-03-31 01:48:58 +0000499TEST_P(BinderRpc, GetInterfaceDescriptor) {
500 auto proc = createRpcTestSocketServerProcess(1);
501 ASSERT_NE(proc.rootBinder, nullptr);
502 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
503}
504
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000505TEST_P(BinderRpc, MultipleSessions) {
506 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 5 /*sessions*/);
507 for (auto session : proc.proc.sessions) {
508 ASSERT_NE(nullptr, session.root);
509 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000510 }
511}
512
Steven Morelandc1635952021-04-01 16:20:47 +0000513TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000514 auto proc = createRpcTestSocketServerProcess(1);
515 Parcel data;
516 Parcel reply;
517 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
518}
519
Steven Moreland67753c32021-04-02 18:45:19 +0000520TEST_P(BinderRpc, AppendSeparateFormats) {
521 auto proc = createRpcTestSocketServerProcess(1);
522
523 Parcel p1;
524 p1.markForBinder(proc.rootBinder);
525 p1.writeInt32(3);
526
527 Parcel p2;
528
529 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
530 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
531}
532
Steven Morelandc1635952021-04-01 16:20:47 +0000533TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000534 auto proc = createRpcTestSocketServerProcess(1);
535 Parcel data;
536 data.markForBinder(proc.rootBinder);
537 Parcel reply;
538 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
539}
540
Steven Morelandc1635952021-04-01 16:20:47 +0000541TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000542 auto proc = createRpcTestSocketServerProcess(1);
543 EXPECT_OK(proc.rootIface->sendString("asdf"));
544}
545
Steven Morelandc1635952021-04-01 16:20:47 +0000546TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000547 auto proc = createRpcTestSocketServerProcess(1);
548 std::string doubled;
549 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
550 EXPECT_EQ("cool cool ", doubled);
551}
552
Steven Morelandc1635952021-04-01 16:20:47 +0000553TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000554 auto proc = createRpcTestSocketServerProcess(1);
555 std::string single = std::string(1024, 'a');
556 std::string doubled;
557 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
558 EXPECT_EQ(single + single, doubled);
559}
560
Steven Morelandc1635952021-04-01 16:20:47 +0000561TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000562 auto proc = createRpcTestSocketServerProcess(1);
563
564 int32_t pingResult;
565 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
566 EXPECT_EQ(OK, pingResult);
567
568 EXPECT_EQ(0, MyBinderRpcSession::gNum);
569}
570
Steven Morelandc1635952021-04-01 16:20:47 +0000571TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000572 auto proc = createRpcTestSocketServerProcess(1);
573
574 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
575 sp<IBinder> outBinder;
576 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
577 EXPECT_EQ(inBinder, outBinder);
578
579 wp<IBinder> weak = inBinder;
580 inBinder = nullptr;
581 outBinder = nullptr;
582
583 // Force reading a reply, to process any pending dec refs from the other
584 // process (the other process will process dec refs there before processing
585 // the ping here).
586 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
587
588 EXPECT_EQ(nullptr, weak.promote());
589
590 EXPECT_EQ(0, MyBinderRpcSession::gNum);
591}
592
Steven Morelandc1635952021-04-01 16:20:47 +0000593TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000594 auto proc = createRpcTestSocketServerProcess(1);
595
596 sp<IBinderRpcSession> session;
597 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
598
599 sp<IBinder> inBinder = IInterface::asBinder(session);
600 sp<IBinder> outBinder;
601 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
602 EXPECT_EQ(inBinder, outBinder);
603
604 wp<IBinder> weak = inBinder;
605 session = nullptr;
606 inBinder = nullptr;
607 outBinder = nullptr;
608
609 // Force reading a reply, to process any pending dec refs from the other
610 // process (the other process will process dec refs there before processing
611 // the ping here).
612 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
613
614 EXPECT_EQ(nullptr, weak.promote());
615}
616
Steven Morelandc1635952021-04-01 16:20:47 +0000617TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000618 auto proc = createRpcTestSocketServerProcess(1);
619
620 sp<IBinder> outBinder;
621 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
622 EXPECT_EQ(nullptr, outBinder);
623}
624
Steven Morelandc1635952021-04-01 16:20:47 +0000625TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000626 auto proc = createRpcTestSocketServerProcess(1);
627
628 IBinder* ptr = nullptr;
629 {
630 sp<IBinder> binder = new BBinder();
631 ptr = binder.get();
632 EXPECT_OK(proc.rootIface->holdBinder(binder));
633 }
634
635 sp<IBinder> held;
636 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
637
638 EXPECT_EQ(held.get(), ptr);
639
640 // stop holding binder, because we test to make sure references are cleaned
641 // up
642 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
643 // and flush ref counts
644 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
645}
646
647// START TESTS FOR LIMITATIONS OF SOCKET BINDER
648// These are behavioral differences form regular binder, where certain usecases
649// aren't supported.
650
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000651TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000652 auto proc1 = createRpcTestSocketServerProcess(1);
653 auto proc2 = createRpcTestSocketServerProcess(1);
654
655 sp<IBinder> outBinder;
656 EXPECT_EQ(INVALID_OPERATION,
657 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
658}
659
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000660TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
661 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 2 /*sessions*/);
Steven Moreland736664b2021-05-01 04:27:25 +0000662
663 sp<IBinder> outBinder;
664 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000665 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000666 .transactionError());
667}
668
Steven Morelandc1635952021-04-01 16:20:47 +0000669TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000670 auto proc = createRpcTestSocketServerProcess(1);
671
672 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
673 sp<IBinder> outBinder;
674 EXPECT_EQ(INVALID_OPERATION,
675 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
676}
677
Steven Morelandc1635952021-04-01 16:20:47 +0000678TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000679 auto proc = createRpcTestSocketServerProcess(1);
680
681 // for historical reasons, IServiceManager interface only returns the
682 // exception code
683 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
684 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
685}
686
687// END TESTS FOR LIMITATIONS OF SOCKET BINDER
688
Steven Morelandc1635952021-04-01 16:20:47 +0000689TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000690 auto proc = createRpcTestSocketServerProcess(1);
691
692 sp<IBinder> outBinder;
693 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
694 EXPECT_EQ(proc.rootBinder, outBinder);
695}
696
Steven Morelandc1635952021-04-01 16:20:47 +0000697TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000698 auto proc = createRpcTestSocketServerProcess(1);
699
700 auto nastyNester = sp<MyBinderRpcTest>::make();
701 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
702
703 wp<IBinder> weak = nastyNester;
704 nastyNester = nullptr;
705 EXPECT_EQ(nullptr, weak.promote());
706}
707
Steven Morelandc1635952021-04-01 16:20:47 +0000708TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000709 auto proc = createRpcTestSocketServerProcess(1);
710
711 sp<IBinder> a;
712 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
713
714 sp<IBinder> b;
715 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
716
717 EXPECT_EQ(a, b);
718}
719
Steven Morelandc1635952021-04-01 16:20:47 +0000720TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000721 auto proc = createRpcTestSocketServerProcess(1);
722
723 sp<IBinder> a;
724 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
725 wp<IBinder> weak = a;
726 a = nullptr;
727
728 sp<IBinder> b;
729 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
730
731 // this is the wrong behavior, since BpBinder
732 // doesn't implement onIncStrongAttempted
733 // but make sure there is no crash
734 EXPECT_EQ(nullptr, weak.promote());
735
736 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
737
738 // In order to fix this:
739 // - need to have incStrongAttempted reflected across IPC boundary (wait for
740 // response to promote - round trip...)
741 // - sendOnLastWeakRef, to delete entries out of RpcState table
742 EXPECT_EQ(b, weak.promote());
743}
744
745#define expectSessions(expected, iface) \
746 do { \
747 int session; \
748 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
749 EXPECT_EQ(expected, session); \
750 } while (false)
751
Steven Morelandc1635952021-04-01 16:20:47 +0000752TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000753 auto proc = createRpcTestSocketServerProcess(1);
754
755 sp<IBinderRpcSession> session;
756 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
757 std::string out;
758 EXPECT_OK(session->getName(&out));
759 EXPECT_EQ("aoeu", out);
760
761 expectSessions(1, proc.rootIface);
762 session = nullptr;
763 expectSessions(0, proc.rootIface);
764}
765
Steven Morelandc1635952021-04-01 16:20:47 +0000766TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000767 auto proc = createRpcTestSocketServerProcess(1);
768
769 std::vector<sp<IBinderRpcSession>> sessions;
770
771 for (size_t i = 0; i < 15; i++) {
772 expectSessions(i, proc.rootIface);
773 sp<IBinderRpcSession> session;
774 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
775 sessions.push_back(session);
776 }
777 expectSessions(sessions.size(), proc.rootIface);
778 for (size_t i = 0; i < sessions.size(); i++) {
779 std::string out;
780 EXPECT_OK(sessions.at(i)->getName(&out));
781 EXPECT_EQ(std::to_string(i), out);
782 }
783 expectSessions(sessions.size(), proc.rootIface);
784
785 while (!sessions.empty()) {
786 sessions.pop_back();
787 expectSessions(sessions.size(), proc.rootIface);
788 }
789 expectSessions(0, proc.rootIface);
790}
791
792size_t epochMillis() {
793 using std::chrono::duration_cast;
794 using std::chrono::milliseconds;
795 using std::chrono::seconds;
796 using std::chrono::system_clock;
797 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
798}
799
Steven Morelandc1635952021-04-01 16:20:47 +0000800TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000801 constexpr size_t kNumThreads = 10;
802
803 auto proc = createRpcTestSocketServerProcess(kNumThreads);
804
805 EXPECT_OK(proc.rootIface->lock());
806
807 // block all but one thread taking locks
808 std::vector<std::thread> ts;
809 for (size_t i = 0; i < kNumThreads - 1; i++) {
810 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
811 }
812
813 usleep(100000); // give chance for calls on other threads
814
815 // other calls still work
816 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
817
818 constexpr size_t blockTimeMs = 500;
819 size_t epochMsBefore = epochMillis();
820 // after this, we should never see a response within this time
821 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
822
823 // this call should be blocked for blockTimeMs
824 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
825
826 size_t epochMsAfter = epochMillis();
827 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
828
829 for (auto& t : ts) t.join();
830}
831
Steven Morelandc1635952021-04-01 16:20:47 +0000832TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000833 constexpr size_t kNumThreads = 10;
834 constexpr size_t kNumCalls = kNumThreads + 3;
835 constexpr size_t kSleepMs = 500;
836
837 auto proc = createRpcTestSocketServerProcess(kNumThreads);
838
839 size_t epochMsBefore = epochMillis();
840
841 std::vector<std::thread> ts;
842 for (size_t i = 0; i < kNumCalls; i++) {
843 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
844 }
845
846 for (auto& t : ts) t.join();
847
848 size_t epochMsAfter = epochMillis();
849
850 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
851
852 // Potential flake, but make sure calls are handled in parallel.
853 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
854}
855
Steven Morelandc1635952021-04-01 16:20:47 +0000856TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000857 constexpr size_t kNumClientThreads = 10;
858 constexpr size_t kNumServerThreads = 10;
859 constexpr size_t kNumCalls = 100;
860
861 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
862
863 std::vector<std::thread> threads;
864 for (size_t i = 0; i < kNumClientThreads; i++) {
865 threads.push_back(std::thread([&] {
866 for (size_t j = 0; j < kNumCalls; j++) {
867 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000868 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000869 EXPECT_EQ(proc.rootBinder, out);
870 }
871 }));
872 }
873
874 for (auto& t : threads) t.join();
875}
876
Steven Morelandc6046982021-04-20 00:49:42 +0000877TEST_P(BinderRpc, OnewayStressTest) {
878 constexpr size_t kNumClientThreads = 10;
879 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000880 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000881
882 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
883
884 std::vector<std::thread> threads;
885 for (size_t i = 0; i < kNumClientThreads; i++) {
886 threads.push_back(std::thread([&] {
887 for (size_t j = 0; j < kNumCalls; j++) {
888 EXPECT_OK(proc.rootIface->sendString("a"));
889 }
890
891 // check threads are not stuck
892 EXPECT_OK(proc.rootIface->sleepMs(250));
893 }));
894 }
895
896 for (auto& t : threads) t.join();
897}
898
Steven Morelandc1635952021-04-01 16:20:47 +0000899TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000900 constexpr size_t kReallyLongTimeMs = 100;
901 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
902
Steven Morelandf5174272021-05-25 00:39:28 +0000903 auto proc = createRpcTestSocketServerProcess(1);
Steven Moreland5553ac42020-11-11 02:14:45 +0000904
905 size_t epochMsBefore = epochMillis();
906
907 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
908
909 size_t epochMsAfter = epochMillis();
910 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
911}
912
Steven Morelandc1635952021-04-01 16:20:47 +0000913TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000914 constexpr size_t kNumSleeps = 10;
915 constexpr size_t kNumExtraServerThreads = 4;
916 constexpr size_t kSleepMs = 50;
917
918 // make sure calls to the same object happen on the same thread
919 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
920
921 EXPECT_OK(proc.rootIface->lock());
922
923 for (size_t i = 0; i < kNumSleeps; i++) {
924 // these should be processed serially
925 proc.rootIface->sleepMsAsync(kSleepMs);
926 }
927 // should also be processesed serially
928 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
929
930 size_t epochMsBefore = epochMillis();
931 EXPECT_OK(proc.rootIface->lockUnlock());
932 size_t epochMsAfter = epochMillis();
933
934 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000935
936 // pending oneway transactions hold ref, make sure we read data on all
937 // sockets
938 std::vector<std::thread> threads;
939 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
940 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
941 }
942 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +0000943}
944
Steven Morelandd45be622021-06-04 02:19:37 +0000945TEST_P(BinderRpc, OnewayCallExhaustion) {
946 constexpr size_t kNumClients = 2;
947 constexpr size_t kTooLongMs = 1000;
948
949 auto proc = createRpcTestSocketServerProcess(kNumClients /*threads*/, 2 /*sessions*/);
950
951 // Build up oneway calls on the second session to make sure it terminates
952 // and shuts down. The first session should be unaffected (proc destructor
953 // checks the first session).
954 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
955
956 std::vector<std::thread> threads;
957 for (size_t i = 0; i < kNumClients; i++) {
958 // one of these threads will get stuck queueing a transaction once the
959 // socket fills up, the other will be able to fill up transactions on
960 // this object
961 threads.push_back(std::thread([&] {
962 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
963 }
964 }));
965 }
966 for (auto& t : threads) t.join();
967
968 Status status = iface->sleepMsAsync(kTooLongMs);
969 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
970
971 // the second session should be shutdown in the other process by the time we
972 // are able to join above (it'll only be hung up once it finishes processing
973 // any pending commands). We need to erase this session from the record
974 // here, so that the destructor for our session won't check that this
975 // session is valid, but we still want it to test the other session.
976 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
977}
978
Steven Moreland659416d2021-05-11 00:47:50 +0000979TEST_P(BinderRpc, Callbacks) {
980 const static std::string kTestString = "good afternoon!";
981
Steven Morelandc7d40132021-06-10 03:42:11 +0000982 for (bool callIsOneway : {true, false}) {
983 for (bool callbackIsOneway : {true, false}) {
984 for (bool delayed : {true, false}) {
985 auto proc = createRpcTestSocketServerProcess(1, 1, 1);
986 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +0000987
Steven Morelandc7d40132021-06-10 03:42:11 +0000988 if (callIsOneway) {
989 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
990 kTestString));
991 } else {
992 EXPECT_OK(
993 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
994 }
Steven Moreland659416d2021-05-11 00:47:50 +0000995
Steven Morelandc7d40132021-06-10 03:42:11 +0000996 using std::literals::chrono_literals::operator""s;
997 std::unique_lock<std::mutex> _l(cb->mMutex);
998 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +0000999
Steven Morelandc7d40132021-06-10 03:42:11 +00001000 EXPECT_EQ(cb->mValues.size(), 1)
1001 << "callIsOneway: " << callIsOneway
1002 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1003 if (cb->mValues.empty()) continue;
1004 EXPECT_EQ(cb->mValues.at(0), kTestString)
1005 << "callIsOneway: " << callIsOneway
1006 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001007
Steven Morelandc7d40132021-06-10 03:42:11 +00001008 // since we are severing the connection, we need to go ahead and
1009 // tell the server to shutdown and exit so that waitpid won't hang
1010 EXPECT_OK(proc.rootIface->scheduleShutdown());
Steven Moreland659416d2021-05-11 00:47:50 +00001011
Steven Morelandc7d40132021-06-10 03:42:11 +00001012 // since this session has a reverse connection w/ a threadpool, we
1013 // need to manually shut it down
1014 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001015
Steven Morelandc7d40132021-06-10 03:42:11 +00001016 proc.expectAlreadyShutdown = true;
1017 }
Steven Moreland659416d2021-05-11 00:47:50 +00001018 }
1019 }
1020}
1021
Steven Moreland195edb82021-06-08 02:44:39 +00001022TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
1023 auto proc = createRpcTestSocketServerProcess(1);
1024 auto cb = sp<MyBinderRpcCallback>::make();
1025
1026 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1027 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1028}
1029
Steven Morelandc1635952021-04-01 16:20:47 +00001030TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001031 for (bool doDeathCleanup : {true, false}) {
1032 auto proc = createRpcTestSocketServerProcess(1);
1033
1034 // make sure there is some state during crash
1035 // 1. we hold their binder
1036 sp<IBinderRpcSession> session;
1037 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1038 // 2. they hold our binder
1039 sp<IBinder> binder = new BBinder();
1040 EXPECT_OK(proc.rootIface->holdBinder(binder));
1041
1042 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1043 << "Do death cleanup: " << doDeathCleanup;
1044
Steven Morelandaf4ca712021-05-24 23:22:08 +00001045 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001046 }
1047}
1048
Steven Morelandd7302072021-05-15 01:32:04 +00001049TEST_P(BinderRpc, UseKernelBinderCallingId) {
1050 auto proc = createRpcTestSocketServerProcess(1);
1051
1052 // we can't allocate IPCThreadState so actually the first time should
1053 // succeed :(
1054 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1055
1056 // second time! we catch the error :)
1057 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1058
Steven Morelandaf4ca712021-05-24 23:22:08 +00001059 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001060}
1061
Steven Moreland37aff182021-03-26 02:04:16 +00001062TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
1063 auto proc = createRpcTestSocketServerProcess(1);
1064
1065 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1066 ASSERT_NE(binder, nullptr);
1067
1068 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1069}
1070
1071TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
1072 auto proc = createRpcTestSocketServerProcess(1);
1073
1074 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1075 ASSERT_NE(binder, nullptr);
1076
1077 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1078 ASSERT_NE(ndkBinder, nullptr);
1079
1080 std::string out;
1081 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1082 ASSERT_TRUE(status.isOk()) << status.getDescription();
1083 ASSERT_EQ("aoeuaoeu", out);
1084}
1085
Steven Moreland5553ac42020-11-11 02:14:45 +00001086ssize_t countFds() {
1087 DIR* dir = opendir("/proc/self/fd/");
1088 if (dir == nullptr) return -1;
1089 ssize_t ret = 0;
1090 dirent* ent;
1091 while ((ent = readdir(dir)) != nullptr) ret++;
1092 closedir(dir);
1093 return ret;
1094}
1095
Steven Morelandc1635952021-04-01 16:20:47 +00001096TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001097 ssize_t beforeFds = countFds();
1098 ASSERT_GE(beforeFds, 0);
1099 {
1100 auto proc = createRpcTestSocketServerProcess(10);
1101 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1102 }
1103 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1104}
1105
Steven Morelandda573042021-06-12 01:13:45 +00001106static bool testSupportVsockLoopback() {
1107 unsigned int vsockPort = allocateVsockPort();
1108 sp<RpcServer> server = RpcServer::make();
1109 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1110 CHECK(server->setupVsockServer(vsockPort));
1111 server->start();
1112
1113 sp<RpcSession> session = RpcSession::make();
1114 bool okay = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
1115 CHECK(server->shutdown());
1116 ALOGE("Detected vsock loopback supported: %d", okay);
1117 return okay;
1118}
1119
1120static std::vector<SocketType> testSocketTypes() {
1121 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1122
1123 static bool hasVsockLoopback = testSupportVsockLoopback();
1124
1125 if (hasVsockLoopback) {
1126 ret.push_back(SocketType::VSOCK);
1127 }
1128
1129 return ret;
1130}
1131
1132INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc, ::testing::ValuesIn(testSocketTypes()),
Steven Morelandf6ec4632021-04-01 16:20:47 +00001133 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +00001134
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001135class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
1136
1137TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1138 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1139 auto setRootObject = [](bool isStrong) -> SetFn {
1140 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1141 };
1142
1143 auto server = RpcServer::make();
1144 auto [isStrong1, isStrong2] = GetParam();
1145 auto binder1 = sp<BBinder>::make();
1146 IBinder* binderRaw1 = binder1.get();
1147 setRootObject(isStrong1)(server.get(), binder1);
1148 EXPECT_EQ(binderRaw1, server->getRootObject());
1149 binder1.clear();
1150 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1151
1152 auto binder2 = sp<BBinder>::make();
1153 IBinder* binderRaw2 = binder2.get();
1154 setRootObject(isStrong2)(server.get(), binder2);
1155 EXPECT_EQ(binderRaw2, server->getRootObject());
1156 binder2.clear();
1157 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1158}
1159
1160INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
1161 ::testing::Combine(::testing::Bool(), ::testing::Bool()));
1162
Yifan Hong1a235852021-05-13 16:07:47 -07001163class OneOffSignal {
1164public:
1165 // If notify() was previously called, or is called within |duration|, return true; else false.
1166 template <typename R, typename P>
1167 bool wait(std::chrono::duration<R, P> duration) {
1168 std::unique_lock<std::mutex> lock(mMutex);
1169 return mCv.wait_for(lock, duration, [this] { return mValue; });
1170 }
1171 void notify() {
1172 std::unique_lock<std::mutex> lock(mMutex);
1173 mValue = true;
1174 lock.unlock();
1175 mCv.notify_all();
1176 }
1177
1178private:
1179 std::mutex mMutex;
1180 std::condition_variable mCv;
1181 bool mValue = false;
1182};
1183
1184TEST(BinderRpc, Shutdown) {
1185 auto addr = allocateSocketAddress();
1186 unlink(addr.c_str());
1187 auto server = RpcServer::make();
1188 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1189 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1190 auto joinEnds = std::make_shared<OneOffSignal>();
1191
1192 // If things are broken and the thread never stops, don't block other tests. Because the thread
1193 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1194 // shared pointers are passed.
1195 std::thread([server, joinEnds] {
1196 server->join();
1197 joinEnds->notify();
1198 }).detach();
1199
1200 bool shutdown = false;
1201 for (int i = 0; i < 10 && !shutdown; i++) {
1202 usleep(300 * 1000); // 300ms; total 3s
1203 if (server->shutdown()) shutdown = true;
1204 }
1205 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1206
1207 ASSERT_TRUE(joinEnds->wait(2s))
1208 << "After server->shutdown() returns true, join() did not stop after 2s";
1209}
1210
Yifan Hong0f9c5c72021-06-29 18:44:56 -07001211TEST(BinderRpc, Java) {
1212#if !defined(__ANDROID__)
1213 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1214 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1215 "to binderHostDeviceTest. Hence, just disable this test on host.";
1216#endif // !__ANDROID__
1217 sp<IServiceManager> sm = defaultServiceManager();
1218 ASSERT_NE(nullptr, sm);
1219 // Any Java service with non-empty getInterfaceDescriptor() would do.
1220 // Let's pick batteryproperties.
1221 auto binder = sm->checkService(String16("batteryproperties"));
1222 ASSERT_NE(nullptr, binder);
1223 auto descriptor = binder->getInterfaceDescriptor();
1224 ASSERT_GE(descriptor.size(), 0);
1225 ASSERT_EQ(OK, binder->pingBinder());
1226
1227 auto rpcServer = RpcServer::make();
1228 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1229 unsigned int port;
1230 ASSERT_TRUE(rpcServer->setupInetServer(0, &port));
1231 auto socket = rpcServer->releaseServer();
1232
1233 auto keepAlive = sp<BBinder>::make();
1234 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1235
1236 auto rpcSession = RpcSession::make();
1237 ASSERT_TRUE(rpcSession->setupInetClient("127.0.0.1", port));
1238 auto rpcBinder = rpcSession->getRootObject();
1239 ASSERT_NE(nullptr, rpcBinder);
1240
1241 ASSERT_EQ(OK, rpcBinder->pingBinder());
1242
1243 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1244 << "getInterfaceDescriptor should not crash system_server";
1245 ASSERT_EQ(OK, rpcBinder->pingBinder());
1246}
1247
Steven Morelandc1635952021-04-01 16:20:47 +00001248} // namespace android
1249
1250int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001251 ::testing::InitGoogleTest(&argc, argv);
1252 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1253 return RUN_ALL_TESTS();
1254}