blob: 980d3cfd2ae2776358502c5d747c20e1b3064628 [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 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000131 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000132 return Status::ok();
133 }
134 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
135 if (binder == nullptr) {
136 std::cout << "Received null binder!" << std::endl;
137 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
138 }
139 *out = binder->pingBinder();
140 return Status::ok();
141 }
142 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
143 *out = binder;
144 return Status::ok();
145 }
146 static sp<IBinder> mHeldBinder;
147 Status holdBinder(const sp<IBinder>& binder) override {
148 mHeldBinder = binder;
149 return Status::ok();
150 }
151 Status getHeldBinder(sp<IBinder>* held) override {
152 *held = mHeldBinder;
153 return Status::ok();
154 }
155 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
156 if (count <= 0) return Status::ok();
157 return binder->nestMe(this, count - 1);
158 }
159 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
160 static sp<IBinder> binder = new BBinder;
161 *out = binder;
162 return Status::ok();
163 }
164 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
165 *out = new MyBinderRpcSession(name);
166 return Status::ok();
167 }
168 Status getNumOpenSessions(int32_t* out) override {
169 *out = MyBinderRpcSession::gNum;
170 return Status::ok();
171 }
172
173 std::mutex blockMutex;
174 Status lock() override {
175 blockMutex.lock();
176 return Status::ok();
177 }
178 Status unlockInMsAsync(int32_t ms) override {
179 usleep(ms * 1000);
180 blockMutex.unlock();
181 return Status::ok();
182 }
183 Status lockUnlock() override {
184 std::lock_guard<std::mutex> _l(blockMutex);
185 return Status::ok();
186 }
187
188 Status sleepMs(int32_t ms) override {
189 usleep(ms * 1000);
190 return Status::ok();
191 }
192
193 Status sleepMsAsync(int32_t ms) override {
194 // In-process binder calls are asynchronous, but the call to this method
195 // is synchronous wrt its client. This in/out-process threading model
196 // diffentiation is a classic binder leaky abstraction (for better or
197 // worse) and is preserved here the way binder sockets plugs itself
198 // into BpBinder, as nothing is changed at the higher levels
199 // (IInterface) which result in this behavior.
200 return sleepMs(ms);
201 }
202
Steven Moreland659416d2021-05-11 00:47:50 +0000203 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
204 const std::string& value) override {
205 if (callback == nullptr) {
206 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
207 }
208
209 if (delayed) {
210 std::thread([=]() {
211 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000212 Status status = doCallback(callback, oneway, false, value);
213 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000214 }).detach();
215 return Status::ok();
216 }
217
218 if (oneway) {
219 return callback->sendOnewayCallback(value);
220 }
221
222 return callback->sendCallback(value);
223 }
224
Steven Morelandc7d40132021-06-10 03:42:11 +0000225 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
226 const std::string& value) override {
227 return doCallback(callback, oneway, delayed, value);
228 }
229
Steven Moreland5553ac42020-11-11 02:14:45 +0000230 Status die(bool cleanup) override {
231 if (cleanup) {
232 exit(1);
233 } else {
234 _exit(1);
235 }
236 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000237
238 Status scheduleShutdown() override {
239 sp<RpcServer> strongServer = server.promote();
240 if (strongServer == nullptr) {
241 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
242 }
243 std::thread([=] {
244 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
245 }).detach();
246 return Status::ok();
247 }
248
Steven Morelandd7302072021-05-15 01:32:04 +0000249 Status useKernelBinderCallingId() override {
250 // this is WRONG! It does not make sense when using RPC binder, and
251 // because it is SO wrong, and so much code calls this, it should abort!
252
253 (void)IPCThreadState::self()->getCallingPid();
254 return Status::ok();
255 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000256};
257sp<IBinder> MyBinderRpcTest::mHeldBinder;
258
259class Process {
260public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700261 Process(Process&&) = default;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700262 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */)>& f) {
263 android::base::unique_fd writeEnd;
264 CHECK(android::base::Pipe(&mReadEnd, &writeEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000265 if (0 == (mPid = fork())) {
266 // racey: assume parent doesn't crash before this is set
267 prctl(PR_SET_PDEATHSIG, SIGHUP);
268
Yifan Hong0f58fb92021-06-16 16:09:23 -0700269 f(writeEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000270
271 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000272 }
273 }
274 ~Process() {
275 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000276 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000277 }
278 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700279 android::base::borrowed_fd readEnd() { return mReadEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000280
281private:
282 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700283 android::base::unique_fd mReadEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000284};
285
286static std::string allocateSocketAddress() {
287 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000288 std::string temp = getenv("TMPDIR") ?: "/tmp";
289 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000290};
291
Steven Morelandda573042021-06-12 01:13:45 +0000292static unsigned int allocateVsockPort() {
293 static unsigned int vsockPort = 3456;
294 return vsockPort++;
295}
296
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000297struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000298 // reference to process hosting a socket server
299 Process host;
300
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000301 struct SessionInfo {
302 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000303 sp<IBinder> root;
304 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000305
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000306 // client session objects associated with other process
307 // each one represents a separate session
308 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000309
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000310 ProcessSession(ProcessSession&&) = default;
311 ~ProcessSession() {
312 for (auto& session : sessions) {
313 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000314 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000315
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000316 for (auto& info : sessions) {
317 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000318
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000319 EXPECT_NE(nullptr, session);
320 EXPECT_NE(nullptr, session->state());
321 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000322
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000323 wp<RpcSession> weakSession = session;
324 session = nullptr;
325 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000326 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000327 }
328};
329
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000330// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000331// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000332struct BinderRpcTestProcessSession {
333 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000334
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000335 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000336 sp<IBinder> rootBinder;
337
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000338 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000339 sp<IBinderRpcTest> rootIface;
340
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000341 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000342 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000343
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000344 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
345 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000346 EXPECT_NE(nullptr, rootIface);
347 if (rootIface == nullptr) return;
348
Steven Morelandaf4ca712021-05-24 23:22:08 +0000349 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000350 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000351 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000352 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000353 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000354 for (auto remoteCount : remoteCounts) {
355 EXPECT_EQ(remoteCount, 1);
356 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000357
Steven Moreland798e0d12021-07-14 23:19:25 +0000358 // even though it is on another thread, shutdown races with
359 // the transaction reply being written
360 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
361 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
362 }
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 Morelandda573042021-06-12 01:13:45 +0000388
Steven Morelandc1635952021-04-01 16:20:47 +0000389class BinderRpc : public ::testing::TestWithParam<SocketType> {
390public:
391 // This creates a new process serving an interface on a certain number of
392 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000393 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland659416d2021-05-11 00:47:50 +0000394 size_t numThreads, size_t numSessions, size_t numReverseConnections,
Steven Moreland736664b2021-05-01 04:27:25 +0000395 const std::function<void(const sp<RpcServer>&)>& configure) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000396 CHECK_GE(numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000397
Steven Morelandc1635952021-04-01 16:20:47 +0000398 SocketType socketType = GetParam();
399
Steven Morelandda573042021-06-12 01:13:45 +0000400 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000401 std::string addr = allocateSocketAddress();
402 unlink(addr.c_str());
Steven Morelandc1635952021-04-01 16:20:47 +0000403
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000404 auto ret = ProcessSession{
Yifan Hong0f58fb92021-06-16 16:09:23 -0700405 .host = Process([&](android::base::borrowed_fd writeEnd) {
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
Yifan Hong0f58fb92021-06-16 16:09:23 -0700429 CHECK(android::base::WriteFully(writeEnd, &outPort, sizeof(outPort)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000430
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;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700442 CHECK(android::base::ReadFully(ret.host.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 Moreland52eee942021-06-03 00:59:28 +0000879 constexpr size_t kNumCalls = 500;
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 Morelandd45be622021-06-04 02:19:37 +0000944TEST_P(BinderRpc, OnewayCallExhaustion) {
945 constexpr size_t kNumClients = 2;
946 constexpr size_t kTooLongMs = 1000;
947
948 auto proc = createRpcTestSocketServerProcess(kNumClients /*threads*/, 2 /*sessions*/);
949
950 // Build up oneway calls on the second session to make sure it terminates
951 // and shuts down. The first session should be unaffected (proc destructor
952 // checks the first session).
953 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
954
955 std::vector<std::thread> threads;
956 for (size_t i = 0; i < kNumClients; i++) {
957 // one of these threads will get stuck queueing a transaction once the
958 // socket fills up, the other will be able to fill up transactions on
959 // this object
960 threads.push_back(std::thread([&] {
961 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
962 }
963 }));
964 }
965 for (auto& t : threads) t.join();
966
967 Status status = iface->sleepMsAsync(kTooLongMs);
968 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
969
Steven Moreland798e0d12021-07-14 23:19:25 +0000970 // now that it has died, wait for the remote session to shutdown
971 std::vector<int32_t> remoteCounts;
972 do {
973 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
974 } while (remoteCounts.size() == kNumClients);
975
Steven Morelandd45be622021-06-04 02:19:37 +0000976 // 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
Steven Moreland798e0d12021-07-14 23:19:25 +00001015 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1016 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1017 }
Steven Moreland659416d2021-05-11 00:47:50 +00001018
Steven Morelandc7d40132021-06-10 03:42:11 +00001019 // since this session has a reverse connection w/ a threadpool, we
1020 // need to manually shut it down
1021 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001022
Steven Morelandc7d40132021-06-10 03:42:11 +00001023 proc.expectAlreadyShutdown = true;
1024 }
Steven Moreland659416d2021-05-11 00:47:50 +00001025 }
1026 }
1027}
1028
Steven Moreland195edb82021-06-08 02:44:39 +00001029TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
1030 auto proc = createRpcTestSocketServerProcess(1);
1031 auto cb = sp<MyBinderRpcCallback>::make();
1032
1033 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1034 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1035}
1036
Steven Morelandc1635952021-04-01 16:20:47 +00001037TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001038 for (bool doDeathCleanup : {true, false}) {
1039 auto proc = createRpcTestSocketServerProcess(1);
1040
1041 // make sure there is some state during crash
1042 // 1. we hold their binder
1043 sp<IBinderRpcSession> session;
1044 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1045 // 2. they hold our binder
1046 sp<IBinder> binder = new BBinder();
1047 EXPECT_OK(proc.rootIface->holdBinder(binder));
1048
1049 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1050 << "Do death cleanup: " << doDeathCleanup;
1051
Steven Morelandaf4ca712021-05-24 23:22:08 +00001052 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001053 }
1054}
1055
Steven Morelandd7302072021-05-15 01:32:04 +00001056TEST_P(BinderRpc, UseKernelBinderCallingId) {
1057 auto proc = createRpcTestSocketServerProcess(1);
1058
1059 // we can't allocate IPCThreadState so actually the first time should
1060 // succeed :(
1061 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1062
1063 // second time! we catch the error :)
1064 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1065
Steven Morelandaf4ca712021-05-24 23:22:08 +00001066 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001067}
1068
Steven Moreland37aff182021-03-26 02:04:16 +00001069TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
1070 auto proc = createRpcTestSocketServerProcess(1);
1071
1072 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1073 ASSERT_NE(binder, nullptr);
1074
1075 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1076}
1077
1078TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
1079 auto proc = createRpcTestSocketServerProcess(1);
1080
1081 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1082 ASSERT_NE(binder, nullptr);
1083
1084 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1085 ASSERT_NE(ndkBinder, nullptr);
1086
1087 std::string out;
1088 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1089 ASSERT_TRUE(status.isOk()) << status.getDescription();
1090 ASSERT_EQ("aoeuaoeu", out);
1091}
1092
Steven Moreland5553ac42020-11-11 02:14:45 +00001093ssize_t countFds() {
1094 DIR* dir = opendir("/proc/self/fd/");
1095 if (dir == nullptr) return -1;
1096 ssize_t ret = 0;
1097 dirent* ent;
1098 while ((ent = readdir(dir)) != nullptr) ret++;
1099 closedir(dir);
1100 return ret;
1101}
1102
Steven Morelandc1635952021-04-01 16:20:47 +00001103TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001104 ssize_t beforeFds = countFds();
1105 ASSERT_GE(beforeFds, 0);
1106 {
1107 auto proc = createRpcTestSocketServerProcess(10);
1108 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1109 }
1110 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1111}
1112
Steven Morelandda573042021-06-12 01:13:45 +00001113static bool testSupportVsockLoopback() {
1114 unsigned int vsockPort = allocateVsockPort();
1115 sp<RpcServer> server = RpcServer::make();
1116 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1117 CHECK(server->setupVsockServer(vsockPort));
1118 server->start();
1119
1120 sp<RpcSession> session = RpcSession::make();
1121 bool okay = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001122 while (!server->shutdown()) usleep(10000);
Steven Morelandda573042021-06-12 01:13:45 +00001123 ALOGE("Detected vsock loopback supported: %d", okay);
1124 return okay;
1125}
1126
1127static std::vector<SocketType> testSocketTypes() {
1128 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1129
1130 static bool hasVsockLoopback = testSupportVsockLoopback();
1131
1132 if (hasVsockLoopback) {
1133 ret.push_back(SocketType::VSOCK);
1134 }
1135
1136 return ret;
1137}
1138
1139INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc, ::testing::ValuesIn(testSocketTypes()),
Steven Morelandf6ec4632021-04-01 16:20:47 +00001140 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +00001141
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001142class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
1143
1144TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1145 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1146 auto setRootObject = [](bool isStrong) -> SetFn {
1147 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1148 };
1149
1150 auto server = RpcServer::make();
1151 auto [isStrong1, isStrong2] = GetParam();
1152 auto binder1 = sp<BBinder>::make();
1153 IBinder* binderRaw1 = binder1.get();
1154 setRootObject(isStrong1)(server.get(), binder1);
1155 EXPECT_EQ(binderRaw1, server->getRootObject());
1156 binder1.clear();
1157 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1158
1159 auto binder2 = sp<BBinder>::make();
1160 IBinder* binderRaw2 = binder2.get();
1161 setRootObject(isStrong2)(server.get(), binder2);
1162 EXPECT_EQ(binderRaw2, server->getRootObject());
1163 binder2.clear();
1164 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1165}
1166
1167INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
1168 ::testing::Combine(::testing::Bool(), ::testing::Bool()));
1169
Yifan Hong1a235852021-05-13 16:07:47 -07001170class OneOffSignal {
1171public:
1172 // If notify() was previously called, or is called within |duration|, return true; else false.
1173 template <typename R, typename P>
1174 bool wait(std::chrono::duration<R, P> duration) {
1175 std::unique_lock<std::mutex> lock(mMutex);
1176 return mCv.wait_for(lock, duration, [this] { return mValue; });
1177 }
1178 void notify() {
1179 std::unique_lock<std::mutex> lock(mMutex);
1180 mValue = true;
1181 lock.unlock();
1182 mCv.notify_all();
1183 }
1184
1185private:
1186 std::mutex mMutex;
1187 std::condition_variable mCv;
1188 bool mValue = false;
1189};
1190
1191TEST(BinderRpc, Shutdown) {
1192 auto addr = allocateSocketAddress();
1193 unlink(addr.c_str());
1194 auto server = RpcServer::make();
1195 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1196 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1197 auto joinEnds = std::make_shared<OneOffSignal>();
1198
1199 // If things are broken and the thread never stops, don't block other tests. Because the thread
1200 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1201 // shared pointers are passed.
1202 std::thread([server, joinEnds] {
1203 server->join();
1204 joinEnds->notify();
1205 }).detach();
1206
1207 bool shutdown = false;
1208 for (int i = 0; i < 10 && !shutdown; i++) {
1209 usleep(300 * 1000); // 300ms; total 3s
1210 if (server->shutdown()) shutdown = true;
1211 }
1212 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1213
1214 ASSERT_TRUE(joinEnds->wait(2s))
1215 << "After server->shutdown() returns true, join() did not stop after 2s";
1216}
1217
Yifan Hong0f9c5c72021-06-29 18:44:56 -07001218TEST(BinderRpc, Java) {
1219#if !defined(__ANDROID__)
1220 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1221 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1222 "to binderHostDeviceTest. Hence, just disable this test on host.";
1223#endif // !__ANDROID__
1224 sp<IServiceManager> sm = defaultServiceManager();
1225 ASSERT_NE(nullptr, sm);
1226 // Any Java service with non-empty getInterfaceDescriptor() would do.
1227 // Let's pick batteryproperties.
1228 auto binder = sm->checkService(String16("batteryproperties"));
1229 ASSERT_NE(nullptr, binder);
1230 auto descriptor = binder->getInterfaceDescriptor();
1231 ASSERT_GE(descriptor.size(), 0);
1232 ASSERT_EQ(OK, binder->pingBinder());
1233
1234 auto rpcServer = RpcServer::make();
1235 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1236 unsigned int port;
1237 ASSERT_TRUE(rpcServer->setupInetServer(0, &port));
1238 auto socket = rpcServer->releaseServer();
1239
1240 auto keepAlive = sp<BBinder>::make();
1241 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1242
1243 auto rpcSession = RpcSession::make();
1244 ASSERT_TRUE(rpcSession->setupInetClient("127.0.0.1", port));
1245 auto rpcBinder = rpcSession->getRootObject();
1246 ASSERT_NE(nullptr, rpcBinder);
1247
1248 ASSERT_EQ(OK, rpcBinder->pingBinder());
1249
1250 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1251 << "getInterfaceDescriptor should not crash system_server";
1252 ASSERT_EQ(OK, rpcBinder->pingBinder());
1253}
1254
Steven Morelandc1635952021-04-01 16:20:47 +00001255} // namespace android
1256
1257int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001258 ::testing::InitGoogleTest(&argc, argv);
1259 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1260 return RUN_ALL_TESTS();
1261}