blob: e1cf18d4c36d1bfdc3e9fd61d68424dd6937b51e [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 Moreland1b304292021-07-15 22:59:34 +0000394 size_t numThreads, size_t numSessions, size_t numIncomingConnections,
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 Moreland1b304292021-07-15 22:59:34 +0000449 session->setMaxThreads(numIncomingConnections);
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 Moreland1b304292021-07-15 22:59:34 +0000471 BinderRpcTestProcessSession createRpcTestSocketServerProcess(
472 size_t numThreads, size_t numSessions = 1, size_t numIncomingConnections = 0) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000473 BinderRpcTestProcessSession ret{
474 .proc = createRpcTestSocketServerProcess(numThreads, numSessions,
Steven Moreland1b304292021-07-15 22:59:34 +0000475 numIncomingConnections,
Steven Moreland611d15f2021-05-01 01:28:27 +0000476 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000477 sp<MyBinderRpcTest> service =
478 new MyBinderRpcTest;
479 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000480 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000481 }),
482 };
483
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000484 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000485 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
486
487 return ret;
488 }
489};
490
Steven Morelandc1635952021-04-01 16:20:47 +0000491TEST_P(BinderRpc, Ping) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000492 auto proc = createRpcTestSocketServerProcess(1);
493 ASSERT_NE(proc.rootBinder, nullptr);
494 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
495}
496
Steven Moreland4cf688f2021-03-31 01:48:58 +0000497TEST_P(BinderRpc, GetInterfaceDescriptor) {
498 auto proc = createRpcTestSocketServerProcess(1);
499 ASSERT_NE(proc.rootBinder, nullptr);
500 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
501}
502
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000503TEST_P(BinderRpc, MultipleSessions) {
504 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 5 /*sessions*/);
505 for (auto session : proc.proc.sessions) {
506 ASSERT_NE(nullptr, session.root);
507 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000508 }
509}
510
Steven Morelandc1635952021-04-01 16:20:47 +0000511TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000512 auto proc = createRpcTestSocketServerProcess(1);
513 Parcel data;
514 Parcel reply;
515 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
516}
517
Steven Moreland67753c32021-04-02 18:45:19 +0000518TEST_P(BinderRpc, AppendSeparateFormats) {
519 auto proc = createRpcTestSocketServerProcess(1);
520
521 Parcel p1;
522 p1.markForBinder(proc.rootBinder);
523 p1.writeInt32(3);
524
525 Parcel p2;
526
527 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
528 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
529}
530
Steven Morelandc1635952021-04-01 16:20:47 +0000531TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000532 auto proc = createRpcTestSocketServerProcess(1);
533 Parcel data;
534 data.markForBinder(proc.rootBinder);
535 Parcel reply;
536 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
537}
538
Steven Morelandc1635952021-04-01 16:20:47 +0000539TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000540 auto proc = createRpcTestSocketServerProcess(1);
541 EXPECT_OK(proc.rootIface->sendString("asdf"));
542}
543
Steven Morelandc1635952021-04-01 16:20:47 +0000544TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000545 auto proc = createRpcTestSocketServerProcess(1);
546 std::string doubled;
547 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
548 EXPECT_EQ("cool cool ", doubled);
549}
550
Steven Morelandc1635952021-04-01 16:20:47 +0000551TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000552 auto proc = createRpcTestSocketServerProcess(1);
553 std::string single = std::string(1024, 'a');
554 std::string doubled;
555 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
556 EXPECT_EQ(single + single, doubled);
557}
558
Steven Morelandc1635952021-04-01 16:20:47 +0000559TEST_P(BinderRpc, CallMeBack) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000560 auto proc = createRpcTestSocketServerProcess(1);
561
562 int32_t pingResult;
563 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
564 EXPECT_EQ(OK, pingResult);
565
566 EXPECT_EQ(0, MyBinderRpcSession::gNum);
567}
568
Steven Morelandc1635952021-04-01 16:20:47 +0000569TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000570 auto proc = createRpcTestSocketServerProcess(1);
571
572 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
573 sp<IBinder> outBinder;
574 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
575 EXPECT_EQ(inBinder, outBinder);
576
577 wp<IBinder> weak = inBinder;
578 inBinder = nullptr;
579 outBinder = nullptr;
580
581 // Force reading a reply, to process any pending dec refs from the other
582 // process (the other process will process dec refs there before processing
583 // the ping here).
584 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
585
586 EXPECT_EQ(nullptr, weak.promote());
587
588 EXPECT_EQ(0, MyBinderRpcSession::gNum);
589}
590
Steven Morelandc1635952021-04-01 16:20:47 +0000591TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000592 auto proc = createRpcTestSocketServerProcess(1);
593
594 sp<IBinderRpcSession> session;
595 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
596
597 sp<IBinder> inBinder = IInterface::asBinder(session);
598 sp<IBinder> outBinder;
599 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
600 EXPECT_EQ(inBinder, outBinder);
601
602 wp<IBinder> weak = inBinder;
603 session = nullptr;
604 inBinder = nullptr;
605 outBinder = nullptr;
606
607 // Force reading a reply, to process any pending dec refs from the other
608 // process (the other process will process dec refs there before processing
609 // the ping here).
610 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
611
612 EXPECT_EQ(nullptr, weak.promote());
613}
614
Steven Morelandc1635952021-04-01 16:20:47 +0000615TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000616 auto proc = createRpcTestSocketServerProcess(1);
617
618 sp<IBinder> outBinder;
619 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
620 EXPECT_EQ(nullptr, outBinder);
621}
622
Steven Morelandc1635952021-04-01 16:20:47 +0000623TEST_P(BinderRpc, HoldBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000624 auto proc = createRpcTestSocketServerProcess(1);
625
626 IBinder* ptr = nullptr;
627 {
628 sp<IBinder> binder = new BBinder();
629 ptr = binder.get();
630 EXPECT_OK(proc.rootIface->holdBinder(binder));
631 }
632
633 sp<IBinder> held;
634 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
635
636 EXPECT_EQ(held.get(), ptr);
637
638 // stop holding binder, because we test to make sure references are cleaned
639 // up
640 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
641 // and flush ref counts
642 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
643}
644
645// START TESTS FOR LIMITATIONS OF SOCKET BINDER
646// These are behavioral differences form regular binder, where certain usecases
647// aren't supported.
648
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000649TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000650 auto proc1 = createRpcTestSocketServerProcess(1);
651 auto proc2 = createRpcTestSocketServerProcess(1);
652
653 sp<IBinder> outBinder;
654 EXPECT_EQ(INVALID_OPERATION,
655 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
656}
657
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000658TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
659 auto proc = createRpcTestSocketServerProcess(1 /*threads*/, 2 /*sessions*/);
Steven Moreland736664b2021-05-01 04:27:25 +0000660
661 sp<IBinder> outBinder;
662 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000663 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000664 .transactionError());
665}
666
Steven Morelandc1635952021-04-01 16:20:47 +0000667TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000668 auto proc = createRpcTestSocketServerProcess(1);
669
670 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
671 sp<IBinder> outBinder;
672 EXPECT_EQ(INVALID_OPERATION,
673 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
674}
675
Steven Morelandc1635952021-04-01 16:20:47 +0000676TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000677 auto proc = createRpcTestSocketServerProcess(1);
678
679 // for historical reasons, IServiceManager interface only returns the
680 // exception code
681 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
682 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
683}
684
685// END TESTS FOR LIMITATIONS OF SOCKET BINDER
686
Steven Morelandc1635952021-04-01 16:20:47 +0000687TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000688 auto proc = createRpcTestSocketServerProcess(1);
689
690 sp<IBinder> outBinder;
691 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
692 EXPECT_EQ(proc.rootBinder, outBinder);
693}
694
Steven Morelandc1635952021-04-01 16:20:47 +0000695TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000696 auto proc = createRpcTestSocketServerProcess(1);
697
698 auto nastyNester = sp<MyBinderRpcTest>::make();
699 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
700
701 wp<IBinder> weak = nastyNester;
702 nastyNester = nullptr;
703 EXPECT_EQ(nullptr, weak.promote());
704}
705
Steven Morelandc1635952021-04-01 16:20:47 +0000706TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000707 auto proc = createRpcTestSocketServerProcess(1);
708
709 sp<IBinder> a;
710 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
711
712 sp<IBinder> b;
713 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
714
715 EXPECT_EQ(a, b);
716}
717
Steven Morelandc1635952021-04-01 16:20:47 +0000718TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000719 auto proc = createRpcTestSocketServerProcess(1);
720
721 sp<IBinder> a;
722 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
723 wp<IBinder> weak = a;
724 a = nullptr;
725
726 sp<IBinder> b;
727 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
728
729 // this is the wrong behavior, since BpBinder
730 // doesn't implement onIncStrongAttempted
731 // but make sure there is no crash
732 EXPECT_EQ(nullptr, weak.promote());
733
734 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
735
736 // In order to fix this:
737 // - need to have incStrongAttempted reflected across IPC boundary (wait for
738 // response to promote - round trip...)
739 // - sendOnLastWeakRef, to delete entries out of RpcState table
740 EXPECT_EQ(b, weak.promote());
741}
742
743#define expectSessions(expected, iface) \
744 do { \
745 int session; \
746 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
747 EXPECT_EQ(expected, session); \
748 } while (false)
749
Steven Morelandc1635952021-04-01 16:20:47 +0000750TEST_P(BinderRpc, SingleSession) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000751 auto proc = createRpcTestSocketServerProcess(1);
752
753 sp<IBinderRpcSession> session;
754 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
755 std::string out;
756 EXPECT_OK(session->getName(&out));
757 EXPECT_EQ("aoeu", out);
758
759 expectSessions(1, proc.rootIface);
760 session = nullptr;
761 expectSessions(0, proc.rootIface);
762}
763
Steven Morelandc1635952021-04-01 16:20:47 +0000764TEST_P(BinderRpc, ManySessions) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000765 auto proc = createRpcTestSocketServerProcess(1);
766
767 std::vector<sp<IBinderRpcSession>> sessions;
768
769 for (size_t i = 0; i < 15; i++) {
770 expectSessions(i, proc.rootIface);
771 sp<IBinderRpcSession> session;
772 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
773 sessions.push_back(session);
774 }
775 expectSessions(sessions.size(), proc.rootIface);
776 for (size_t i = 0; i < sessions.size(); i++) {
777 std::string out;
778 EXPECT_OK(sessions.at(i)->getName(&out));
779 EXPECT_EQ(std::to_string(i), out);
780 }
781 expectSessions(sessions.size(), proc.rootIface);
782
783 while (!sessions.empty()) {
784 sessions.pop_back();
785 expectSessions(sessions.size(), proc.rootIface);
786 }
787 expectSessions(0, proc.rootIface);
788}
789
790size_t epochMillis() {
791 using std::chrono::duration_cast;
792 using std::chrono::milliseconds;
793 using std::chrono::seconds;
794 using std::chrono::system_clock;
795 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
796}
797
Steven Morelandc1635952021-04-01 16:20:47 +0000798TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000799 constexpr size_t kNumThreads = 10;
800
801 auto proc = createRpcTestSocketServerProcess(kNumThreads);
802
803 EXPECT_OK(proc.rootIface->lock());
804
805 // block all but one thread taking locks
806 std::vector<std::thread> ts;
807 for (size_t i = 0; i < kNumThreads - 1; i++) {
808 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
809 }
810
811 usleep(100000); // give chance for calls on other threads
812
813 // other calls still work
814 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
815
816 constexpr size_t blockTimeMs = 500;
817 size_t epochMsBefore = epochMillis();
818 // after this, we should never see a response within this time
819 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
820
821 // this call should be blocked for blockTimeMs
822 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
823
824 size_t epochMsAfter = epochMillis();
825 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
826
827 for (auto& t : ts) t.join();
828}
829
Steven Morelandc1635952021-04-01 16:20:47 +0000830TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000831 constexpr size_t kNumThreads = 10;
832 constexpr size_t kNumCalls = kNumThreads + 3;
833 constexpr size_t kSleepMs = 500;
834
835 auto proc = createRpcTestSocketServerProcess(kNumThreads);
836
837 size_t epochMsBefore = epochMillis();
838
839 std::vector<std::thread> ts;
840 for (size_t i = 0; i < kNumCalls; i++) {
841 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
842 }
843
844 for (auto& t : ts) t.join();
845
846 size_t epochMsAfter = epochMillis();
847
848 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
849
850 // Potential flake, but make sure calls are handled in parallel.
851 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
852}
853
Steven Morelandc1635952021-04-01 16:20:47 +0000854TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000855 constexpr size_t kNumClientThreads = 10;
856 constexpr size_t kNumServerThreads = 10;
857 constexpr size_t kNumCalls = 100;
858
859 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
860
861 std::vector<std::thread> threads;
862 for (size_t i = 0; i < kNumClientThreads; i++) {
863 threads.push_back(std::thread([&] {
864 for (size_t j = 0; j < kNumCalls; j++) {
865 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000866 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000867 EXPECT_EQ(proc.rootBinder, out);
868 }
869 }));
870 }
871
872 for (auto& t : threads) t.join();
873}
874
Steven Morelandc6046982021-04-20 00:49:42 +0000875TEST_P(BinderRpc, OnewayStressTest) {
876 constexpr size_t kNumClientThreads = 10;
877 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000878 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000879
880 auto proc = createRpcTestSocketServerProcess(kNumServerThreads);
881
882 std::vector<std::thread> threads;
883 for (size_t i = 0; i < kNumClientThreads; i++) {
884 threads.push_back(std::thread([&] {
885 for (size_t j = 0; j < kNumCalls; j++) {
886 EXPECT_OK(proc.rootIface->sendString("a"));
887 }
888
889 // check threads are not stuck
890 EXPECT_OK(proc.rootIface->sleepMs(250));
891 }));
892 }
893
894 for (auto& t : threads) t.join();
895}
896
Steven Morelandc1635952021-04-01 16:20:47 +0000897TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000898 constexpr size_t kReallyLongTimeMs = 100;
899 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
900
Steven Morelandf5174272021-05-25 00:39:28 +0000901 auto proc = createRpcTestSocketServerProcess(1);
Steven Moreland5553ac42020-11-11 02:14:45 +0000902
903 size_t epochMsBefore = epochMillis();
904
905 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
906
907 size_t epochMsAfter = epochMillis();
908 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
909}
910
Steven Morelandc1635952021-04-01 16:20:47 +0000911TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000912 constexpr size_t kNumSleeps = 10;
913 constexpr size_t kNumExtraServerThreads = 4;
914 constexpr size_t kSleepMs = 50;
915
916 // make sure calls to the same object happen on the same thread
917 auto proc = createRpcTestSocketServerProcess(1 + kNumExtraServerThreads);
918
919 EXPECT_OK(proc.rootIface->lock());
920
921 for (size_t i = 0; i < kNumSleeps; i++) {
922 // these should be processed serially
923 proc.rootIface->sleepMsAsync(kSleepMs);
924 }
925 // should also be processesed serially
926 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
927
928 size_t epochMsBefore = epochMillis();
929 EXPECT_OK(proc.rootIface->lockUnlock());
930 size_t epochMsAfter = epochMillis();
931
932 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000933
934 // pending oneway transactions hold ref, make sure we read data on all
935 // sockets
936 std::vector<std::thread> threads;
937 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
938 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
939 }
940 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +0000941}
942
Steven Morelandd45be622021-06-04 02:19:37 +0000943TEST_P(BinderRpc, OnewayCallExhaustion) {
944 constexpr size_t kNumClients = 2;
945 constexpr size_t kTooLongMs = 1000;
946
947 auto proc = createRpcTestSocketServerProcess(kNumClients /*threads*/, 2 /*sessions*/);
948
949 // Build up oneway calls on the second session to make sure it terminates
950 // and shuts down. The first session should be unaffected (proc destructor
951 // checks the first session).
952 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
953
954 std::vector<std::thread> threads;
955 for (size_t i = 0; i < kNumClients; i++) {
956 // one of these threads will get stuck queueing a transaction once the
957 // socket fills up, the other will be able to fill up transactions on
958 // this object
959 threads.push_back(std::thread([&] {
960 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
961 }
962 }));
963 }
964 for (auto& t : threads) t.join();
965
966 Status status = iface->sleepMsAsync(kTooLongMs);
967 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
968
Steven Moreland798e0d12021-07-14 23:19:25 +0000969 // now that it has died, wait for the remote session to shutdown
970 std::vector<int32_t> remoteCounts;
971 do {
972 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
973 } while (remoteCounts.size() == kNumClients);
974
Steven Morelandd45be622021-06-04 02:19:37 +0000975 // the second session should be shutdown in the other process by the time we
976 // are able to join above (it'll only be hung up once it finishes processing
977 // any pending commands). We need to erase this session from the record
978 // here, so that the destructor for our session won't check that this
979 // session is valid, but we still want it to test the other session.
980 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
981}
982
Steven Moreland659416d2021-05-11 00:47:50 +0000983TEST_P(BinderRpc, Callbacks) {
984 const static std::string kTestString = "good afternoon!";
985
Steven Morelandc7d40132021-06-10 03:42:11 +0000986 for (bool callIsOneway : {true, false}) {
987 for (bool callbackIsOneway : {true, false}) {
988 for (bool delayed : {true, false}) {
989 auto proc = createRpcTestSocketServerProcess(1, 1, 1);
990 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +0000991
Steven Morelandc7d40132021-06-10 03:42:11 +0000992 if (callIsOneway) {
993 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
994 kTestString));
995 } else {
996 EXPECT_OK(
997 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
998 }
Steven Moreland659416d2021-05-11 00:47:50 +0000999
Steven Morelandc7d40132021-06-10 03:42:11 +00001000 using std::literals::chrono_literals::operator""s;
1001 std::unique_lock<std::mutex> _l(cb->mMutex);
1002 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001003
Steven Morelandc7d40132021-06-10 03:42:11 +00001004 EXPECT_EQ(cb->mValues.size(), 1)
1005 << "callIsOneway: " << callIsOneway
1006 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1007 if (cb->mValues.empty()) continue;
1008 EXPECT_EQ(cb->mValues.at(0), kTestString)
1009 << "callIsOneway: " << callIsOneway
1010 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001011
Steven Morelandc7d40132021-06-10 03:42:11 +00001012 // since we are severing the connection, we need to go ahead and
1013 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001014 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1015 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1016 }
Steven Moreland659416d2021-05-11 00:47:50 +00001017
Steven Moreland1b304292021-07-15 22:59:34 +00001018 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001019 // need to manually shut it down
1020 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001021
Steven Morelandc7d40132021-06-10 03:42:11 +00001022 proc.expectAlreadyShutdown = true;
1023 }
Steven Moreland659416d2021-05-11 00:47:50 +00001024 }
1025 }
1026}
1027
Steven Moreland195edb82021-06-08 02:44:39 +00001028TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
1029 auto proc = createRpcTestSocketServerProcess(1);
1030 auto cb = sp<MyBinderRpcCallback>::make();
1031
1032 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1033 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1034}
1035
Steven Morelandc1635952021-04-01 16:20:47 +00001036TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001037 for (bool doDeathCleanup : {true, false}) {
1038 auto proc = createRpcTestSocketServerProcess(1);
1039
1040 // make sure there is some state during crash
1041 // 1. we hold their binder
1042 sp<IBinderRpcSession> session;
1043 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1044 // 2. they hold our binder
1045 sp<IBinder> binder = new BBinder();
1046 EXPECT_OK(proc.rootIface->holdBinder(binder));
1047
1048 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1049 << "Do death cleanup: " << doDeathCleanup;
1050
Steven Morelandaf4ca712021-05-24 23:22:08 +00001051 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001052 }
1053}
1054
Steven Morelandd7302072021-05-15 01:32:04 +00001055TEST_P(BinderRpc, UseKernelBinderCallingId) {
1056 auto proc = createRpcTestSocketServerProcess(1);
1057
1058 // we can't allocate IPCThreadState so actually the first time should
1059 // succeed :(
1060 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1061
1062 // second time! we catch the error :)
1063 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1064
Steven Morelandaf4ca712021-05-24 23:22:08 +00001065 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001066}
1067
Steven Moreland37aff182021-03-26 02:04:16 +00001068TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
1069 auto proc = createRpcTestSocketServerProcess(1);
1070
1071 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1072 ASSERT_NE(binder, nullptr);
1073
1074 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1075}
1076
1077TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
1078 auto proc = createRpcTestSocketServerProcess(1);
1079
1080 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1081 ASSERT_NE(binder, nullptr);
1082
1083 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1084 ASSERT_NE(ndkBinder, nullptr);
1085
1086 std::string out;
1087 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1088 ASSERT_TRUE(status.isOk()) << status.getDescription();
1089 ASSERT_EQ("aoeuaoeu", out);
1090}
1091
Steven Moreland5553ac42020-11-11 02:14:45 +00001092ssize_t countFds() {
1093 DIR* dir = opendir("/proc/self/fd/");
1094 if (dir == nullptr) return -1;
1095 ssize_t ret = 0;
1096 dirent* ent;
1097 while ((ent = readdir(dir)) != nullptr) ret++;
1098 closedir(dir);
1099 return ret;
1100}
1101
Steven Morelandc1635952021-04-01 16:20:47 +00001102TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001103 ssize_t beforeFds = countFds();
1104 ASSERT_GE(beforeFds, 0);
1105 {
1106 auto proc = createRpcTestSocketServerProcess(10);
1107 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1108 }
1109 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1110}
1111
Steven Morelandda573042021-06-12 01:13:45 +00001112static bool testSupportVsockLoopback() {
1113 unsigned int vsockPort = allocateVsockPort();
1114 sp<RpcServer> server = RpcServer::make();
1115 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1116 CHECK(server->setupVsockServer(vsockPort));
1117 server->start();
1118
1119 sp<RpcSession> session = RpcSession::make();
1120 bool okay = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001121 while (!server->shutdown()) usleep(10000);
Steven Morelandda573042021-06-12 01:13:45 +00001122 ALOGE("Detected vsock loopback supported: %d", okay);
1123 return okay;
1124}
1125
1126static std::vector<SocketType> testSocketTypes() {
1127 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1128
1129 static bool hasVsockLoopback = testSupportVsockLoopback();
1130
1131 if (hasVsockLoopback) {
1132 ret.push_back(SocketType::VSOCK);
1133 }
1134
1135 return ret;
1136}
1137
1138INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc, ::testing::ValuesIn(testSocketTypes()),
Steven Morelandf6ec4632021-04-01 16:20:47 +00001139 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +00001140
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001141class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
1142
1143TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1144 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1145 auto setRootObject = [](bool isStrong) -> SetFn {
1146 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1147 };
1148
1149 auto server = RpcServer::make();
1150 auto [isStrong1, isStrong2] = GetParam();
1151 auto binder1 = sp<BBinder>::make();
1152 IBinder* binderRaw1 = binder1.get();
1153 setRootObject(isStrong1)(server.get(), binder1);
1154 EXPECT_EQ(binderRaw1, server->getRootObject());
1155 binder1.clear();
1156 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1157
1158 auto binder2 = sp<BBinder>::make();
1159 IBinder* binderRaw2 = binder2.get();
1160 setRootObject(isStrong2)(server.get(), binder2);
1161 EXPECT_EQ(binderRaw2, server->getRootObject());
1162 binder2.clear();
1163 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1164}
1165
1166INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
1167 ::testing::Combine(::testing::Bool(), ::testing::Bool()));
1168
Yifan Hong1a235852021-05-13 16:07:47 -07001169class OneOffSignal {
1170public:
1171 // If notify() was previously called, or is called within |duration|, return true; else false.
1172 template <typename R, typename P>
1173 bool wait(std::chrono::duration<R, P> duration) {
1174 std::unique_lock<std::mutex> lock(mMutex);
1175 return mCv.wait_for(lock, duration, [this] { return mValue; });
1176 }
1177 void notify() {
1178 std::unique_lock<std::mutex> lock(mMutex);
1179 mValue = true;
1180 lock.unlock();
1181 mCv.notify_all();
1182 }
1183
1184private:
1185 std::mutex mMutex;
1186 std::condition_variable mCv;
1187 bool mValue = false;
1188};
1189
1190TEST(BinderRpc, Shutdown) {
1191 auto addr = allocateSocketAddress();
1192 unlink(addr.c_str());
1193 auto server = RpcServer::make();
1194 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1195 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1196 auto joinEnds = std::make_shared<OneOffSignal>();
1197
1198 // If things are broken and the thread never stops, don't block other tests. Because the thread
1199 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1200 // shared pointers are passed.
1201 std::thread([server, joinEnds] {
1202 server->join();
1203 joinEnds->notify();
1204 }).detach();
1205
1206 bool shutdown = false;
1207 for (int i = 0; i < 10 && !shutdown; i++) {
1208 usleep(300 * 1000); // 300ms; total 3s
1209 if (server->shutdown()) shutdown = true;
1210 }
1211 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1212
1213 ASSERT_TRUE(joinEnds->wait(2s))
1214 << "After server->shutdown() returns true, join() did not stop after 2s";
1215}
1216
Yifan Hong0f9c5c72021-06-29 18:44:56 -07001217TEST(BinderRpc, Java) {
1218#if !defined(__ANDROID__)
1219 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1220 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1221 "to binderHostDeviceTest. Hence, just disable this test on host.";
1222#endif // !__ANDROID__
1223 sp<IServiceManager> sm = defaultServiceManager();
1224 ASSERT_NE(nullptr, sm);
1225 // Any Java service with non-empty getInterfaceDescriptor() would do.
1226 // Let's pick batteryproperties.
1227 auto binder = sm->checkService(String16("batteryproperties"));
1228 ASSERT_NE(nullptr, binder);
1229 auto descriptor = binder->getInterfaceDescriptor();
1230 ASSERT_GE(descriptor.size(), 0);
1231 ASSERT_EQ(OK, binder->pingBinder());
1232
1233 auto rpcServer = RpcServer::make();
1234 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1235 unsigned int port;
1236 ASSERT_TRUE(rpcServer->setupInetServer(0, &port));
1237 auto socket = rpcServer->releaseServer();
1238
1239 auto keepAlive = sp<BBinder>::make();
1240 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1241
1242 auto rpcSession = RpcSession::make();
1243 ASSERT_TRUE(rpcSession->setupInetClient("127.0.0.1", port));
1244 auto rpcBinder = rpcSession->getRootObject();
1245 ASSERT_NE(nullptr, rpcBinder);
1246
1247 ASSERT_EQ(OK, rpcBinder->pingBinder());
1248
1249 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1250 << "getInterfaceDescriptor should not crash system_server";
1251 ASSERT_EQ(OK, rpcBinder->pingBinder());
1252}
1253
Steven Morelandc1635952021-04-01 16:20:47 +00001254} // namespace android
1255
1256int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001257 ::testing::InitGoogleTest(&argc, argv);
1258 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1259 return RUN_ALL_TESTS();
1260}