blob: 40ebd9c8bcdce0c60f5729bcb456f4182d86add5 [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:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000391 struct Options {
392 size_t numThreads = 1;
393 size_t numSessions = 1;
394 size_t numIncomingConnections = 0;
395 };
396
Steven Morelandc1635952021-04-01 16:20:47 +0000397 // This creates a new process serving an interface on a certain number of
398 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000399 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000400 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
401 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000402
Steven Morelandc1635952021-04-01 16:20:47 +0000403 SocketType socketType = GetParam();
404
Steven Morelandda573042021-06-12 01:13:45 +0000405 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000406 std::string addr = allocateSocketAddress();
407 unlink(addr.c_str());
Steven Morelandc1635952021-04-01 16:20:47 +0000408
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409 auto ret = ProcessSession{
Yifan Hong0f58fb92021-06-16 16:09:23 -0700410 .host = Process([&](android::base::borrowed_fd writeEnd) {
Steven Morelandc1635952021-04-01 16:20:47 +0000411 sp<RpcServer> server = RpcServer::make();
412
413 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000414 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000415
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000416 unsigned int outPort = 0;
417
Steven Morelandc1635952021-04-01 16:20:47 +0000418 switch (socketType) {
419 case SocketType::UNIX:
Steven Moreland611d15f2021-05-01 01:28:27 +0000420 CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000421 break;
422 case SocketType::VSOCK:
Steven Moreland611d15f2021-05-01 01:28:27 +0000423 CHECK(server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000424 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700425 case SocketType::INET: {
Steven Moreland611d15f2021-05-01 01:28:27 +0000426 CHECK(server->setupInetServer(0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700427 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700428 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700429 }
Steven Morelandc1635952021-04-01 16:20:47 +0000430 default:
431 LOG_ALWAYS_FATAL("Unknown socket type");
432 }
433
Yifan Hong0f58fb92021-06-16 16:09:23 -0700434 CHECK(android::base::WriteFully(writeEnd, &outPort, sizeof(outPort)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000435
Steven Moreland611d15f2021-05-01 01:28:27 +0000436 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000437
Steven Morelandf137de92021-04-24 01:54:26 +0000438 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000439
440 // Another thread calls shutdown. Wait for it to complete.
441 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000442 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000443 };
444
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000445 // always read socket, so that we have waited for the server to start
446 unsigned int outPort = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700447 CHECK(android::base::ReadFully(ret.host.readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700448 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000449 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700450 }
451
Steven Moreland4313d7e2021-07-15 23:41:22 +0000452 for (size_t i = 0; i < options.numSessions; i++) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000453 sp<RpcSession> session = RpcSession::make();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000454 session->setMaxThreads(options.numIncomingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000455
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000456 switch (socketType) {
457 case SocketType::UNIX:
458 if (session->setupUnixDomainClient(addr.c_str())) goto success;
459 break;
460 case SocketType::VSOCK:
461 if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
462 break;
463 case SocketType::INET:
464 if (session->setupInetClient("127.0.0.1", outPort)) goto success;
465 break;
466 default:
467 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000468 }
Steven Moreland736664b2021-05-01 04:27:25 +0000469 LOG_ALWAYS_FATAL("Could not connect");
470 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000471 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000472 }
Steven Morelandc1635952021-04-01 16:20:47 +0000473 return ret;
474 }
475
Steven Moreland4313d7e2021-07-15 23:41:22 +0000476 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000477 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000478 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000479 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000480 sp<MyBinderRpcTest> service =
481 new MyBinderRpcTest;
482 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000483 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000484 }),
485 };
486
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000487 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000488 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
489
490 return ret;
491 }
492};
493
Steven Morelandc1635952021-04-01 16:20:47 +0000494TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000495 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000496 ASSERT_NE(proc.rootBinder, nullptr);
497 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
498}
499
Steven Moreland4cf688f2021-03-31 01:48:58 +0000500TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000501 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000502 ASSERT_NE(proc.rootBinder, nullptr);
503 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
504}
505
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000506TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000507 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000508 for (auto session : proc.proc.sessions) {
509 ASSERT_NE(nullptr, session.root);
510 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000511 }
512}
513
Steven Morelandc1635952021-04-01 16:20:47 +0000514TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000515 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000516 Parcel data;
517 Parcel reply;
518 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
519}
520
Steven Moreland67753c32021-04-02 18:45:19 +0000521TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000522 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000523
524 Parcel p1;
525 p1.markForBinder(proc.rootBinder);
526 p1.writeInt32(3);
527
528 Parcel p2;
529
530 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
531 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
532}
533
Steven Morelandc1635952021-04-01 16:20:47 +0000534TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000535 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000536 Parcel data;
537 data.markForBinder(proc.rootBinder);
538 Parcel reply;
539 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
540}
541
Steven Morelandc1635952021-04-01 16:20:47 +0000542TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000543 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000544 EXPECT_OK(proc.rootIface->sendString("asdf"));
545}
546
Steven Morelandc1635952021-04-01 16:20:47 +0000547TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000548 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000549 std::string doubled;
550 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
551 EXPECT_EQ("cool cool ", doubled);
552}
553
Steven Morelandc1635952021-04-01 16:20:47 +0000554TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000555 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000556 std::string single = std::string(1024, 'a');
557 std::string doubled;
558 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
559 EXPECT_EQ(single + single, doubled);
560}
561
Steven Morelandc1635952021-04-01 16:20:47 +0000562TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000563 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000564
565 int32_t pingResult;
566 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
567 EXPECT_EQ(OK, pingResult);
568
569 EXPECT_EQ(0, MyBinderRpcSession::gNum);
570}
571
Steven Morelandc1635952021-04-01 16:20:47 +0000572TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000573 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000574
575 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
576 sp<IBinder> outBinder;
577 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
578 EXPECT_EQ(inBinder, outBinder);
579
580 wp<IBinder> weak = inBinder;
581 inBinder = nullptr;
582 outBinder = nullptr;
583
584 // Force reading a reply, to process any pending dec refs from the other
585 // process (the other process will process dec refs there before processing
586 // the ping here).
587 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
588
589 EXPECT_EQ(nullptr, weak.promote());
590
591 EXPECT_EQ(0, MyBinderRpcSession::gNum);
592}
593
Steven Morelandc1635952021-04-01 16:20:47 +0000594TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000595 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000596
597 sp<IBinderRpcSession> session;
598 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
599
600 sp<IBinder> inBinder = IInterface::asBinder(session);
601 sp<IBinder> outBinder;
602 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
603 EXPECT_EQ(inBinder, outBinder);
604
605 wp<IBinder> weak = inBinder;
606 session = nullptr;
607 inBinder = nullptr;
608 outBinder = nullptr;
609
610 // Force reading a reply, to process any pending dec refs from the other
611 // process (the other process will process dec refs there before processing
612 // the ping here).
613 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
614
615 EXPECT_EQ(nullptr, weak.promote());
616}
617
Steven Morelandc1635952021-04-01 16:20:47 +0000618TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000619 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000620
621 sp<IBinder> outBinder;
622 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
623 EXPECT_EQ(nullptr, outBinder);
624}
625
Steven Morelandc1635952021-04-01 16:20:47 +0000626TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000627 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000628
629 IBinder* ptr = nullptr;
630 {
631 sp<IBinder> binder = new BBinder();
632 ptr = binder.get();
633 EXPECT_OK(proc.rootIface->holdBinder(binder));
634 }
635
636 sp<IBinder> held;
637 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
638
639 EXPECT_EQ(held.get(), ptr);
640
641 // stop holding binder, because we test to make sure references are cleaned
642 // up
643 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
644 // and flush ref counts
645 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
646}
647
648// START TESTS FOR LIMITATIONS OF SOCKET BINDER
649// These are behavioral differences form regular binder, where certain usecases
650// aren't supported.
651
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000652TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000653 auto proc1 = createRpcTestSocketServerProcess({});
654 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000655
656 sp<IBinder> outBinder;
657 EXPECT_EQ(INVALID_OPERATION,
658 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
659}
660
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000661TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000662 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000663
664 sp<IBinder> outBinder;
665 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000666 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000667 .transactionError());
668}
669
Steven Morelandc1635952021-04-01 16:20:47 +0000670TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000671 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000672
673 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
674 sp<IBinder> outBinder;
675 EXPECT_EQ(INVALID_OPERATION,
676 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
677}
678
Steven Morelandc1635952021-04-01 16:20:47 +0000679TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000680 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000681
682 // for historical reasons, IServiceManager interface only returns the
683 // exception code
684 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
685 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
686}
687
688// END TESTS FOR LIMITATIONS OF SOCKET BINDER
689
Steven Morelandc1635952021-04-01 16:20:47 +0000690TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000691 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000692
693 sp<IBinder> outBinder;
694 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
695 EXPECT_EQ(proc.rootBinder, outBinder);
696}
697
Steven Morelandc1635952021-04-01 16:20:47 +0000698TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000699 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000700
701 auto nastyNester = sp<MyBinderRpcTest>::make();
702 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
703
704 wp<IBinder> weak = nastyNester;
705 nastyNester = nullptr;
706 EXPECT_EQ(nullptr, weak.promote());
707}
708
Steven Morelandc1635952021-04-01 16:20:47 +0000709TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000710 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000711
712 sp<IBinder> a;
713 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
714
715 sp<IBinder> b;
716 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
717
718 EXPECT_EQ(a, b);
719}
720
Steven Morelandc1635952021-04-01 16:20:47 +0000721TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000722 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000723
724 sp<IBinder> a;
725 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
726 wp<IBinder> weak = a;
727 a = nullptr;
728
729 sp<IBinder> b;
730 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
731
732 // this is the wrong behavior, since BpBinder
733 // doesn't implement onIncStrongAttempted
734 // but make sure there is no crash
735 EXPECT_EQ(nullptr, weak.promote());
736
737 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
738
739 // In order to fix this:
740 // - need to have incStrongAttempted reflected across IPC boundary (wait for
741 // response to promote - round trip...)
742 // - sendOnLastWeakRef, to delete entries out of RpcState table
743 EXPECT_EQ(b, weak.promote());
744}
745
746#define expectSessions(expected, iface) \
747 do { \
748 int session; \
749 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
750 EXPECT_EQ(expected, session); \
751 } while (false)
752
Steven Morelandc1635952021-04-01 16:20:47 +0000753TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000754 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000755
756 sp<IBinderRpcSession> session;
757 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
758 std::string out;
759 EXPECT_OK(session->getName(&out));
760 EXPECT_EQ("aoeu", out);
761
762 expectSessions(1, proc.rootIface);
763 session = nullptr;
764 expectSessions(0, proc.rootIface);
765}
766
Steven Morelandc1635952021-04-01 16:20:47 +0000767TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000768 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000769
770 std::vector<sp<IBinderRpcSession>> sessions;
771
772 for (size_t i = 0; i < 15; i++) {
773 expectSessions(i, proc.rootIface);
774 sp<IBinderRpcSession> session;
775 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
776 sessions.push_back(session);
777 }
778 expectSessions(sessions.size(), proc.rootIface);
779 for (size_t i = 0; i < sessions.size(); i++) {
780 std::string out;
781 EXPECT_OK(sessions.at(i)->getName(&out));
782 EXPECT_EQ(std::to_string(i), out);
783 }
784 expectSessions(sessions.size(), proc.rootIface);
785
786 while (!sessions.empty()) {
787 sessions.pop_back();
788 expectSessions(sessions.size(), proc.rootIface);
789 }
790 expectSessions(0, proc.rootIface);
791}
792
793size_t epochMillis() {
794 using std::chrono::duration_cast;
795 using std::chrono::milliseconds;
796 using std::chrono::seconds;
797 using std::chrono::system_clock;
798 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
799}
800
Steven Morelandc1635952021-04-01 16:20:47 +0000801TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000802 constexpr size_t kNumThreads = 10;
803
Steven Moreland4313d7e2021-07-15 23:41:22 +0000804 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000805
806 EXPECT_OK(proc.rootIface->lock());
807
808 // block all but one thread taking locks
809 std::vector<std::thread> ts;
810 for (size_t i = 0; i < kNumThreads - 1; i++) {
811 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
812 }
813
814 usleep(100000); // give chance for calls on other threads
815
816 // other calls still work
817 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
818
819 constexpr size_t blockTimeMs = 500;
820 size_t epochMsBefore = epochMillis();
821 // after this, we should never see a response within this time
822 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
823
824 // this call should be blocked for blockTimeMs
825 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
826
827 size_t epochMsAfter = epochMillis();
828 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
829
830 for (auto& t : ts) t.join();
831}
832
Steven Morelandc1635952021-04-01 16:20:47 +0000833TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000834 constexpr size_t kNumThreads = 10;
835 constexpr size_t kNumCalls = kNumThreads + 3;
836 constexpr size_t kSleepMs = 500;
837
Steven Moreland4313d7e2021-07-15 23:41:22 +0000838 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000839
840 size_t epochMsBefore = epochMillis();
841
842 std::vector<std::thread> ts;
843 for (size_t i = 0; i < kNumCalls; i++) {
844 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
845 }
846
847 for (auto& t : ts) t.join();
848
849 size_t epochMsAfter = epochMillis();
850
851 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
852
853 // Potential flake, but make sure calls are handled in parallel.
854 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
855}
856
Steven Morelandc1635952021-04-01 16:20:47 +0000857TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000858 constexpr size_t kNumClientThreads = 10;
859 constexpr size_t kNumServerThreads = 10;
860 constexpr size_t kNumCalls = 100;
861
Steven Moreland4313d7e2021-07-15 23:41:22 +0000862 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000863
864 std::vector<std::thread> threads;
865 for (size_t i = 0; i < kNumClientThreads; i++) {
866 threads.push_back(std::thread([&] {
867 for (size_t j = 0; j < kNumCalls; j++) {
868 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000869 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000870 EXPECT_EQ(proc.rootBinder, out);
871 }
872 }));
873 }
874
875 for (auto& t : threads) t.join();
876}
877
Steven Morelandc6046982021-04-20 00:49:42 +0000878TEST_P(BinderRpc, OnewayStressTest) {
879 constexpr size_t kNumClientThreads = 10;
880 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000881 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000882
Steven Moreland4313d7e2021-07-15 23:41:22 +0000883 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000884
885 std::vector<std::thread> threads;
886 for (size_t i = 0; i < kNumClientThreads; i++) {
887 threads.push_back(std::thread([&] {
888 for (size_t j = 0; j < kNumCalls; j++) {
889 EXPECT_OK(proc.rootIface->sendString("a"));
890 }
891
892 // check threads are not stuck
893 EXPECT_OK(proc.rootIface->sleepMs(250));
894 }));
895 }
896
897 for (auto& t : threads) t.join();
898}
899
Steven Morelandc1635952021-04-01 16:20:47 +0000900TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000901 constexpr size_t kReallyLongTimeMs = 100;
902 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
903
Steven Moreland4313d7e2021-07-15 23:41:22 +0000904 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000905
906 size_t epochMsBefore = epochMillis();
907
908 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
909
910 size_t epochMsAfter = epochMillis();
911 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
912}
913
Steven Morelandc1635952021-04-01 16:20:47 +0000914TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000915 constexpr size_t kNumSleeps = 10;
916 constexpr size_t kNumExtraServerThreads = 4;
917 constexpr size_t kSleepMs = 50;
918
919 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000920 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000921
922 EXPECT_OK(proc.rootIface->lock());
923
924 for (size_t i = 0; i < kNumSleeps; i++) {
925 // these should be processed serially
926 proc.rootIface->sleepMsAsync(kSleepMs);
927 }
928 // should also be processesed serially
929 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
930
931 size_t epochMsBefore = epochMillis();
932 EXPECT_OK(proc.rootIface->lockUnlock());
933 size_t epochMsAfter = epochMillis();
934
935 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000936
937 // pending oneway transactions hold ref, make sure we read data on all
938 // sockets
939 std::vector<std::thread> threads;
940 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
941 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
942 }
943 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +0000944}
945
Steven Morelandd45be622021-06-04 02:19:37 +0000946TEST_P(BinderRpc, OnewayCallExhaustion) {
947 constexpr size_t kNumClients = 2;
948 constexpr size_t kTooLongMs = 1000;
949
Steven Moreland4313d7e2021-07-15 23:41:22 +0000950 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000951
952 // Build up oneway calls on the second session to make sure it terminates
953 // and shuts down. The first session should be unaffected (proc destructor
954 // checks the first session).
955 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
956
957 std::vector<std::thread> threads;
958 for (size_t i = 0; i < kNumClients; i++) {
959 // one of these threads will get stuck queueing a transaction once the
960 // socket fills up, the other will be able to fill up transactions on
961 // this object
962 threads.push_back(std::thread([&] {
963 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
964 }
965 }));
966 }
967 for (auto& t : threads) t.join();
968
969 Status status = iface->sleepMsAsync(kTooLongMs);
970 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
971
Steven Moreland798e0d12021-07-14 23:19:25 +0000972 // now that it has died, wait for the remote session to shutdown
973 std::vector<int32_t> remoteCounts;
974 do {
975 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
976 } while (remoteCounts.size() == kNumClients);
977
Steven Morelandd45be622021-06-04 02:19:37 +0000978 // the second session should be shutdown in the other process by the time we
979 // are able to join above (it'll only be hung up once it finishes processing
980 // any pending commands). We need to erase this session from the record
981 // here, so that the destructor for our session won't check that this
982 // session is valid, but we still want it to test the other session.
983 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
984}
985
Steven Moreland659416d2021-05-11 00:47:50 +0000986TEST_P(BinderRpc, Callbacks) {
987 const static std::string kTestString = "good afternoon!";
988
Steven Morelandc7d40132021-06-10 03:42:11 +0000989 for (bool callIsOneway : {true, false}) {
990 for (bool callbackIsOneway : {true, false}) {
991 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000992 auto proc = createRpcTestSocketServerProcess(
993 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +0000994 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +0000995
Steven Morelandc7d40132021-06-10 03:42:11 +0000996 if (callIsOneway) {
997 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
998 kTestString));
999 } else {
1000 EXPECT_OK(
1001 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1002 }
Steven Moreland659416d2021-05-11 00:47:50 +00001003
Steven Morelandc7d40132021-06-10 03:42:11 +00001004 using std::literals::chrono_literals::operator""s;
1005 std::unique_lock<std::mutex> _l(cb->mMutex);
1006 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001007
Steven Morelandc7d40132021-06-10 03:42:11 +00001008 EXPECT_EQ(cb->mValues.size(), 1)
1009 << "callIsOneway: " << callIsOneway
1010 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1011 if (cb->mValues.empty()) continue;
1012 EXPECT_EQ(cb->mValues.at(0), kTestString)
1013 << "callIsOneway: " << callIsOneway
1014 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001015
Steven Morelandc7d40132021-06-10 03:42:11 +00001016 // since we are severing the connection, we need to go ahead and
1017 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001018 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1019 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1020 }
Steven Moreland659416d2021-05-11 00:47:50 +00001021
Steven Moreland1b304292021-07-15 22:59:34 +00001022 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001023 // need to manually shut it down
1024 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001025
Steven Morelandc7d40132021-06-10 03:42:11 +00001026 proc.expectAlreadyShutdown = true;
1027 }
Steven Moreland659416d2021-05-11 00:47:50 +00001028 }
1029 }
1030}
1031
Steven Moreland195edb82021-06-08 02:44:39 +00001032TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001033 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001034 auto cb = sp<MyBinderRpcCallback>::make();
1035
1036 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1037 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1038}
1039
Steven Morelandc1635952021-04-01 16:20:47 +00001040TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001041 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001042 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001043
1044 // make sure there is some state during crash
1045 // 1. we hold their binder
1046 sp<IBinderRpcSession> session;
1047 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1048 // 2. they hold our binder
1049 sp<IBinder> binder = new BBinder();
1050 EXPECT_OK(proc.rootIface->holdBinder(binder));
1051
1052 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1053 << "Do death cleanup: " << doDeathCleanup;
1054
Steven Morelandaf4ca712021-05-24 23:22:08 +00001055 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001056 }
1057}
1058
Steven Morelandd7302072021-05-15 01:32:04 +00001059TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001060 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001061
1062 // we can't allocate IPCThreadState so actually the first time should
1063 // succeed :(
1064 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1065
1066 // second time! we catch the error :)
1067 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1068
Steven Morelandaf4ca712021-05-24 23:22:08 +00001069 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001070}
1071
Steven Moreland37aff182021-03-26 02:04:16 +00001072TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001073 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001074
1075 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1076 ASSERT_NE(binder, nullptr);
1077
1078 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1079}
1080
1081TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001082 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001083
1084 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1085 ASSERT_NE(binder, nullptr);
1086
1087 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1088 ASSERT_NE(ndkBinder, nullptr);
1089
1090 std::string out;
1091 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1092 ASSERT_TRUE(status.isOk()) << status.getDescription();
1093 ASSERT_EQ("aoeuaoeu", out);
1094}
1095
Steven Moreland5553ac42020-11-11 02:14:45 +00001096ssize_t countFds() {
1097 DIR* dir = opendir("/proc/self/fd/");
1098 if (dir == nullptr) return -1;
1099 ssize_t ret = 0;
1100 dirent* ent;
1101 while ((ent = readdir(dir)) != nullptr) ret++;
1102 closedir(dir);
1103 return ret;
1104}
1105
Steven Morelandc1635952021-04-01 16:20:47 +00001106TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001107 ssize_t beforeFds = countFds();
1108 ASSERT_GE(beforeFds, 0);
1109 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001110 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001111 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1112 }
1113 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1114}
1115
Steven Morelandda573042021-06-12 01:13:45 +00001116static bool testSupportVsockLoopback() {
1117 unsigned int vsockPort = allocateVsockPort();
1118 sp<RpcServer> server = RpcServer::make();
1119 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1120 CHECK(server->setupVsockServer(vsockPort));
1121 server->start();
1122
1123 sp<RpcSession> session = RpcSession::make();
1124 bool okay = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001125 while (!server->shutdown()) usleep(10000);
Steven Morelandda573042021-06-12 01:13:45 +00001126 ALOGE("Detected vsock loopback supported: %d", okay);
1127 return okay;
1128}
1129
1130static std::vector<SocketType> testSocketTypes() {
1131 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1132
1133 static bool hasVsockLoopback = testSupportVsockLoopback();
1134
1135 if (hasVsockLoopback) {
1136 ret.push_back(SocketType::VSOCK);
1137 }
1138
1139 return ret;
1140}
1141
1142INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc, ::testing::ValuesIn(testSocketTypes()),
Steven Morelandf6ec4632021-04-01 16:20:47 +00001143 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +00001144
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001145class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
1146
1147TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1148 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1149 auto setRootObject = [](bool isStrong) -> SetFn {
1150 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1151 };
1152
1153 auto server = RpcServer::make();
1154 auto [isStrong1, isStrong2] = GetParam();
1155 auto binder1 = sp<BBinder>::make();
1156 IBinder* binderRaw1 = binder1.get();
1157 setRootObject(isStrong1)(server.get(), binder1);
1158 EXPECT_EQ(binderRaw1, server->getRootObject());
1159 binder1.clear();
1160 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1161
1162 auto binder2 = sp<BBinder>::make();
1163 IBinder* binderRaw2 = binder2.get();
1164 setRootObject(isStrong2)(server.get(), binder2);
1165 EXPECT_EQ(binderRaw2, server->getRootObject());
1166 binder2.clear();
1167 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1168}
1169
1170INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
1171 ::testing::Combine(::testing::Bool(), ::testing::Bool()));
1172
Yifan Hong1a235852021-05-13 16:07:47 -07001173class OneOffSignal {
1174public:
1175 // If notify() was previously called, or is called within |duration|, return true; else false.
1176 template <typename R, typename P>
1177 bool wait(std::chrono::duration<R, P> duration) {
1178 std::unique_lock<std::mutex> lock(mMutex);
1179 return mCv.wait_for(lock, duration, [this] { return mValue; });
1180 }
1181 void notify() {
1182 std::unique_lock<std::mutex> lock(mMutex);
1183 mValue = true;
1184 lock.unlock();
1185 mCv.notify_all();
1186 }
1187
1188private:
1189 std::mutex mMutex;
1190 std::condition_variable mCv;
1191 bool mValue = false;
1192};
1193
1194TEST(BinderRpc, Shutdown) {
1195 auto addr = allocateSocketAddress();
1196 unlink(addr.c_str());
1197 auto server = RpcServer::make();
1198 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1199 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1200 auto joinEnds = std::make_shared<OneOffSignal>();
1201
1202 // If things are broken and the thread never stops, don't block other tests. Because the thread
1203 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1204 // shared pointers are passed.
1205 std::thread([server, joinEnds] {
1206 server->join();
1207 joinEnds->notify();
1208 }).detach();
1209
1210 bool shutdown = false;
1211 for (int i = 0; i < 10 && !shutdown; i++) {
1212 usleep(300 * 1000); // 300ms; total 3s
1213 if (server->shutdown()) shutdown = true;
1214 }
1215 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1216
1217 ASSERT_TRUE(joinEnds->wait(2s))
1218 << "After server->shutdown() returns true, join() did not stop after 2s";
1219}
1220
Yifan Hong0f9c5c72021-06-29 18:44:56 -07001221TEST(BinderRpc, Java) {
1222#if !defined(__ANDROID__)
1223 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1224 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1225 "to binderHostDeviceTest. Hence, just disable this test on host.";
1226#endif // !__ANDROID__
1227 sp<IServiceManager> sm = defaultServiceManager();
1228 ASSERT_NE(nullptr, sm);
1229 // Any Java service with non-empty getInterfaceDescriptor() would do.
1230 // Let's pick batteryproperties.
1231 auto binder = sm->checkService(String16("batteryproperties"));
1232 ASSERT_NE(nullptr, binder);
1233 auto descriptor = binder->getInterfaceDescriptor();
1234 ASSERT_GE(descriptor.size(), 0);
1235 ASSERT_EQ(OK, binder->pingBinder());
1236
1237 auto rpcServer = RpcServer::make();
1238 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1239 unsigned int port;
1240 ASSERT_TRUE(rpcServer->setupInetServer(0, &port));
1241 auto socket = rpcServer->releaseServer();
1242
1243 auto keepAlive = sp<BBinder>::make();
1244 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1245
1246 auto rpcSession = RpcSession::make();
1247 ASSERT_TRUE(rpcSession->setupInetClient("127.0.0.1", port));
1248 auto rpcBinder = rpcSession->getRootObject();
1249 ASSERT_NE(nullptr, rpcBinder);
1250
1251 ASSERT_EQ(OK, rpcBinder->pingBinder());
1252
1253 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1254 << "getInterfaceDescriptor should not crash system_server";
1255 ASSERT_EQ(OK, rpcBinder->pingBinder());
1256}
1257
Steven Morelandc1635952021-04-01 16:20:47 +00001258} // namespace android
1259
1260int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001261 ::testing::InitGoogleTest(&argc, argv);
1262 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1263 return RUN_ALL_TESTS();
1264}