blob: 69682b0ae571d28dd162a853aa0e92988d07f018 [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
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700264class Pipe {
265public:
266 Pipe() { CHECK(android::base::Pipe(&mRead, &mWrite)); }
267 Pipe(Pipe&&) = default;
268 android::base::borrowed_fd readEnd() { return mRead; }
269 android::base::borrowed_fd writeEnd() { return mWrite; }
270
271private:
272 android::base::unique_fd mRead;
273 android::base::unique_fd mWrite;
274};
275
Steven Moreland5553ac42020-11-11 02:14:45 +0000276class Process {
277public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700278 Process(Process&&) = default;
279 Process(const std::function<void(Pipe*)>& f) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000280 if (0 == (mPid = fork())) {
281 // racey: assume parent doesn't crash before this is set
282 prctl(PR_SET_PDEATHSIG, SIGHUP);
283
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700284 f(&mPipe);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000285
286 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000287 }
288 }
289 ~Process() {
290 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000291 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000292 }
293 }
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700294 Pipe* getPipe() { return &mPipe; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000295
296private:
297 pid_t mPid = 0;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700298 Pipe mPipe;
Steven Moreland5553ac42020-11-11 02:14:45 +0000299};
300
301static std::string allocateSocketAddress() {
302 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000303 std::string temp = getenv("TMPDIR") ?: "/tmp";
304 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000305};
306
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000307struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000308 // reference to process hosting a socket server
309 Process host;
310
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000311 struct SessionInfo {
312 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000313 sp<IBinder> root;
314 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000315
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000316 // client session objects associated with other process
317 // each one represents a separate session
318 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000319
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000320 ProcessSession(ProcessSession&&) = default;
321 ~ProcessSession() {
322 for (auto& session : sessions) {
323 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000324 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000325
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000326 for (auto& info : sessions) {
327 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000328
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000329 EXPECT_NE(nullptr, session);
330 EXPECT_NE(nullptr, session->state());
331 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000332
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000333 wp<RpcSession> weakSession = session;
334 session = nullptr;
335 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000336 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000337 }
338};
339
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000340// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000341// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000342struct BinderRpcTestProcessSession {
343 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000344
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000345 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000346 sp<IBinder> rootBinder;
347
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000348 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000349 sp<IBinderRpcTest> rootIface;
350
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000351 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000352 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000353
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000354 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
355 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000356 EXPECT_NE(nullptr, rootIface);
357 if (rootIface == nullptr) return;
358
Steven Morelandaf4ca712021-05-24 23:22:08 +0000359 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000360 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000361 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000362 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000363 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000364 for (auto remoteCount : remoteCounts) {
365 EXPECT_EQ(remoteCount, 1);
366 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000367
368 EXPECT_OK(rootIface->scheduleShutdown());
Steven Moreland5553ac42020-11-11 02:14:45 +0000369 }
370
371 rootIface = nullptr;
372 rootBinder = nullptr;
373 }
374};
375
Steven Morelandc1635952021-04-01 16:20:47 +0000376enum class SocketType {
377 UNIX,
378 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700379 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000380};
381static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
382 switch (info.param) {
383 case SocketType::UNIX:
384 return "unix_domain_socket";
385 case SocketType::VSOCK:
386 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700387 case SocketType::INET:
388 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000389 default:
390 LOG_ALWAYS_FATAL("Unknown socket type");
391 return "";
392 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000393}
Steven Morelandc1635952021-04-01 16:20:47 +0000394class BinderRpc : public ::testing::TestWithParam<SocketType> {
395public:
396 // This creates a new process serving an interface on a certain number of
397 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000398 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland659416d2021-05-11 00:47:50 +0000399 size_t numThreads, size_t numSessions, size_t numReverseConnections,
Steven Moreland736664b2021-05-01 04:27:25 +0000400 const std::function<void(const sp<RpcServer>&)>& configure) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000401 CHECK_GE(numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000402
Steven Morelandc1635952021-04-01 16:20:47 +0000403 SocketType socketType = GetParam();
404
405 std::string addr = allocateSocketAddress();
406 unlink(addr.c_str());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700407 static unsigned int vsockPort = 3456;
408 vsockPort++;
Steven Morelandc1635952021-04-01 16:20:47 +0000409
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000410 auto ret = ProcessSession{
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700411 .host = Process([&](Pipe* pipe) {
Steven Morelandc1635952021-04-01 16:20:47 +0000412 sp<RpcServer> server = RpcServer::make();
413
414 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Morelandf137de92021-04-24 01:54:26 +0000415 server->setMaxThreads(numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000416
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000417 unsigned int outPort = 0;
418
Steven Morelandc1635952021-04-01 16:20:47 +0000419 switch (socketType) {
420 case SocketType::UNIX:
Steven Moreland611d15f2021-05-01 01:28:27 +0000421 CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000422 break;
423 case SocketType::VSOCK:
Steven Moreland611d15f2021-05-01 01:28:27 +0000424 CHECK(server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000425 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700426 case SocketType::INET: {
Steven Moreland611d15f2021-05-01 01:28:27 +0000427 CHECK(server->setupInetServer(0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700428 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700429 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700430 }
Steven Morelandc1635952021-04-01 16:20:47 +0000431 default:
432 LOG_ALWAYS_FATAL("Unknown socket type");
433 }
434
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000435 CHECK(android::base::WriteFully(pipe->writeEnd(), &outPort, sizeof(outPort)));
436
Steven Moreland611d15f2021-05-01 01:28:27 +0000437 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000438
Steven Morelandf137de92021-04-24 01:54:26 +0000439 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000440
441 // Another thread calls shutdown. Wait for it to complete.
442 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000443 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000444 };
445
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000446 // always read socket, so that we have waited for the server to start
447 unsigned int outPort = 0;
448 CHECK(android::base::ReadFully(ret.host.getPipe()->readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700449 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000450 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700451 }
452
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000453 for (size_t i = 0; i < numSessions; i++) {
454 sp<RpcSession> session = RpcSession::make();
Steven Moreland103424e2021-06-02 18:16:19 +0000455 session->setMaxThreads(numReverseConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000456
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000457 switch (socketType) {
458 case SocketType::UNIX:
459 if (session->setupUnixDomainClient(addr.c_str())) goto success;
460 break;
461 case SocketType::VSOCK:
462 if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
463 break;
464 case SocketType::INET:
465 if (session->setupInetClient("127.0.0.1", outPort)) goto success;
466 break;
467 default:
468 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000469 }
Steven Moreland736664b2021-05-01 04:27:25 +0000470 LOG_ALWAYS_FATAL("Could not connect");
471 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000472 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000473 }
Steven Morelandc1635952021-04-01 16:20:47 +0000474 return ret;
475 }
476
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000477 BinderRpcTestProcessSession createRpcTestSocketServerProcess(size_t numThreads,
Steven Moreland659416d2021-05-11 00:47:50 +0000478 size_t numSessions = 1,
479 size_t numReverseConnections = 0) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000480 BinderRpcTestProcessSession ret{
481 .proc = createRpcTestSocketServerProcess(numThreads, numSessions,
Steven Moreland659416d2021-05-11 00:47:50 +0000482 numReverseConnections,
Steven Moreland611d15f2021-05-01 01:28:27 +0000483 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000484 sp<MyBinderRpcTest> service =
485 new MyBinderRpcTest;
486 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000487 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000488 }),
489 };
490
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000491 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000492 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
493
494 return ret;
495 }
496};
497
Steven Morelandc1635952021-04-01 16:20:47 +0000498TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000499 auto proc = createRpcTestSocketServerProcess(1);
500 ASSERT_NE(proc.rootBinder, nullptr);
501 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
502}
503
Steven Moreland4cf688f2021-03-31 01:48:58 +0000504TEST_P(BinderRpc, GetInterfaceDescriptor) {
505 auto proc = createRpcTestSocketServerProcess(1);
506 ASSERT_NE(proc.rootBinder, nullptr);
507 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
508}
509
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000510TEST_P(BinderRpc, MultipleSessions) {
511 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 5 /*sessions*/);
512 for (auto session : proc.proc.sessions) {
513 ASSERT_NE(nullptr, session.root);
514 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000515 }
516}
517
Steven Morelandc1635952021-04-01 16:20:47 +0000518TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000519 auto proc = createRpcTestSocketServerProcess(1);
520 Parcel data;
521 Parcel reply;
522 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
523}
524
Steven Moreland67753c32021-04-02 18:45:19 +0000525TEST_P(BinderRpc, AppendSeparateFormats) {
526 auto proc = createRpcTestSocketServerProcess(1);
527
528 Parcel p1;
529 p1.markForBinder(proc.rootBinder);
530 p1.writeInt32(3);
531
532 Parcel p2;
533
534 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
535 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
536}
537
Steven Morelandc1635952021-04-01 16:20:47 +0000538TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000539 auto proc = createRpcTestSocketServerProcess(1);
540 Parcel data;
541 data.markForBinder(proc.rootBinder);
542 Parcel reply;
543 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
544}
545
Steven Morelandc1635952021-04-01 16:20:47 +0000546TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000547 auto proc = createRpcTestSocketServerProcess(1);
548 EXPECT_OK(proc.rootIface->sendString("asdf"));
549}
550
Steven Morelandc1635952021-04-01 16:20:47 +0000551TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000552 auto proc = createRpcTestSocketServerProcess(1);
553 std::string doubled;
554 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
555 EXPECT_EQ("cool cool ", doubled);
556}
557
Steven Morelandc1635952021-04-01 16:20:47 +0000558TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000559 auto proc = createRpcTestSocketServerProcess(1);
560 std::string single = std::string(1024, 'a');
561 std::string doubled;
562 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
563 EXPECT_EQ(single + single, doubled);
564}
565
Steven Morelandc1635952021-04-01 16:20:47 +0000566TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000567 auto proc = createRpcTestSocketServerProcess(1);
568
569 int32_t pingResult;
570 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
571 EXPECT_EQ(OK, pingResult);
572
573 EXPECT_EQ(0, MyBinderRpcSession::gNum);
574}
575
Steven Morelandc1635952021-04-01 16:20:47 +0000576TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000577 auto proc = createRpcTestSocketServerProcess(1);
578
579 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
580 sp<IBinder> outBinder;
581 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
582 EXPECT_EQ(inBinder, outBinder);
583
584 wp<IBinder> weak = inBinder;
585 inBinder = nullptr;
586 outBinder = nullptr;
587
588 // Force reading a reply, to process any pending dec refs from the other
589 // process (the other process will process dec refs there before processing
590 // the ping here).
591 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
592
593 EXPECT_EQ(nullptr, weak.promote());
594
595 EXPECT_EQ(0, MyBinderRpcSession::gNum);
596}
597
Steven Morelandc1635952021-04-01 16:20:47 +0000598TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000599 auto proc = createRpcTestSocketServerProcess(1);
600
601 sp<IBinderRpcSession> session;
602 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
603
604 sp<IBinder> inBinder = IInterface::asBinder(session);
605 sp<IBinder> outBinder;
606 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
607 EXPECT_EQ(inBinder, outBinder);
608
609 wp<IBinder> weak = inBinder;
610 session = nullptr;
611 inBinder = nullptr;
612 outBinder = nullptr;
613
614 // Force reading a reply, to process any pending dec refs from the other
615 // process (the other process will process dec refs there before processing
616 // the ping here).
617 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
618
619 EXPECT_EQ(nullptr, weak.promote());
620}
621
Steven Morelandc1635952021-04-01 16:20:47 +0000622TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000623 auto proc = createRpcTestSocketServerProcess(1);
624
625 sp<IBinder> outBinder;
626 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
627 EXPECT_EQ(nullptr, outBinder);
628}
629
Steven Morelandc1635952021-04-01 16:20:47 +0000630TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000631 auto proc = createRpcTestSocketServerProcess(1);
632
633 IBinder* ptr = nullptr;
634 {
635 sp<IBinder> binder = new BBinder();
636 ptr = binder.get();
637 EXPECT_OK(proc.rootIface->holdBinder(binder));
638 }
639
640 sp<IBinder> held;
641 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
642
643 EXPECT_EQ(held.get(), ptr);
644
645 // stop holding binder, because we test to make sure references are cleaned
646 // up
647 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
648 // and flush ref counts
649 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
650}
651
652// START TESTS FOR LIMITATIONS OF SOCKET BINDER
653// These are behavioral differences form regular binder, where certain usecases
654// aren't supported.
655
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000656TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000657 auto proc1 = createRpcTestSocketServerProcess(1);
658 auto proc2 = createRpcTestSocketServerProcess(1);
659
660 sp<IBinder> outBinder;
661 EXPECT_EQ(INVALID_OPERATION,
662 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
663}
664
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000665TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
666 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 2 /*sessions*/);
Steven Moreland736664b2021-05-01 04:27:25 +0000667
668 sp<IBinder> outBinder;
669 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000670 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000671 .transactionError());
672}
673
Steven Morelandc1635952021-04-01 16:20:47 +0000674TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000675 auto proc = createRpcTestSocketServerProcess(1);
676
677 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
678 sp<IBinder> outBinder;
679 EXPECT_EQ(INVALID_OPERATION,
680 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
681}
682
Steven Morelandc1635952021-04-01 16:20:47 +0000683TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000684 auto proc = createRpcTestSocketServerProcess(1);
685
686 // for historical reasons, IServiceManager interface only returns the
687 // exception code
688 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
689 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
690}
691
692// END TESTS FOR LIMITATIONS OF SOCKET BINDER
693
Steven Morelandc1635952021-04-01 16:20:47 +0000694TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000695 auto proc = createRpcTestSocketServerProcess(1);
696
697 sp<IBinder> outBinder;
698 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
699 EXPECT_EQ(proc.rootBinder, outBinder);
700}
701
Steven Morelandc1635952021-04-01 16:20:47 +0000702TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000703 auto proc = createRpcTestSocketServerProcess(1);
704
705 auto nastyNester = sp<MyBinderRpcTest>::make();
706 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
707
708 wp<IBinder> weak = nastyNester;
709 nastyNester = nullptr;
710 EXPECT_EQ(nullptr, weak.promote());
711}
712
Steven Morelandc1635952021-04-01 16:20:47 +0000713TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000714 auto proc = createRpcTestSocketServerProcess(1);
715
716 sp<IBinder> a;
717 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
718
719 sp<IBinder> b;
720 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
721
722 EXPECT_EQ(a, b);
723}
724
Steven Morelandc1635952021-04-01 16:20:47 +0000725TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000726 auto proc = createRpcTestSocketServerProcess(1);
727
728 sp<IBinder> a;
729 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
730 wp<IBinder> weak = a;
731 a = nullptr;
732
733 sp<IBinder> b;
734 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
735
736 // this is the wrong behavior, since BpBinder
737 // doesn't implement onIncStrongAttempted
738 // but make sure there is no crash
739 EXPECT_EQ(nullptr, weak.promote());
740
741 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
742
743 // In order to fix this:
744 // - need to have incStrongAttempted reflected across IPC boundary (wait for
745 // response to promote - round trip...)
746 // - sendOnLastWeakRef, to delete entries out of RpcState table
747 EXPECT_EQ(b, weak.promote());
748}
749
750#define expectSessions(expected, iface) \
751 do { \
752 int session; \
753 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
754 EXPECT_EQ(expected, session); \
755 } while (false)
756
Steven Morelandc1635952021-04-01 16:20:47 +0000757TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000758 auto proc = createRpcTestSocketServerProcess(1);
759
760 sp<IBinderRpcSession> session;
761 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
762 std::string out;
763 EXPECT_OK(session->getName(&out));
764 EXPECT_EQ("aoeu", out);
765
766 expectSessions(1, proc.rootIface);
767 session = nullptr;
768 expectSessions(0, proc.rootIface);
769}
770
Steven Morelandc1635952021-04-01 16:20:47 +0000771TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000772 auto proc = createRpcTestSocketServerProcess(1);
773
774 std::vector<sp<IBinderRpcSession>> sessions;
775
776 for (size_t i = 0; i < 15; i++) {
777 expectSessions(i, proc.rootIface);
778 sp<IBinderRpcSession> session;
779 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
780 sessions.push_back(session);
781 }
782 expectSessions(sessions.size(), proc.rootIface);
783 for (size_t i = 0; i < sessions.size(); i++) {
784 std::string out;
785 EXPECT_OK(sessions.at(i)->getName(&out));
786 EXPECT_EQ(std::to_string(i), out);
787 }
788 expectSessions(sessions.size(), proc.rootIface);
789
790 while (!sessions.empty()) {
791 sessions.pop_back();
792 expectSessions(sessions.size(), proc.rootIface);
793 }
794 expectSessions(0, proc.rootIface);
795}
796
797size_t epochMillis() {
798 using std::chrono::duration_cast;
799 using std::chrono::milliseconds;
800 using std::chrono::seconds;
801 using std::chrono::system_clock;
802 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
803}
804
Steven Morelandc1635952021-04-01 16:20:47 +0000805TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000806 constexpr size_t kNumThreads = 10;
807
808 auto proc = createRpcTestSocketServerProcess(kNumThreads);
809
810 EXPECT_OK(proc.rootIface->lock());
811
812 // block all but one thread taking locks
813 std::vector<std::thread> ts;
814 for (size_t i = 0; i < kNumThreads - 1; i++) {
815 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
816 }
817
818 usleep(100000); // give chance for calls on other threads
819
820 // other calls still work
821 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
822
823 constexpr size_t blockTimeMs = 500;
824 size_t epochMsBefore = epochMillis();
825 // after this, we should never see a response within this time
826 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
827
828 // this call should be blocked for blockTimeMs
829 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
830
831 size_t epochMsAfter = epochMillis();
832 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
833
834 for (auto& t : ts) t.join();
835}
836
Steven Morelandc1635952021-04-01 16:20:47 +0000837TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000838 constexpr size_t kNumThreads = 10;
839 constexpr size_t kNumCalls = kNumThreads + 3;
840 constexpr size_t kSleepMs = 500;
841
842 auto proc = createRpcTestSocketServerProcess(kNumThreads);
843
844 size_t epochMsBefore = epochMillis();
845
846 std::vector<std::thread> ts;
847 for (size_t i = 0; i < kNumCalls; i++) {
848 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
849 }
850
851 for (auto& t : ts) t.join();
852
853 size_t epochMsAfter = epochMillis();
854
855 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
856
857 // Potential flake, but make sure calls are handled in parallel.
858 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
859}
860
Steven Morelandc1635952021-04-01 16:20:47 +0000861TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000862 constexpr size_t kNumClientThreads = 10;
863 constexpr size_t kNumServerThreads = 10;
864 constexpr size_t kNumCalls = 100;
865
866 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
867
868 std::vector<std::thread> threads;
869 for (size_t i = 0; i < kNumClientThreads; i++) {
870 threads.push_back(std::thread([&] {
871 for (size_t j = 0; j < kNumCalls; j++) {
872 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000873 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000874 EXPECT_EQ(proc.rootBinder, out);
875 }
876 }));
877 }
878
879 for (auto& t : threads) t.join();
880}
881
Steven Morelandc6046982021-04-20 00:49:42 +0000882TEST_P(BinderRpc, OnewayStressTest) {
883 constexpr size_t kNumClientThreads = 10;
884 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000885 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000886
887 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
888
889 std::vector<std::thread> threads;
890 for (size_t i = 0; i < kNumClientThreads; i++) {
891 threads.push_back(std::thread([&] {
892 for (size_t j = 0; j < kNumCalls; j++) {
893 EXPECT_OK(proc.rootIface->sendString("a"));
894 }
895
896 // check threads are not stuck
897 EXPECT_OK(proc.rootIface->sleepMs(250));
898 }));
899 }
900
901 for (auto& t : threads) t.join();
902}
903
Steven Morelandc1635952021-04-01 16:20:47 +0000904TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000905 constexpr size_t kReallyLongTimeMs = 100;
906 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
907
Steven Morelandf5174272021-05-25 00:39:28 +0000908 auto proc = createRpcTestSocketServerProcess(1);
Steven Moreland5553ac42020-11-11 02:14:45 +0000909
910 size_t epochMsBefore = epochMillis();
911
912 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
913
914 size_t epochMsAfter = epochMillis();
915 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
916}
917
Steven Morelandc1635952021-04-01 16:20:47 +0000918TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000919 constexpr size_t kNumSleeps = 10;
920 constexpr size_t kNumExtraServerThreads = 4;
921 constexpr size_t kSleepMs = 50;
922
923 // make sure calls to the same object happen on the same thread
924 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
925
926 EXPECT_OK(proc.rootIface->lock());
927
928 for (size_t i = 0; i < kNumSleeps; i++) {
929 // these should be processed serially
930 proc.rootIface->sleepMsAsync(kSleepMs);
931 }
932 // should also be processesed serially
933 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
934
935 size_t epochMsBefore = epochMillis();
936 EXPECT_OK(proc.rootIface->lockUnlock());
937 size_t epochMsAfter = epochMillis();
938
939 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000940
941 // pending oneway transactions hold ref, make sure we read data on all
942 // sockets
943 std::vector<std::thread> threads;
944 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
945 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
946 }
947 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +0000948}
949
Steven Morelandd45be622021-06-04 02:19:37 +0000950TEST_P(BinderRpc, OnewayCallExhaustion) {
951 constexpr size_t kNumClients = 2;
952 constexpr size_t kTooLongMs = 1000;
953
954 auto proc = createRpcTestSocketServerProcess(kNumClients /*threads*/, 2 /*sessions*/);
955
956 // Build up oneway calls on the second session to make sure it terminates
957 // and shuts down. The first session should be unaffected (proc destructor
958 // checks the first session).
959 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
960
961 std::vector<std::thread> threads;
962 for (size_t i = 0; i < kNumClients; i++) {
963 // one of these threads will get stuck queueing a transaction once the
964 // socket fills up, the other will be able to fill up transactions on
965 // this object
966 threads.push_back(std::thread([&] {
967 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
968 }
969 }));
970 }
971 for (auto& t : threads) t.join();
972
973 Status status = iface->sleepMsAsync(kTooLongMs);
974 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
975
976 // the second session should be shutdown in the other process by the time we
977 // are able to join above (it'll only be hung up once it finishes processing
978 // any pending commands). We need to erase this session from the record
979 // here, so that the destructor for our session won't check that this
980 // session is valid, but we still want it to test the other session.
981 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
982}
983
Steven Moreland659416d2021-05-11 00:47:50 +0000984TEST_P(BinderRpc, Callbacks) {
985 const static std::string kTestString = "good afternoon!";
986
Steven Morelandc7d40132021-06-10 03:42:11 +0000987 for (bool callIsOneway : {true, false}) {
988 for (bool callbackIsOneway : {true, false}) {
989 for (bool delayed : {true, false}) {
990 auto proc = createRpcTestSocketServerProcess(1, 1, 1);
991 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +0000992
Steven Morelandc7d40132021-06-10 03:42:11 +0000993 if (callIsOneway) {
994 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
995 kTestString));
996 } else {
997 EXPECT_OK(
998 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
999 }
Steven Moreland659416d2021-05-11 00:47:50 +00001000
Steven Morelandc7d40132021-06-10 03:42:11 +00001001 using std::literals::chrono_literals::operator""s;
1002 std::unique_lock<std::mutex> _l(cb->mMutex);
1003 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001004
Steven Morelandc7d40132021-06-10 03:42:11 +00001005 EXPECT_EQ(cb->mValues.size(), 1)
1006 << "callIsOneway: " << callIsOneway
1007 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1008 if (cb->mValues.empty()) continue;
1009 EXPECT_EQ(cb->mValues.at(0), kTestString)
1010 << "callIsOneway: " << callIsOneway
1011 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001012
Steven Morelandc7d40132021-06-10 03:42:11 +00001013 // since we are severing the connection, we need to go ahead and
1014 // tell the server to shutdown and exit so that waitpid won't hang
1015 EXPECT_OK(proc.rootIface->scheduleShutdown());
Steven Moreland659416d2021-05-11 00:47:50 +00001016
Steven Morelandc7d40132021-06-10 03:42:11 +00001017 // since this session has a reverse connection w/ a threadpool, we
1018 // need to manually shut it down
1019 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001020
Steven Morelandc7d40132021-06-10 03:42:11 +00001021 proc.expectAlreadyShutdown = true;
1022 }
Steven Moreland659416d2021-05-11 00:47:50 +00001023 }
1024 }
1025}
1026
Steven Moreland195edb82021-06-08 02:44:39 +00001027TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
1028 auto proc = createRpcTestSocketServerProcess(1);
1029 auto cb = sp<MyBinderRpcCallback>::make();
1030
1031 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1032 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1033}
1034
Steven Morelandc1635952021-04-01 16:20:47 +00001035TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001036 for (bool doDeathCleanup : {true, false}) {
1037 auto proc = createRpcTestSocketServerProcess(1);
1038
1039 // make sure there is some state during crash
1040 // 1. we hold their binder
1041 sp<IBinderRpcSession> session;
1042 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1043 // 2. they hold our binder
1044 sp<IBinder> binder = new BBinder();
1045 EXPECT_OK(proc.rootIface->holdBinder(binder));
1046
1047 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1048 << "Do death cleanup: " << doDeathCleanup;
1049
Steven Morelandaf4ca712021-05-24 23:22:08 +00001050 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001051 }
1052}
1053
Steven Morelandd7302072021-05-15 01:32:04 +00001054TEST_P(BinderRpc, UseKernelBinderCallingId) {
1055 auto proc = createRpcTestSocketServerProcess(1);
1056
1057 // we can't allocate IPCThreadState so actually the first time should
1058 // succeed :(
1059 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1060
1061 // second time! we catch the error :)
1062 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1063
Steven Morelandaf4ca712021-05-24 23:22:08 +00001064 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001065}
1066
Steven Moreland37aff182021-03-26 02:04:16 +00001067TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
1068 auto proc = createRpcTestSocketServerProcess(1);
1069
1070 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1071 ASSERT_NE(binder, nullptr);
1072
1073 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1074}
1075
1076TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
1077 auto proc = createRpcTestSocketServerProcess(1);
1078
1079 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1080 ASSERT_NE(binder, nullptr);
1081
1082 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1083 ASSERT_NE(ndkBinder, nullptr);
1084
1085 std::string out;
1086 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1087 ASSERT_TRUE(status.isOk()) << status.getDescription();
1088 ASSERT_EQ("aoeuaoeu", out);
1089}
1090
Steven Moreland5553ac42020-11-11 02:14:45 +00001091ssize_t countFds() {
1092 DIR* dir = opendir("/proc/self/fd/");
1093 if (dir == nullptr) return -1;
1094 ssize_t ret = 0;
1095 dirent* ent;
1096 while ((ent = readdir(dir)) != nullptr) ret++;
1097 closedir(dir);
1098 return ret;
1099}
1100
Steven Morelandc1635952021-04-01 16:20:47 +00001101TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001102 ssize_t beforeFds = countFds();
1103 ASSERT_GE(beforeFds, 0);
1104 {
1105 auto proc = createRpcTestSocketServerProcess(10);
1106 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1107 }
1108 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1109}
1110
Steven Morelandc1635952021-04-01 16:20:47 +00001111INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Yifan Hong0d2bd112021-04-13 17:38:36 -07001112 ::testing::ValuesIn({
1113 SocketType::UNIX,
Steven Morelandbd5002b2021-05-04 23:12:56 +00001114// TODO(b/185269356): working on host
Steven Morelandf6ec4632021-04-01 16:20:47 +00001115#ifdef __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -07001116 SocketType::VSOCK,
Steven Morelandbd5002b2021-05-04 23:12:56 +00001117#endif
Yifan Hong0d2bd112021-04-13 17:38:36 -07001118 SocketType::INET,
1119 }),
Steven Morelandf6ec4632021-04-01 16:20:47 +00001120 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +00001121
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001122class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
1123
1124TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1125 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1126 auto setRootObject = [](bool isStrong) -> SetFn {
1127 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1128 };
1129
1130 auto server = RpcServer::make();
1131 auto [isStrong1, isStrong2] = GetParam();
1132 auto binder1 = sp<BBinder>::make();
1133 IBinder* binderRaw1 = binder1.get();
1134 setRootObject(isStrong1)(server.get(), binder1);
1135 EXPECT_EQ(binderRaw1, server->getRootObject());
1136 binder1.clear();
1137 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1138
1139 auto binder2 = sp<BBinder>::make();
1140 IBinder* binderRaw2 = binder2.get();
1141 setRootObject(isStrong2)(server.get(), binder2);
1142 EXPECT_EQ(binderRaw2, server->getRootObject());
1143 binder2.clear();
1144 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1145}
1146
1147INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
1148 ::testing::Combine(::testing::Bool(), ::testing::Bool()));
1149
Yifan Hong1a235852021-05-13 16:07:47 -07001150class OneOffSignal {
1151public:
1152 // If notify() was previously called, or is called within |duration|, return true; else false.
1153 template <typename R, typename P>
1154 bool wait(std::chrono::duration<R, P> duration) {
1155 std::unique_lock<std::mutex> lock(mMutex);
1156 return mCv.wait_for(lock, duration, [this] { return mValue; });
1157 }
1158 void notify() {
1159 std::unique_lock<std::mutex> lock(mMutex);
1160 mValue = true;
1161 lock.unlock();
1162 mCv.notify_all();
1163 }
1164
1165private:
1166 std::mutex mMutex;
1167 std::condition_variable mCv;
1168 bool mValue = false;
1169};
1170
1171TEST(BinderRpc, Shutdown) {
1172 auto addr = allocateSocketAddress();
1173 unlink(addr.c_str());
1174 auto server = RpcServer::make();
1175 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1176 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1177 auto joinEnds = std::make_shared<OneOffSignal>();
1178
1179 // If things are broken and the thread never stops, don't block other tests. Because the thread
1180 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1181 // shared pointers are passed.
1182 std::thread([server, joinEnds] {
1183 server->join();
1184 joinEnds->notify();
1185 }).detach();
1186
1187 bool shutdown = false;
1188 for (int i = 0; i < 10 && !shutdown; i++) {
1189 usleep(300 * 1000); // 300ms; total 3s
1190 if (server->shutdown()) shutdown = true;
1191 }
1192 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1193
1194 ASSERT_TRUE(joinEnds->wait(2s))
1195 << "After server->shutdown() returns true, join() did not stop after 2s";
1196}
1197
Steven Morelandc1635952021-04-01 16:20:47 +00001198} // namespace android
1199
1200int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001201 ::testing::InitGoogleTest(&argc, argv);
1202 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1203 return RUN_ALL_TESTS();
1204}