blob: e48b7c54a57936cb32f9d339f2b5353606c8f5c0 [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Steven Moreland659416d2021-05-11 00:47:50 +000017#include <BnBinderRpcCallback.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000018#include <BnBinderRpcSession.h>
19#include <BnBinderRpcTest.h>
Steven Moreland37aff182021-03-26 02:04:16 +000020#include <aidl/IBinderRpcTest.h>
Yifan Hong6d82c8a2021-04-26 20:26:45 -070021#include <android-base/file.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000022#include <android-base/logging.h>
Steven Moreland37aff182021-03-26 02:04:16 +000023#include <android/binder_auto_utils.h>
24#include <android/binder_libbinder.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000025#include <binder/Binder.h>
26#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000027#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000028#include <binder/IServiceManager.h>
29#include <binder/ProcessState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000030#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000031#include <binder/RpcSession.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000032#include <gtest/gtest.h>
33
Steven Morelandc1635952021-04-01 16:20:47 +000034#include <chrono>
35#include <cstdlib>
36#include <iostream>
37#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000038#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000039
Steven Morelandc1635952021-04-01 16:20:47 +000040#include <sys/prctl.h>
41#include <unistd.h>
42
Steven Morelandbd5002b2021-05-04 23:12:56 +000043#include "../RpcState.h" // for debugging
44#include "../vm_sockets.h" // for VMADDR_*
Steven Moreland5553ac42020-11-11 02:14:45 +000045
Yifan Hong1a235852021-05-13 16:07:47 -070046using namespace std::chrono_literals;
47
Steven Moreland5553ac42020-11-11 02:14:45 +000048namespace android {
49
Steven Moreland1fda67b2021-04-02 18:35:50 +000050TEST(BinderRpcParcel, EntireParcelFormatted) {
51 Parcel p;
52 p.writeInt32(3);
53
54 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
55}
56
Yifan Hong00aeb762021-05-12 17:07:36 -070057TEST(BinderRpc, SetExternalServer) {
58 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
59 int sinkFd = sink.get();
60 auto server = RpcServer::make();
61 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
62 ASSERT_FALSE(server->hasServer());
63 ASSERT_TRUE(server->setupExternalServer(std::move(sink)));
64 ASSERT_TRUE(server->hasServer());
65 base::unique_fd retrieved = server->releaseServer();
66 ASSERT_FALSE(server->hasServer());
67 ASSERT_EQ(sinkFd, retrieved.get());
68}
69
Steven Moreland5553ac42020-11-11 02:14:45 +000070using android::binder::Status;
71
72#define EXPECT_OK(status) \
73 do { \
74 Status stat = (status); \
75 EXPECT_TRUE(stat.isOk()) << stat; \
76 } while (false)
77
78class MyBinderRpcSession : public BnBinderRpcSession {
79public:
80 static std::atomic<int32_t> gNum;
81
82 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
83 Status getName(std::string* name) override {
84 *name = mName;
85 return Status::ok();
86 }
87 ~MyBinderRpcSession() { gNum--; }
88
89private:
90 std::string mName;
91};
92std::atomic<int32_t> MyBinderRpcSession::gNum;
93
Steven Moreland659416d2021-05-11 00:47:50 +000094class MyBinderRpcCallback : public BnBinderRpcCallback {
95 Status sendCallback(const std::string& value) {
96 std::unique_lock _l(mMutex);
97 mValues.push_back(value);
98 _l.unlock();
99 mCv.notify_one();
100 return Status::ok();
101 }
102 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
103
104public:
105 std::mutex mMutex;
106 std::condition_variable mCv;
107 std::vector<std::string> mValues;
108};
109
Steven Moreland5553ac42020-11-11 02:14:45 +0000110class MyBinderRpcTest : public BnBinderRpcTest {
111public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000112 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +0000113
114 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000115 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000116 return Status::ok();
117 }
118 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000119 *strstr = str + str;
120 return Status::ok();
121 }
Steven Moreland736664b2021-05-01 04:27:25 +0000122 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000123 sp<RpcServer> spServer = server.promote();
124 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000125 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
126 }
Steven Moreland736664b2021-05-01 04:27:25 +0000127 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000128 for (auto session : spServer->listSessions()) {
129 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000130 if (count != 1) {
131 // this is called when there is only one binder held remaining,
132 // so to aid debugging
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000133 session->state()->dump();
Steven Moreland611d15f2021-05-01 01:28:27 +0000134 }
Steven Moreland736664b2021-05-01 04:27:25 +0000135 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000136 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000137 return Status::ok();
138 }
139 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
140 if (binder == nullptr) {
141 std::cout << "Received null binder!" << std::endl;
142 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
143 }
144 *out = binder->pingBinder();
145 return Status::ok();
146 }
147 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
148 *out = binder;
149 return Status::ok();
150 }
151 static sp<IBinder> mHeldBinder;
152 Status holdBinder(const sp<IBinder>& binder) override {
153 mHeldBinder = binder;
154 return Status::ok();
155 }
156 Status getHeldBinder(sp<IBinder>* held) override {
157 *held = mHeldBinder;
158 return Status::ok();
159 }
160 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
161 if (count <= 0) return Status::ok();
162 return binder->nestMe(this, count - 1);
163 }
164 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
165 static sp<IBinder> binder = new BBinder;
166 *out = binder;
167 return Status::ok();
168 }
169 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
170 *out = new MyBinderRpcSession(name);
171 return Status::ok();
172 }
173 Status getNumOpenSessions(int32_t* out) override {
174 *out = MyBinderRpcSession::gNum;
175 return Status::ok();
176 }
177
178 std::mutex blockMutex;
179 Status lock() override {
180 blockMutex.lock();
181 return Status::ok();
182 }
183 Status unlockInMsAsync(int32_t ms) override {
184 usleep(ms * 1000);
185 blockMutex.unlock();
186 return Status::ok();
187 }
188 Status lockUnlock() override {
189 std::lock_guard<std::mutex> _l(blockMutex);
190 return Status::ok();
191 }
192
193 Status sleepMs(int32_t ms) override {
194 usleep(ms * 1000);
195 return Status::ok();
196 }
197
198 Status sleepMsAsync(int32_t ms) override {
199 // In-process binder calls are asynchronous, but the call to this method
200 // is synchronous wrt its client. This in/out-process threading model
201 // diffentiation is a classic binder leaky abstraction (for better or
202 // worse) and is preserved here the way binder sockets plugs itself
203 // into BpBinder, as nothing is changed at the higher levels
204 // (IInterface) which result in this behavior.
205 return sleepMs(ms);
206 }
207
Steven Moreland659416d2021-05-11 00:47:50 +0000208 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
209 const std::string& value) override {
210 if (callback == nullptr) {
211 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
212 }
213
214 if (delayed) {
215 std::thread([=]() {
216 ALOGE("Executing delayed callback: '%s'", value.c_str());
217 (void)doCallback(callback, oneway, false, value);
218 }).detach();
219 return Status::ok();
220 }
221
222 if (oneway) {
223 return callback->sendOnewayCallback(value);
224 }
225
226 return callback->sendCallback(value);
227 }
228
Steven Moreland5553ac42020-11-11 02:14:45 +0000229 Status die(bool cleanup) override {
230 if (cleanup) {
231 exit(1);
232 } else {
233 _exit(1);
234 }
235 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000236
237 Status scheduleShutdown() override {
238 sp<RpcServer> strongServer = server.promote();
239 if (strongServer == nullptr) {
240 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
241 }
242 std::thread([=] {
243 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
244 }).detach();
245 return Status::ok();
246 }
247
Steven Morelandd7302072021-05-15 01:32:04 +0000248 Status useKernelBinderCallingId() override {
249 // this is WRONG! It does not make sense when using RPC binder, and
250 // because it is SO wrong, and so much code calls this, it should abort!
251
252 (void)IPCThreadState::self()->getCallingPid();
253 return Status::ok();
254 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000255};
256sp<IBinder> MyBinderRpcTest::mHeldBinder;
257
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700258class Pipe {
259public:
260 Pipe() { CHECK(android::base::Pipe(&mRead, &mWrite)); }
261 Pipe(Pipe&&) = default;
262 android::base::borrowed_fd readEnd() { return mRead; }
263 android::base::borrowed_fd writeEnd() { return mWrite; }
264
265private:
266 android::base::unique_fd mRead;
267 android::base::unique_fd mWrite;
268};
269
Steven Moreland5553ac42020-11-11 02:14:45 +0000270class Process {
271public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700272 Process(Process&&) = default;
273 Process(const std::function<void(Pipe*)>& f) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000274 if (0 == (mPid = fork())) {
275 // racey: assume parent doesn't crash before this is set
276 prctl(PR_SET_PDEATHSIG, SIGHUP);
277
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700278 f(&mPipe);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000279
280 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000281 }
282 }
283 ~Process() {
284 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000285 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000286 }
287 }
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700288 Pipe* getPipe() { return &mPipe; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000289
290private:
291 pid_t mPid = 0;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700292 Pipe mPipe;
Steven Moreland5553ac42020-11-11 02:14:45 +0000293};
294
295static std::string allocateSocketAddress() {
296 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000297 std::string temp = getenv("TMPDIR") ?: "/tmp";
298 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000299};
300
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000301struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000302 // reference to process hosting a socket server
303 Process host;
304
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000305 struct SessionInfo {
306 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000307 sp<IBinder> root;
308 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000309
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000310 // client session objects associated with other process
311 // each one represents a separate session
312 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000313
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000314 ProcessSession(ProcessSession&&) = default;
315 ~ProcessSession() {
316 for (auto& session : sessions) {
317 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000318 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000319
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000320 for (auto& info : sessions) {
321 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000322
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000323 EXPECT_NE(nullptr, session);
324 EXPECT_NE(nullptr, session->state());
325 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000326
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000327 wp<RpcSession> weakSession = session;
328 session = nullptr;
329 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000330 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000331 }
332};
333
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000334// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000335// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000336struct BinderRpcTestProcessSession {
337 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000338
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000339 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000340 sp<IBinder> rootBinder;
341
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000342 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000343 sp<IBinderRpcTest> rootIface;
344
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000345 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000346 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000347
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000348 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
349 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000350 EXPECT_NE(nullptr, rootIface);
351 if (rootIface == nullptr) return;
352
Steven Morelandaf4ca712021-05-24 23:22:08 +0000353 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000354 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000355 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000356 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000357 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000358 for (auto remoteCount : remoteCounts) {
359 EXPECT_EQ(remoteCount, 1);
360 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000361
362 EXPECT_OK(rootIface->scheduleShutdown());
Steven Moreland5553ac42020-11-11 02:14:45 +0000363 }
364
365 rootIface = nullptr;
366 rootBinder = nullptr;
367 }
368};
369
Steven Morelandc1635952021-04-01 16:20:47 +0000370enum class SocketType {
371 UNIX,
372 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700373 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000374};
375static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
376 switch (info.param) {
377 case SocketType::UNIX:
378 return "unix_domain_socket";
379 case SocketType::VSOCK:
380 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700381 case SocketType::INET:
382 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000383 default:
384 LOG_ALWAYS_FATAL("Unknown socket type");
385 return "";
386 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000387}
Steven Morelandc1635952021-04-01 16:20:47 +0000388class BinderRpc : public ::testing::TestWithParam<SocketType> {
389public:
390 // This creates a new process serving an interface on a certain number of
391 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000392 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland659416d2021-05-11 00:47:50 +0000393 size_t numThreads, size_t numSessions, size_t numReverseConnections,
Steven Moreland736664b2021-05-01 04:27:25 +0000394 const std::function<void(const sp<RpcServer>&)>& configure) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395 CHECK_GE(numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000396
Steven Morelandc1635952021-04-01 16:20:47 +0000397 SocketType socketType = GetParam();
398
399 std::string addr = allocateSocketAddress();
400 unlink(addr.c_str());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700401 static unsigned int vsockPort = 3456;
402 vsockPort++;
Steven Morelandc1635952021-04-01 16:20:47 +0000403
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000404 auto ret = ProcessSession{
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700405 .host = Process([&](Pipe* pipe) {
Steven Morelandc1635952021-04-01 16:20:47 +0000406 sp<RpcServer> server = RpcServer::make();
407
408 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Morelandf137de92021-04-24 01:54:26 +0000409 server->setMaxThreads(numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000410
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000411 unsigned int outPort = 0;
412
Steven Morelandc1635952021-04-01 16:20:47 +0000413 switch (socketType) {
414 case SocketType::UNIX:
Steven Moreland611d15f2021-05-01 01:28:27 +0000415 CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000416 break;
417 case SocketType::VSOCK:
Steven Moreland611d15f2021-05-01 01:28:27 +0000418 CHECK(server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000419 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700420 case SocketType::INET: {
Steven Moreland611d15f2021-05-01 01:28:27 +0000421 CHECK(server->setupInetServer(0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700422 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700423 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700424 }
Steven Morelandc1635952021-04-01 16:20:47 +0000425 default:
426 LOG_ALWAYS_FATAL("Unknown socket type");
427 }
428
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000429 CHECK(android::base::WriteFully(pipe->writeEnd(), &outPort, sizeof(outPort)));
430
Steven Moreland611d15f2021-05-01 01:28:27 +0000431 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000432
Steven Morelandf137de92021-04-24 01:54:26 +0000433 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000434
435 // Another thread calls shutdown. Wait for it to complete.
436 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000437 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000438 };
439
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000440 // always read socket, so that we have waited for the server to start
441 unsigned int outPort = 0;
442 CHECK(android::base::ReadFully(ret.host.getPipe()->readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700443 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000444 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700445 }
446
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000447 for (size_t i = 0; i < numSessions; i++) {
448 sp<RpcSession> session = RpcSession::make();
Steven Moreland103424e2021-06-02 18:16:19 +0000449 session->setMaxThreads(numReverseConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000450
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000451 switch (socketType) {
452 case SocketType::UNIX:
453 if (session->setupUnixDomainClient(addr.c_str())) goto success;
454 break;
455 case SocketType::VSOCK:
456 if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
457 break;
458 case SocketType::INET:
459 if (session->setupInetClient("127.0.0.1", outPort)) goto success;
460 break;
461 default:
462 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000463 }
Steven Moreland736664b2021-05-01 04:27:25 +0000464 LOG_ALWAYS_FATAL("Could not connect");
465 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000466 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000467 }
Steven Morelandc1635952021-04-01 16:20:47 +0000468 return ret;
469 }
470
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000471 BinderRpcTestProcessSession createRpcTestSocketServerProcess(size_t numThreads,
Steven Moreland659416d2021-05-11 00:47:50 +0000472 size_t numSessions = 1,
473 size_t numReverseConnections = 0) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000474 BinderRpcTestProcessSession ret{
475 .proc = createRpcTestSocketServerProcess(numThreads, numSessions,
Steven Moreland659416d2021-05-11 00:47:50 +0000476 numReverseConnections,
Steven Moreland611d15f2021-05-01 01:28:27 +0000477 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000478 sp<MyBinderRpcTest> service =
479 new MyBinderRpcTest;
480 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000481 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000482 }),
483 };
484
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000485 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000486 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
487
488 return ret;
489 }
490};
491
Steven Morelandc1635952021-04-01 16:20:47 +0000492TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000493 auto proc = createRpcTestSocketServerProcess(1);
494 ASSERT_NE(proc.rootBinder, nullptr);
495 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
496}
497
Steven Moreland4cf688f2021-03-31 01:48:58 +0000498TEST_P(BinderRpc, GetInterfaceDescriptor) {
499 auto proc = createRpcTestSocketServerProcess(1);
500 ASSERT_NE(proc.rootBinder, nullptr);
501 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
502}
503
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000504TEST_P(BinderRpc, MultipleSessions) {
505 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 5 /*sessions*/);
506 for (auto session : proc.proc.sessions) {
507 ASSERT_NE(nullptr, session.root);
508 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000509 }
510}
511
Steven Morelandc1635952021-04-01 16:20:47 +0000512TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000513 auto proc = createRpcTestSocketServerProcess(1);
514 Parcel data;
515 Parcel reply;
516 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
517}
518
Steven Moreland67753c32021-04-02 18:45:19 +0000519TEST_P(BinderRpc, AppendSeparateFormats) {
520 auto proc = createRpcTestSocketServerProcess(1);
521
522 Parcel p1;
523 p1.markForBinder(proc.rootBinder);
524 p1.writeInt32(3);
525
526 Parcel p2;
527
528 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
529 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
530}
531
Steven Morelandc1635952021-04-01 16:20:47 +0000532TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000533 auto proc = createRpcTestSocketServerProcess(1);
534 Parcel data;
535 data.markForBinder(proc.rootBinder);
536 Parcel reply;
537 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
538}
539
Steven Morelandc1635952021-04-01 16:20:47 +0000540TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000541 auto proc = createRpcTestSocketServerProcess(1);
542 EXPECT_OK(proc.rootIface->sendString("asdf"));
543}
544
Steven Morelandc1635952021-04-01 16:20:47 +0000545TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000546 auto proc = createRpcTestSocketServerProcess(1);
547 std::string doubled;
548 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
549 EXPECT_EQ("cool cool ", doubled);
550}
551
Steven Morelandc1635952021-04-01 16:20:47 +0000552TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000553 auto proc = createRpcTestSocketServerProcess(1);
554 std::string single = std::string(1024, 'a');
555 std::string doubled;
556 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
557 EXPECT_EQ(single + single, doubled);
558}
559
Steven Morelandc1635952021-04-01 16:20:47 +0000560TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000561 auto proc = createRpcTestSocketServerProcess(1);
562
563 int32_t pingResult;
564 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
565 EXPECT_EQ(OK, pingResult);
566
567 EXPECT_EQ(0, MyBinderRpcSession::gNum);
568}
569
Steven Morelandc1635952021-04-01 16:20:47 +0000570TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000571 auto proc = createRpcTestSocketServerProcess(1);
572
573 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
574 sp<IBinder> outBinder;
575 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
576 EXPECT_EQ(inBinder, outBinder);
577
578 wp<IBinder> weak = inBinder;
579 inBinder = nullptr;
580 outBinder = nullptr;
581
582 // Force reading a reply, to process any pending dec refs from the other
583 // process (the other process will process dec refs there before processing
584 // the ping here).
585 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
586
587 EXPECT_EQ(nullptr, weak.promote());
588
589 EXPECT_EQ(0, MyBinderRpcSession::gNum);
590}
591
Steven Morelandc1635952021-04-01 16:20:47 +0000592TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000593 auto proc = createRpcTestSocketServerProcess(1);
594
595 sp<IBinderRpcSession> session;
596 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
597
598 sp<IBinder> inBinder = IInterface::asBinder(session);
599 sp<IBinder> outBinder;
600 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
601 EXPECT_EQ(inBinder, outBinder);
602
603 wp<IBinder> weak = inBinder;
604 session = nullptr;
605 inBinder = nullptr;
606 outBinder = nullptr;
607
608 // Force reading a reply, to process any pending dec refs from the other
609 // process (the other process will process dec refs there before processing
610 // the ping here).
611 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
612
613 EXPECT_EQ(nullptr, weak.promote());
614}
615
Steven Morelandc1635952021-04-01 16:20:47 +0000616TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000617 auto proc = createRpcTestSocketServerProcess(1);
618
619 sp<IBinder> outBinder;
620 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
621 EXPECT_EQ(nullptr, outBinder);
622}
623
Steven Morelandc1635952021-04-01 16:20:47 +0000624TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000625 auto proc = createRpcTestSocketServerProcess(1);
626
627 IBinder* ptr = nullptr;
628 {
629 sp<IBinder> binder = new BBinder();
630 ptr = binder.get();
631 EXPECT_OK(proc.rootIface->holdBinder(binder));
632 }
633
634 sp<IBinder> held;
635 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
636
637 EXPECT_EQ(held.get(), ptr);
638
639 // stop holding binder, because we test to make sure references are cleaned
640 // up
641 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
642 // and flush ref counts
643 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
644}
645
646// START TESTS FOR LIMITATIONS OF SOCKET BINDER
647// These are behavioral differences form regular binder, where certain usecases
648// aren't supported.
649
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000650TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000651 auto proc1 = createRpcTestSocketServerProcess(1);
652 auto proc2 = createRpcTestSocketServerProcess(1);
653
654 sp<IBinder> outBinder;
655 EXPECT_EQ(INVALID_OPERATION,
656 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
657}
658
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000659TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
660 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 2 /*sessions*/);
Steven Moreland736664b2021-05-01 04:27:25 +0000661
662 sp<IBinder> outBinder;
663 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000664 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000665 .transactionError());
666}
667
Steven Morelandc1635952021-04-01 16:20:47 +0000668TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000669 auto proc = createRpcTestSocketServerProcess(1);
670
671 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
672 sp<IBinder> outBinder;
673 EXPECT_EQ(INVALID_OPERATION,
674 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
675}
676
Steven Morelandc1635952021-04-01 16:20:47 +0000677TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000678 auto proc = createRpcTestSocketServerProcess(1);
679
680 // for historical reasons, IServiceManager interface only returns the
681 // exception code
682 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
683 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
684}
685
686// END TESTS FOR LIMITATIONS OF SOCKET BINDER
687
Steven Morelandc1635952021-04-01 16:20:47 +0000688TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000689 auto proc = createRpcTestSocketServerProcess(1);
690
691 sp<IBinder> outBinder;
692 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
693 EXPECT_EQ(proc.rootBinder, outBinder);
694}
695
Steven Morelandc1635952021-04-01 16:20:47 +0000696TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000697 auto proc = createRpcTestSocketServerProcess(1);
698
699 auto nastyNester = sp<MyBinderRpcTest>::make();
700 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
701
702 wp<IBinder> weak = nastyNester;
703 nastyNester = nullptr;
704 EXPECT_EQ(nullptr, weak.promote());
705}
706
Steven Morelandc1635952021-04-01 16:20:47 +0000707TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000708 auto proc = createRpcTestSocketServerProcess(1);
709
710 sp<IBinder> a;
711 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
712
713 sp<IBinder> b;
714 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
715
716 EXPECT_EQ(a, b);
717}
718
Steven Morelandc1635952021-04-01 16:20:47 +0000719TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000720 auto proc = createRpcTestSocketServerProcess(1);
721
722 sp<IBinder> a;
723 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
724 wp<IBinder> weak = a;
725 a = nullptr;
726
727 sp<IBinder> b;
728 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
729
730 // this is the wrong behavior, since BpBinder
731 // doesn't implement onIncStrongAttempted
732 // but make sure there is no crash
733 EXPECT_EQ(nullptr, weak.promote());
734
735 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
736
737 // In order to fix this:
738 // - need to have incStrongAttempted reflected across IPC boundary (wait for
739 // response to promote - round trip...)
740 // - sendOnLastWeakRef, to delete entries out of RpcState table
741 EXPECT_EQ(b, weak.promote());
742}
743
744#define expectSessions(expected, iface) \
745 do { \
746 int session; \
747 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
748 EXPECT_EQ(expected, session); \
749 } while (false)
750
Steven Morelandc1635952021-04-01 16:20:47 +0000751TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000752 auto proc = createRpcTestSocketServerProcess(1);
753
754 sp<IBinderRpcSession> session;
755 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
756 std::string out;
757 EXPECT_OK(session->getName(&out));
758 EXPECT_EQ("aoeu", out);
759
760 expectSessions(1, proc.rootIface);
761 session = nullptr;
762 expectSessions(0, proc.rootIface);
763}
764
Steven Morelandc1635952021-04-01 16:20:47 +0000765TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000766 auto proc = createRpcTestSocketServerProcess(1);
767
768 std::vector<sp<IBinderRpcSession>> sessions;
769
770 for (size_t i = 0; i < 15; i++) {
771 expectSessions(i, proc.rootIface);
772 sp<IBinderRpcSession> session;
773 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
774 sessions.push_back(session);
775 }
776 expectSessions(sessions.size(), proc.rootIface);
777 for (size_t i = 0; i < sessions.size(); i++) {
778 std::string out;
779 EXPECT_OK(sessions.at(i)->getName(&out));
780 EXPECT_EQ(std::to_string(i), out);
781 }
782 expectSessions(sessions.size(), proc.rootIface);
783
784 while (!sessions.empty()) {
785 sessions.pop_back();
786 expectSessions(sessions.size(), proc.rootIface);
787 }
788 expectSessions(0, proc.rootIface);
789}
790
791size_t epochMillis() {
792 using std::chrono::duration_cast;
793 using std::chrono::milliseconds;
794 using std::chrono::seconds;
795 using std::chrono::system_clock;
796 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
797}
798
Steven Morelandc1635952021-04-01 16:20:47 +0000799TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000800 constexpr size_t kNumThreads = 10;
801
802 auto proc = createRpcTestSocketServerProcess(kNumThreads);
803
804 EXPECT_OK(proc.rootIface->lock());
805
806 // block all but one thread taking locks
807 std::vector<std::thread> ts;
808 for (size_t i = 0; i < kNumThreads - 1; i++) {
809 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
810 }
811
812 usleep(100000); // give chance for calls on other threads
813
814 // other calls still work
815 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
816
817 constexpr size_t blockTimeMs = 500;
818 size_t epochMsBefore = epochMillis();
819 // after this, we should never see a response within this time
820 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
821
822 // this call should be blocked for blockTimeMs
823 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
824
825 size_t epochMsAfter = epochMillis();
826 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
827
828 for (auto& t : ts) t.join();
829}
830
Steven Morelandc1635952021-04-01 16:20:47 +0000831TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000832 constexpr size_t kNumThreads = 10;
833 constexpr size_t kNumCalls = kNumThreads + 3;
834 constexpr size_t kSleepMs = 500;
835
836 auto proc = createRpcTestSocketServerProcess(kNumThreads);
837
838 size_t epochMsBefore = epochMillis();
839
840 std::vector<std::thread> ts;
841 for (size_t i = 0; i < kNumCalls; i++) {
842 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
843 }
844
845 for (auto& t : ts) t.join();
846
847 size_t epochMsAfter = epochMillis();
848
849 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
850
851 // Potential flake, but make sure calls are handled in parallel.
852 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
853}
854
Steven Morelandc1635952021-04-01 16:20:47 +0000855TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000856 constexpr size_t kNumClientThreads = 10;
857 constexpr size_t kNumServerThreads = 10;
858 constexpr size_t kNumCalls = 100;
859
860 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
861
862 std::vector<std::thread> threads;
863 for (size_t i = 0; i < kNumClientThreads; i++) {
864 threads.push_back(std::thread([&] {
865 for (size_t j = 0; j < kNumCalls; j++) {
866 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000867 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000868 EXPECT_EQ(proc.rootBinder, out);
869 }
870 }));
871 }
872
873 for (auto& t : threads) t.join();
874}
875
Steven Morelandc6046982021-04-20 00:49:42 +0000876TEST_P(BinderRpc, OnewayStressTest) {
877 constexpr size_t kNumClientThreads = 10;
878 constexpr size_t kNumServerThreads = 10;
Steven Morelande38bcb02021-05-26 01:22:07 +0000879 constexpr size_t kNumCalls = 50;
Steven Morelandc6046982021-04-20 00:49:42 +0000880
881 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
882
883 std::vector<std::thread> threads;
884 for (size_t i = 0; i < kNumClientThreads; i++) {
885 threads.push_back(std::thread([&] {
886 for (size_t j = 0; j < kNumCalls; j++) {
887 EXPECT_OK(proc.rootIface->sendString("a"));
888 }
889
890 // check threads are not stuck
891 EXPECT_OK(proc.rootIface->sleepMs(250));
892 }));
893 }
894
895 for (auto& t : threads) t.join();
896}
897
Steven Morelandc1635952021-04-01 16:20:47 +0000898TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000899 constexpr size_t kReallyLongTimeMs = 100;
900 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
901
Steven Morelandf5174272021-05-25 00:39:28 +0000902 auto proc = createRpcTestSocketServerProcess(1);
Steven Moreland5553ac42020-11-11 02:14:45 +0000903
904 size_t epochMsBefore = epochMillis();
905
906 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
907
908 size_t epochMsAfter = epochMillis();
909 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
910}
911
Steven Morelandc1635952021-04-01 16:20:47 +0000912TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000913 constexpr size_t kNumSleeps = 10;
914 constexpr size_t kNumExtraServerThreads = 4;
915 constexpr size_t kSleepMs = 50;
916
917 // make sure calls to the same object happen on the same thread
918 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
919
920 EXPECT_OK(proc.rootIface->lock());
921
922 for (size_t i = 0; i < kNumSleeps; i++) {
923 // these should be processed serially
924 proc.rootIface->sleepMsAsync(kSleepMs);
925 }
926 // should also be processesed serially
927 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
928
929 size_t epochMsBefore = epochMillis();
930 EXPECT_OK(proc.rootIface->lockUnlock());
931 size_t epochMsAfter = epochMillis();
932
933 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000934
935 // pending oneway transactions hold ref, make sure we read data on all
936 // sockets
937 std::vector<std::thread> threads;
938 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
939 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
940 }
941 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +0000942}
943
Steven Moreland659416d2021-05-11 00:47:50 +0000944TEST_P(BinderRpc, Callbacks) {
945 const static std::string kTestString = "good afternoon!";
946
947 for (bool oneway : {true, false}) {
948 for (bool delayed : {true, false}) {
949 auto proc = createRpcTestSocketServerProcess(1, 1, 1);
950 auto cb = sp<MyBinderRpcCallback>::make();
951
952 EXPECT_OK(proc.rootIface->doCallback(cb, oneway, delayed, kTestString));
953
954 using std::literals::chrono_literals::operator""s;
955 std::unique_lock<std::mutex> _l(cb->mMutex);
956 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
957
958 EXPECT_EQ(cb->mValues.size(), 1) << "oneway: " << oneway << "delayed: " << delayed;
959 if (cb->mValues.empty()) continue;
960 EXPECT_EQ(cb->mValues.at(0), kTestString)
961 << "oneway: " << oneway << "delayed: " << delayed;
962
963 // since we are severing the connection, we need to go ahead and
964 // tell the server to shutdown and exit so that waitpid won't hang
965 EXPECT_OK(proc.rootIface->scheduleShutdown());
966
967 // since this session has a reverse connection w/ a threadpool, we
968 // need to manually shut it down
969 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdown());
970
971 proc.expectAlreadyShutdown = true;
972 }
973 }
974}
975
Steven Morelandc1635952021-04-01 16:20:47 +0000976TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000977 for (bool doDeathCleanup : {true, false}) {
978 auto proc = createRpcTestSocketServerProcess(1);
979
980 // make sure there is some state during crash
981 // 1. we hold their binder
982 sp<IBinderRpcSession> session;
983 EXPECT_OK(proc.rootIface->openSession("happy", &session));
984 // 2. they hold our binder
985 sp<IBinder> binder = new BBinder();
986 EXPECT_OK(proc.rootIface->holdBinder(binder));
987
988 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
989 << "Do death cleanup: " << doDeathCleanup;
990
Steven Morelandaf4ca712021-05-24 23:22:08 +0000991 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +0000992 }
993}
994
Steven Morelandd7302072021-05-15 01:32:04 +0000995TEST_P(BinderRpc, UseKernelBinderCallingId) {
996 auto proc = createRpcTestSocketServerProcess(1);
997
998 // we can't allocate IPCThreadState so actually the first time should
999 // succeed :(
1000 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1001
1002 // second time! we catch the error :)
1003 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1004
Steven Morelandaf4ca712021-05-24 23:22:08 +00001005 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001006}
1007
Steven Moreland37aff182021-03-26 02:04:16 +00001008TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
1009 auto proc = createRpcTestSocketServerProcess(1);
1010
1011 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1012 ASSERT_NE(binder, nullptr);
1013
1014 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1015}
1016
1017TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
1018 auto proc = createRpcTestSocketServerProcess(1);
1019
1020 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1021 ASSERT_NE(binder, nullptr);
1022
1023 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1024 ASSERT_NE(ndkBinder, nullptr);
1025
1026 std::string out;
1027 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1028 ASSERT_TRUE(status.isOk()) << status.getDescription();
1029 ASSERT_EQ("aoeuaoeu", out);
1030}
1031
Steven Moreland5553ac42020-11-11 02:14:45 +00001032ssize_t countFds() {
1033 DIR* dir = opendir("/proc/self/fd/");
1034 if (dir == nullptr) return -1;
1035 ssize_t ret = 0;
1036 dirent* ent;
1037 while ((ent = readdir(dir)) != nullptr) ret++;
1038 closedir(dir);
1039 return ret;
1040}
1041
Steven Morelandc1635952021-04-01 16:20:47 +00001042TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001043 ssize_t beforeFds = countFds();
1044 ASSERT_GE(beforeFds, 0);
1045 {
1046 auto proc = createRpcTestSocketServerProcess(10);
1047 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1048 }
1049 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1050}
1051
Steven Morelandc1635952021-04-01 16:20:47 +00001052INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
Yifan Hong0d2bd112021-04-13 17:38:36 -07001053 ::testing::ValuesIn({
1054 SocketType::UNIX,
Steven Morelandbd5002b2021-05-04 23:12:56 +00001055// TODO(b/185269356): working on host
Steven Morelandf6ec4632021-04-01 16:20:47 +00001056#ifdef __BIONIC__
Yifan Hong0d2bd112021-04-13 17:38:36 -07001057 SocketType::VSOCK,
Steven Morelandbd5002b2021-05-04 23:12:56 +00001058#endif
Yifan Hong0d2bd112021-04-13 17:38:36 -07001059 SocketType::INET,
1060 }),
Steven Morelandf6ec4632021-04-01 16:20:47 +00001061 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +00001062
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001063class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
1064
1065TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1066 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1067 auto setRootObject = [](bool isStrong) -> SetFn {
1068 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1069 };
1070
1071 auto server = RpcServer::make();
1072 auto [isStrong1, isStrong2] = GetParam();
1073 auto binder1 = sp<BBinder>::make();
1074 IBinder* binderRaw1 = binder1.get();
1075 setRootObject(isStrong1)(server.get(), binder1);
1076 EXPECT_EQ(binderRaw1, server->getRootObject());
1077 binder1.clear();
1078 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1079
1080 auto binder2 = sp<BBinder>::make();
1081 IBinder* binderRaw2 = binder2.get();
1082 setRootObject(isStrong2)(server.get(), binder2);
1083 EXPECT_EQ(binderRaw2, server->getRootObject());
1084 binder2.clear();
1085 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1086}
1087
1088INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
1089 ::testing::Combine(::testing::Bool(), ::testing::Bool()));
1090
Yifan Hong1a235852021-05-13 16:07:47 -07001091class OneOffSignal {
1092public:
1093 // If notify() was previously called, or is called within |duration|, return true; else false.
1094 template <typename R, typename P>
1095 bool wait(std::chrono::duration<R, P> duration) {
1096 std::unique_lock<std::mutex> lock(mMutex);
1097 return mCv.wait_for(lock, duration, [this] { return mValue; });
1098 }
1099 void notify() {
1100 std::unique_lock<std::mutex> lock(mMutex);
1101 mValue = true;
1102 lock.unlock();
1103 mCv.notify_all();
1104 }
1105
1106private:
1107 std::mutex mMutex;
1108 std::condition_variable mCv;
1109 bool mValue = false;
1110};
1111
1112TEST(BinderRpc, Shutdown) {
1113 auto addr = allocateSocketAddress();
1114 unlink(addr.c_str());
1115 auto server = RpcServer::make();
1116 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1117 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1118 auto joinEnds = std::make_shared<OneOffSignal>();
1119
1120 // If things are broken and the thread never stops, don't block other tests. Because the thread
1121 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1122 // shared pointers are passed.
1123 std::thread([server, joinEnds] {
1124 server->join();
1125 joinEnds->notify();
1126 }).detach();
1127
1128 bool shutdown = false;
1129 for (int i = 0; i < 10 && !shutdown; i++) {
1130 usleep(300 * 1000); // 300ms; total 3s
1131 if (server->shutdown()) shutdown = true;
1132 }
1133 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1134
1135 ASSERT_TRUE(joinEnds->wait(2s))
1136 << "After server->shutdown() returns true, join() did not stop after 2s";
1137}
1138
Steven Morelandc1635952021-04-01 16:20:47 +00001139} // namespace android
1140
1141int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001142 ::testing::InitGoogleTest(&argc, argv);
1143 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1144 return RUN_ALL_TESTS();
1145}