blob: 6dd4019ae834299fdf00d3347739c617831e3d5f [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>
Yifan Hong702115c2021-06-24 15:39:18 -070032#include <binder/RpcTransport.h>
33#include <binder/RpcTransportRaw.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000034#include <gtest/gtest.h>
35
Steven Morelandc1635952021-04-01 16:20:47 +000036#include <chrono>
37#include <cstdlib>
38#include <iostream>
39#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000040#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000041
Steven Morelandc1635952021-04-01 16:20:47 +000042#include <sys/prctl.h>
43#include <unistd.h>
44
Steven Moreland4198a122021-08-03 17:37:58 -070045#include "../RpcSocketAddress.h" // for testing preconnected clients
Steven Morelandbd5002b2021-05-04 23:12:56 +000046#include "../RpcState.h" // for debugging
47#include "../vm_sockets.h" // for VMADDR_*
Steven Moreland5553ac42020-11-11 02:14:45 +000048
Yifan Hong1a235852021-05-13 16:07:47 -070049using namespace std::chrono_literals;
50
Steven Moreland5553ac42020-11-11 02:14:45 +000051namespace android {
52
Steven Morelandbf57bce2021-07-26 15:26:12 -070053static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
54 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Devin Mooref3b9c4f2021-08-03 15:50:13 +000055const char* kLocalInetAddress = "127.0.0.1";
Steven Morelandbf57bce2021-07-26 15:26:12 -070056
Yifan Hong702115c2021-06-24 15:39:18 -070057enum class RpcSecurity { RAW };
58
59static inline std::vector<RpcSecurity> RpcSecurityValues() {
60 return {RpcSecurity::RAW};
61}
62
63static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(RpcSecurity rpcSecurity) {
64 switch (rpcSecurity) {
65 case RpcSecurity::RAW:
66 return RpcTransportCtxFactoryRaw::make();
67 default:
68 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
69 }
70}
71
Steven Moreland1fda67b2021-04-02 18:35:50 +000072TEST(BinderRpcParcel, EntireParcelFormatted) {
73 Parcel p;
74 p.writeInt32(3);
75
76 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
77}
78
Yifan Hong702115c2021-06-24 15:39:18 -070079class BinderRpcSimple : public ::testing::TestWithParam<RpcSecurity> {
80public:
81 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
82 return newFactory(info.param)->toCString();
83 }
84};
85
86TEST_P(BinderRpcSimple, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -070087 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
88 int sinkFd = sink.get();
Yifan Hong702115c2021-06-24 15:39:18 -070089 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -070090 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
91 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -070092 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -070093 ASSERT_TRUE(server->hasServer());
94 base::unique_fd retrieved = server->releaseServer();
95 ASSERT_FALSE(server->hasServer());
96 ASSERT_EQ(sinkFd, retrieved.get());
97}
98
Steven Morelandbf57bce2021-07-26 15:26:12 -070099TEST(BinderRpc, CannotUseNextWireVersion) {
100 auto session = RpcSession::make();
101 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
102 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
103 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
104 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
105}
106
107TEST(BinderRpc, CanUseExperimentalWireVersion) {
108 auto session = RpcSession::make();
109 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
110}
111
Steven Moreland5553ac42020-11-11 02:14:45 +0000112using android::binder::Status;
113
114#define EXPECT_OK(status) \
115 do { \
116 Status stat = (status); \
117 EXPECT_TRUE(stat.isOk()) << stat; \
118 } while (false)
119
120class MyBinderRpcSession : public BnBinderRpcSession {
121public:
122 static std::atomic<int32_t> gNum;
123
124 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
125 Status getName(std::string* name) override {
126 *name = mName;
127 return Status::ok();
128 }
129 ~MyBinderRpcSession() { gNum--; }
130
131private:
132 std::string mName;
133};
134std::atomic<int32_t> MyBinderRpcSession::gNum;
135
Steven Moreland659416d2021-05-11 00:47:50 +0000136class MyBinderRpcCallback : public BnBinderRpcCallback {
137 Status sendCallback(const std::string& value) {
138 std::unique_lock _l(mMutex);
139 mValues.push_back(value);
140 _l.unlock();
141 mCv.notify_one();
142 return Status::ok();
143 }
144 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
145
146public:
147 std::mutex mMutex;
148 std::condition_variable mCv;
149 std::vector<std::string> mValues;
150};
151
Steven Moreland5553ac42020-11-11 02:14:45 +0000152class MyBinderRpcTest : public BnBinderRpcTest {
153public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000154 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +0000155
156 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000157 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000158 return Status::ok();
159 }
160 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000161 *strstr = str + str;
162 return Status::ok();
163 }
Steven Moreland736664b2021-05-01 04:27:25 +0000164 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000165 sp<RpcServer> spServer = server.promote();
166 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000167 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
168 }
Steven Moreland736664b2021-05-01 04:27:25 +0000169 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000170 for (auto session : spServer->listSessions()) {
171 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000172 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000173 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000174 return Status::ok();
175 }
176 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
177 if (binder == nullptr) {
178 std::cout << "Received null binder!" << std::endl;
179 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
180 }
181 *out = binder->pingBinder();
182 return Status::ok();
183 }
184 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
185 *out = binder;
186 return Status::ok();
187 }
188 static sp<IBinder> mHeldBinder;
189 Status holdBinder(const sp<IBinder>& binder) override {
190 mHeldBinder = binder;
191 return Status::ok();
192 }
193 Status getHeldBinder(sp<IBinder>* held) override {
194 *held = mHeldBinder;
195 return Status::ok();
196 }
197 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
198 if (count <= 0) return Status::ok();
199 return binder->nestMe(this, count - 1);
200 }
201 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
202 static sp<IBinder> binder = new BBinder;
203 *out = binder;
204 return Status::ok();
205 }
206 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
207 *out = new MyBinderRpcSession(name);
208 return Status::ok();
209 }
210 Status getNumOpenSessions(int32_t* out) override {
211 *out = MyBinderRpcSession::gNum;
212 return Status::ok();
213 }
214
215 std::mutex blockMutex;
216 Status lock() override {
217 blockMutex.lock();
218 return Status::ok();
219 }
220 Status unlockInMsAsync(int32_t ms) override {
221 usleep(ms * 1000);
222 blockMutex.unlock();
223 return Status::ok();
224 }
225 Status lockUnlock() override {
226 std::lock_guard<std::mutex> _l(blockMutex);
227 return Status::ok();
228 }
229
230 Status sleepMs(int32_t ms) override {
231 usleep(ms * 1000);
232 return Status::ok();
233 }
234
235 Status sleepMsAsync(int32_t ms) override {
236 // In-process binder calls are asynchronous, but the call to this method
237 // is synchronous wrt its client. This in/out-process threading model
238 // diffentiation is a classic binder leaky abstraction (for better or
239 // worse) and is preserved here the way binder sockets plugs itself
240 // into BpBinder, as nothing is changed at the higher levels
241 // (IInterface) which result in this behavior.
242 return sleepMs(ms);
243 }
244
Steven Moreland659416d2021-05-11 00:47:50 +0000245 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
246 const std::string& value) override {
247 if (callback == nullptr) {
248 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
249 }
250
251 if (delayed) {
252 std::thread([=]() {
253 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000254 Status status = doCallback(callback, oneway, false, value);
255 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000256 }).detach();
257 return Status::ok();
258 }
259
260 if (oneway) {
261 return callback->sendOnewayCallback(value);
262 }
263
264 return callback->sendCallback(value);
265 }
266
Steven Morelandc7d40132021-06-10 03:42:11 +0000267 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
268 const std::string& value) override {
269 return doCallback(callback, oneway, delayed, value);
270 }
271
Steven Moreland5553ac42020-11-11 02:14:45 +0000272 Status die(bool cleanup) override {
273 if (cleanup) {
274 exit(1);
275 } else {
276 _exit(1);
277 }
278 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000279
280 Status scheduleShutdown() override {
281 sp<RpcServer> strongServer = server.promote();
282 if (strongServer == nullptr) {
283 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
284 }
285 std::thread([=] {
286 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
287 }).detach();
288 return Status::ok();
289 }
290
Steven Morelandd7302072021-05-15 01:32:04 +0000291 Status useKernelBinderCallingId() override {
292 // this is WRONG! It does not make sense when using RPC binder, and
293 // because it is SO wrong, and so much code calls this, it should abort!
294
295 (void)IPCThreadState::self()->getCallingPid();
296 return Status::ok();
297 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000298};
299sp<IBinder> MyBinderRpcTest::mHeldBinder;
300
301class Process {
302public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700303 Process(Process&&) = default;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700304 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */)>& f) {
305 android::base::unique_fd writeEnd;
306 CHECK(android::base::Pipe(&mReadEnd, &writeEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000307 if (0 == (mPid = fork())) {
308 // racey: assume parent doesn't crash before this is set
309 prctl(PR_SET_PDEATHSIG, SIGHUP);
310
Yifan Hong0f58fb92021-06-16 16:09:23 -0700311 f(writeEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000312
313 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000314 }
315 }
316 ~Process() {
317 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000318 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000319 }
320 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700321 android::base::borrowed_fd readEnd() { return mReadEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000322
323private:
324 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700325 android::base::unique_fd mReadEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000326};
327
328static std::string allocateSocketAddress() {
329 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000330 std::string temp = getenv("TMPDIR") ?: "/tmp";
331 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000332};
333
Steven Morelandda573042021-06-12 01:13:45 +0000334static unsigned int allocateVsockPort() {
335 static unsigned int vsockPort = 3456;
336 return vsockPort++;
337}
338
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000339struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000340 // reference to process hosting a socket server
341 Process host;
342
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000343 struct SessionInfo {
344 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000345 sp<IBinder> root;
346 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000347
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000348 // client session objects associated with other process
349 // each one represents a separate session
350 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000351
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000352 ProcessSession(ProcessSession&&) = default;
353 ~ProcessSession() {
354 for (auto& session : sessions) {
355 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000356 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000357
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000358 for (auto& info : sessions) {
359 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000360
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000361 EXPECT_NE(nullptr, session);
362 EXPECT_NE(nullptr, session->state());
363 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000364
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000365 wp<RpcSession> weakSession = session;
366 session = nullptr;
367 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000368 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000369 }
370};
371
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000372// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000373// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000374struct BinderRpcTestProcessSession {
375 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000376
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000377 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000378 sp<IBinder> rootBinder;
379
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000380 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000381 sp<IBinderRpcTest> rootIface;
382
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000383 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000384 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000385
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000386 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
387 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000388 EXPECT_NE(nullptr, rootIface);
389 if (rootIface == nullptr) return;
390
Steven Morelandaf4ca712021-05-24 23:22:08 +0000391 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000392 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000393 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000394 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000396 for (auto remoteCount : remoteCounts) {
397 EXPECT_EQ(remoteCount, 1);
398 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000399
Steven Moreland798e0d12021-07-14 23:19:25 +0000400 // even though it is on another thread, shutdown races with
401 // the transaction reply being written
402 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
403 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
404 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000405 }
406
407 rootIface = nullptr;
408 rootBinder = nullptr;
409 }
410};
411
Steven Morelandc1635952021-04-01 16:20:47 +0000412enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700413 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000414 UNIX,
415 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700416 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000417};
Yifan Hong702115c2021-06-24 15:39:18 -0700418static inline std::string PrintToString(SocketType socketType) {
419 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700420 case SocketType::PRECONNECTED:
421 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000422 case SocketType::UNIX:
423 return "unix_domain_socket";
424 case SocketType::VSOCK:
425 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700426 case SocketType::INET:
427 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000428 default:
429 LOG_ALWAYS_FATAL("Unknown socket type");
430 return "";
431 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000432}
Steven Morelandda573042021-06-12 01:13:45 +0000433
Steven Moreland4198a122021-08-03 17:37:58 -0700434static base::unique_fd connectToUds(const char* addrStr) {
435 UnixSocketAddress addr(addrStr);
436 base::unique_fd serverFd(
437 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
438 int savedErrno = errno;
439 CHECK(serverFd.ok()) << "Could not create socket " << addrStr << ": " << strerror(savedErrno);
440
441 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
442 int savedErrno = errno;
443 LOG(FATAL) << "Could not connect to socket " << addrStr << ": " << strerror(savedErrno);
444 }
445 return serverFd;
446}
447
Yifan Hong702115c2021-06-24 15:39:18 -0700448class BinderRpc : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000449public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000450 struct Options {
451 size_t numThreads = 1;
452 size_t numSessions = 1;
453 size_t numIncomingConnections = 0;
454 };
455
Yifan Hong702115c2021-06-24 15:39:18 -0700456 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
457 auto [type, security] = info.param;
458 return PrintToString(type) + "_" + newFactory(security)->toCString();
459 }
460
Steven Morelandc1635952021-04-01 16:20:47 +0000461 // This creates a new process serving an interface on a certain number of
462 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000463 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000464 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
465 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000466
Yifan Hong702115c2021-06-24 15:39:18 -0700467 SocketType socketType = std::get<0>(GetParam());
468 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000469
Steven Morelandda573042021-06-12 01:13:45 +0000470 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000471 std::string addr = allocateSocketAddress();
472 unlink(addr.c_str());
Steven Morelandc1635952021-04-01 16:20:47 +0000473
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000474 auto ret = ProcessSession{
Yifan Hong0f58fb92021-06-16 16:09:23 -0700475 .host = Process([&](android::base::borrowed_fd writeEnd) {
Yifan Hong702115c2021-06-24 15:39:18 -0700476 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity));
Steven Morelandc1635952021-04-01 16:20:47 +0000477
478 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000479 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000480
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000481 unsigned int outPort = 0;
482
Steven Morelandc1635952021-04-01 16:20:47 +0000483 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700484 case SocketType::PRECONNECTED:
485 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000486 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700487 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000488 break;
489 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700490 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000491 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700492 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700493 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700494 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700495 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700496 }
Steven Morelandc1635952021-04-01 16:20:47 +0000497 default:
498 LOG_ALWAYS_FATAL("Unknown socket type");
499 }
500
Yifan Hong0f58fb92021-06-16 16:09:23 -0700501 CHECK(android::base::WriteFully(writeEnd, &outPort, sizeof(outPort)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000502
Steven Moreland611d15f2021-05-01 01:28:27 +0000503 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000504
Steven Morelandf137de92021-04-24 01:54:26 +0000505 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000506
507 // Another thread calls shutdown. Wait for it to complete.
508 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000509 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000510 };
511
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000512 // always read socket, so that we have waited for the server to start
513 unsigned int outPort = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700514 CHECK(android::base::ReadFully(ret.host.readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700515 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000516 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700517 }
518
Steven Moreland2372f9d2021-08-05 15:42:01 -0700519 status_t status;
520
Steven Moreland4313d7e2021-07-15 23:41:22 +0000521 for (size_t i = 0; i < options.numSessions; i++) {
Yifan Hong702115c2021-06-24 15:39:18 -0700522 sp<RpcSession> session = RpcSession::make(newFactory(rpcSecurity));
Steven Moreland4313d7e2021-07-15 23:41:22 +0000523 session->setMaxThreads(options.numIncomingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000524
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000525 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700526 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700527 status = session->setupPreconnectedClient({}, [=]() {
528 return connectToUds(addr.c_str());
529 });
530 if (status == OK) goto success;
Steven Moreland4198a122021-08-03 17:37:58 -0700531 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000532 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700533 status = session->setupUnixDomainClient(addr.c_str());
534 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000535 break;
536 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700537 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
538 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000539 break;
540 case SocketType::INET:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700541 status = session->setupInetClient("127.0.0.1", outPort);
542 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000543 break;
544 default:
545 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000546 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700547 LOG_ALWAYS_FATAL("Could not connect %s", statusToString(status).c_str());
Steven Moreland736664b2021-05-01 04:27:25 +0000548 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000549 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000550 }
Steven Morelandc1635952021-04-01 16:20:47 +0000551 return ret;
552 }
553
Steven Moreland4313d7e2021-07-15 23:41:22 +0000554 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000555 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000556 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000557 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000558 sp<MyBinderRpcTest> service =
559 new MyBinderRpcTest;
560 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000561 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000562 }),
563 };
564
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000565 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000566 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
567
568 return ret;
569 }
570};
571
Steven Morelandc1635952021-04-01 16:20:47 +0000572TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000573 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000574 ASSERT_NE(proc.rootBinder, nullptr);
575 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
576}
577
Steven Moreland4cf688f2021-03-31 01:48:58 +0000578TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000579 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000580 ASSERT_NE(proc.rootBinder, nullptr);
581 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
582}
583
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000584TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000585 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000586 for (auto session : proc.proc.sessions) {
587 ASSERT_NE(nullptr, session.root);
588 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000589 }
590}
591
Steven Morelandc1635952021-04-01 16:20:47 +0000592TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000593 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000594 Parcel data;
595 Parcel reply;
596 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
597}
598
Steven Moreland67753c32021-04-02 18:45:19 +0000599TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000600 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000601
602 Parcel p1;
603 p1.markForBinder(proc.rootBinder);
604 p1.writeInt32(3);
605
606 Parcel p2;
607
608 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
609 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
610}
611
Steven Morelandc1635952021-04-01 16:20:47 +0000612TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000613 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000614 Parcel data;
615 data.markForBinder(proc.rootBinder);
616 Parcel reply;
617 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
618}
619
Steven Morelandc1635952021-04-01 16:20:47 +0000620TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000621 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000622 EXPECT_OK(proc.rootIface->sendString("asdf"));
623}
624
Steven Morelandc1635952021-04-01 16:20:47 +0000625TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000626 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000627 std::string doubled;
628 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
629 EXPECT_EQ("cool cool ", doubled);
630}
631
Steven Morelandc1635952021-04-01 16:20:47 +0000632TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000633 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000634 std::string single = std::string(1024, 'a');
635 std::string doubled;
636 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
637 EXPECT_EQ(single + single, doubled);
638}
639
Steven Morelandc1635952021-04-01 16:20:47 +0000640TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000641 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000642
643 int32_t pingResult;
644 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
645 EXPECT_EQ(OK, pingResult);
646
647 EXPECT_EQ(0, MyBinderRpcSession::gNum);
648}
649
Steven Morelandc1635952021-04-01 16:20:47 +0000650TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000651 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000652
653 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
654 sp<IBinder> outBinder;
655 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
656 EXPECT_EQ(inBinder, outBinder);
657
658 wp<IBinder> weak = inBinder;
659 inBinder = nullptr;
660 outBinder = nullptr;
661
662 // Force reading a reply, to process any pending dec refs from the other
663 // process (the other process will process dec refs there before processing
664 // the ping here).
665 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
666
667 EXPECT_EQ(nullptr, weak.promote());
668
669 EXPECT_EQ(0, MyBinderRpcSession::gNum);
670}
671
Steven Morelandc1635952021-04-01 16:20:47 +0000672TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000673 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000674
675 sp<IBinderRpcSession> session;
676 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
677
678 sp<IBinder> inBinder = IInterface::asBinder(session);
679 sp<IBinder> outBinder;
680 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
681 EXPECT_EQ(inBinder, outBinder);
682
683 wp<IBinder> weak = inBinder;
684 session = nullptr;
685 inBinder = nullptr;
686 outBinder = nullptr;
687
688 // Force reading a reply, to process any pending dec refs from the other
689 // process (the other process will process dec refs there before processing
690 // the ping here).
691 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
692
693 EXPECT_EQ(nullptr, weak.promote());
694}
695
Steven Morelandc1635952021-04-01 16:20:47 +0000696TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000697 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000698
699 sp<IBinder> outBinder;
700 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
701 EXPECT_EQ(nullptr, outBinder);
702}
703
Steven Morelandc1635952021-04-01 16:20:47 +0000704TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000705 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000706
707 IBinder* ptr = nullptr;
708 {
709 sp<IBinder> binder = new BBinder();
710 ptr = binder.get();
711 EXPECT_OK(proc.rootIface->holdBinder(binder));
712 }
713
714 sp<IBinder> held;
715 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
716
717 EXPECT_EQ(held.get(), ptr);
718
719 // stop holding binder, because we test to make sure references are cleaned
720 // up
721 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
722 // and flush ref counts
723 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
724}
725
726// START TESTS FOR LIMITATIONS OF SOCKET BINDER
727// These are behavioral differences form regular binder, where certain usecases
728// aren't supported.
729
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000730TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000731 auto proc1 = createRpcTestSocketServerProcess({});
732 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000733
734 sp<IBinder> outBinder;
735 EXPECT_EQ(INVALID_OPERATION,
736 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
737}
738
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000739TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000740 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000741
742 sp<IBinder> outBinder;
743 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000744 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000745 .transactionError());
746}
747
Steven Morelandc1635952021-04-01 16:20:47 +0000748TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000749 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000750
751 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
752 sp<IBinder> outBinder;
753 EXPECT_EQ(INVALID_OPERATION,
754 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
755}
756
Steven Morelandc1635952021-04-01 16:20:47 +0000757TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000758 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000759
760 // for historical reasons, IServiceManager interface only returns the
761 // exception code
762 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
763 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
764}
765
766// END TESTS FOR LIMITATIONS OF SOCKET BINDER
767
Steven Morelandc1635952021-04-01 16:20:47 +0000768TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000769 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000770
771 sp<IBinder> outBinder;
772 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
773 EXPECT_EQ(proc.rootBinder, outBinder);
774}
775
Steven Morelandc1635952021-04-01 16:20:47 +0000776TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000777 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000778
779 auto nastyNester = sp<MyBinderRpcTest>::make();
780 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
781
782 wp<IBinder> weak = nastyNester;
783 nastyNester = nullptr;
784 EXPECT_EQ(nullptr, weak.promote());
785}
786
Steven Morelandc1635952021-04-01 16:20:47 +0000787TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000788 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000789
790 sp<IBinder> a;
791 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
792
793 sp<IBinder> b;
794 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
795
796 EXPECT_EQ(a, b);
797}
798
Steven Morelandc1635952021-04-01 16:20:47 +0000799TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000800 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000801
802 sp<IBinder> a;
803 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
804 wp<IBinder> weak = a;
805 a = nullptr;
806
807 sp<IBinder> b;
808 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
809
810 // this is the wrong behavior, since BpBinder
811 // doesn't implement onIncStrongAttempted
812 // but make sure there is no crash
813 EXPECT_EQ(nullptr, weak.promote());
814
815 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
816
817 // In order to fix this:
818 // - need to have incStrongAttempted reflected across IPC boundary (wait for
819 // response to promote - round trip...)
820 // - sendOnLastWeakRef, to delete entries out of RpcState table
821 EXPECT_EQ(b, weak.promote());
822}
823
824#define expectSessions(expected, iface) \
825 do { \
826 int session; \
827 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
828 EXPECT_EQ(expected, session); \
829 } while (false)
830
Steven Morelandc1635952021-04-01 16:20:47 +0000831TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000832 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000833
834 sp<IBinderRpcSession> session;
835 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
836 std::string out;
837 EXPECT_OK(session->getName(&out));
838 EXPECT_EQ("aoeu", out);
839
840 expectSessions(1, proc.rootIface);
841 session = nullptr;
842 expectSessions(0, proc.rootIface);
843}
844
Steven Morelandc1635952021-04-01 16:20:47 +0000845TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000846 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000847
848 std::vector<sp<IBinderRpcSession>> sessions;
849
850 for (size_t i = 0; i < 15; i++) {
851 expectSessions(i, proc.rootIface);
852 sp<IBinderRpcSession> session;
853 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
854 sessions.push_back(session);
855 }
856 expectSessions(sessions.size(), proc.rootIface);
857 for (size_t i = 0; i < sessions.size(); i++) {
858 std::string out;
859 EXPECT_OK(sessions.at(i)->getName(&out));
860 EXPECT_EQ(std::to_string(i), out);
861 }
862 expectSessions(sessions.size(), proc.rootIface);
863
864 while (!sessions.empty()) {
865 sessions.pop_back();
866 expectSessions(sessions.size(), proc.rootIface);
867 }
868 expectSessions(0, proc.rootIface);
869}
870
871size_t epochMillis() {
872 using std::chrono::duration_cast;
873 using std::chrono::milliseconds;
874 using std::chrono::seconds;
875 using std::chrono::system_clock;
876 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
877}
878
Steven Morelandc1635952021-04-01 16:20:47 +0000879TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000880 constexpr size_t kNumThreads = 10;
881
Steven Moreland4313d7e2021-07-15 23:41:22 +0000882 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000883
884 EXPECT_OK(proc.rootIface->lock());
885
886 // block all but one thread taking locks
887 std::vector<std::thread> ts;
888 for (size_t i = 0; i < kNumThreads - 1; i++) {
889 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
890 }
891
892 usleep(100000); // give chance for calls on other threads
893
894 // other calls still work
895 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
896
897 constexpr size_t blockTimeMs = 500;
898 size_t epochMsBefore = epochMillis();
899 // after this, we should never see a response within this time
900 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
901
902 // this call should be blocked for blockTimeMs
903 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
904
905 size_t epochMsAfter = epochMillis();
906 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
907
908 for (auto& t : ts) t.join();
909}
910
Steven Morelandc1635952021-04-01 16:20:47 +0000911TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000912 constexpr size_t kNumThreads = 10;
913 constexpr size_t kNumCalls = kNumThreads + 3;
914 constexpr size_t kSleepMs = 500;
915
Steven Moreland4313d7e2021-07-15 23:41:22 +0000916 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000917
918 size_t epochMsBefore = epochMillis();
919
920 std::vector<std::thread> ts;
921 for (size_t i = 0; i < kNumCalls; i++) {
922 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
923 }
924
925 for (auto& t : ts) t.join();
926
927 size_t epochMsAfter = epochMillis();
928
929 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
930
931 // Potential flake, but make sure calls are handled in parallel.
932 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
933}
934
Steven Morelandc1635952021-04-01 16:20:47 +0000935TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000936 constexpr size_t kNumClientThreads = 10;
937 constexpr size_t kNumServerThreads = 10;
938 constexpr size_t kNumCalls = 100;
939
Steven Moreland4313d7e2021-07-15 23:41:22 +0000940 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000941
942 std::vector<std::thread> threads;
943 for (size_t i = 0; i < kNumClientThreads; i++) {
944 threads.push_back(std::thread([&] {
945 for (size_t j = 0; j < kNumCalls; j++) {
946 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000947 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000948 EXPECT_EQ(proc.rootBinder, out);
949 }
950 }));
951 }
952
953 for (auto& t : threads) t.join();
954}
955
Steven Morelandc6046982021-04-20 00:49:42 +0000956TEST_P(BinderRpc, OnewayStressTest) {
957 constexpr size_t kNumClientThreads = 10;
958 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000959 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000960
Steven Moreland4313d7e2021-07-15 23:41:22 +0000961 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000962
963 std::vector<std::thread> threads;
964 for (size_t i = 0; i < kNumClientThreads; i++) {
965 threads.push_back(std::thread([&] {
966 for (size_t j = 0; j < kNumCalls; j++) {
967 EXPECT_OK(proc.rootIface->sendString("a"));
968 }
969
970 // check threads are not stuck
971 EXPECT_OK(proc.rootIface->sleepMs(250));
972 }));
973 }
974
975 for (auto& t : threads) t.join();
976}
977
Steven Morelandc1635952021-04-01 16:20:47 +0000978TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000979 constexpr size_t kReallyLongTimeMs = 100;
980 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
981
Steven Moreland4313d7e2021-07-15 23:41:22 +0000982 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000983
984 size_t epochMsBefore = epochMillis();
985
986 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
987
988 size_t epochMsAfter = epochMillis();
989 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
990}
991
Steven Morelandc1635952021-04-01 16:20:47 +0000992TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000993 constexpr size_t kNumSleeps = 10;
994 constexpr size_t kNumExtraServerThreads = 4;
995 constexpr size_t kSleepMs = 50;
996
997 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000998 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000999
1000 EXPECT_OK(proc.rootIface->lock());
1001
1002 for (size_t i = 0; i < kNumSleeps; i++) {
1003 // these should be processed serially
1004 proc.rootIface->sleepMsAsync(kSleepMs);
1005 }
1006 // should also be processesed serially
1007 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1008
1009 size_t epochMsBefore = epochMillis();
1010 EXPECT_OK(proc.rootIface->lockUnlock());
1011 size_t epochMsAfter = epochMillis();
1012
1013 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001014
1015 // pending oneway transactions hold ref, make sure we read data on all
1016 // sockets
1017 std::vector<std::thread> threads;
1018 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
1019 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
1020 }
1021 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +00001022}
1023
Steven Morelandd45be622021-06-04 02:19:37 +00001024TEST_P(BinderRpc, OnewayCallExhaustion) {
1025 constexpr size_t kNumClients = 2;
1026 constexpr size_t kTooLongMs = 1000;
1027
Steven Moreland4313d7e2021-07-15 23:41:22 +00001028 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001029
1030 // Build up oneway calls on the second session to make sure it terminates
1031 // and shuts down. The first session should be unaffected (proc destructor
1032 // checks the first session).
1033 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1034
1035 std::vector<std::thread> threads;
1036 for (size_t i = 0; i < kNumClients; i++) {
1037 // one of these threads will get stuck queueing a transaction once the
1038 // socket fills up, the other will be able to fill up transactions on
1039 // this object
1040 threads.push_back(std::thread([&] {
1041 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1042 }
1043 }));
1044 }
1045 for (auto& t : threads) t.join();
1046
1047 Status status = iface->sleepMsAsync(kTooLongMs);
1048 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1049
Steven Moreland798e0d12021-07-14 23:19:25 +00001050 // now that it has died, wait for the remote session to shutdown
1051 std::vector<int32_t> remoteCounts;
1052 do {
1053 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1054 } while (remoteCounts.size() == kNumClients);
1055
Steven Morelandd45be622021-06-04 02:19:37 +00001056 // the second session should be shutdown in the other process by the time we
1057 // are able to join above (it'll only be hung up once it finishes processing
1058 // any pending commands). We need to erase this session from the record
1059 // here, so that the destructor for our session won't check that this
1060 // session is valid, but we still want it to test the other session.
1061 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1062}
1063
Steven Moreland659416d2021-05-11 00:47:50 +00001064TEST_P(BinderRpc, Callbacks) {
1065 const static std::string kTestString = "good afternoon!";
1066
Steven Morelandc7d40132021-06-10 03:42:11 +00001067 for (bool callIsOneway : {true, false}) {
1068 for (bool callbackIsOneway : {true, false}) {
1069 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001070 auto proc = createRpcTestSocketServerProcess(
1071 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001072 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001073
Steven Morelandc7d40132021-06-10 03:42:11 +00001074 if (callIsOneway) {
1075 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1076 kTestString));
1077 } else {
1078 EXPECT_OK(
1079 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1080 }
Steven Moreland659416d2021-05-11 00:47:50 +00001081
Steven Morelandc7d40132021-06-10 03:42:11 +00001082 using std::literals::chrono_literals::operator""s;
1083 std::unique_lock<std::mutex> _l(cb->mMutex);
1084 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001085
Steven Morelandc7d40132021-06-10 03:42:11 +00001086 EXPECT_EQ(cb->mValues.size(), 1)
1087 << "callIsOneway: " << callIsOneway
1088 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1089 if (cb->mValues.empty()) continue;
1090 EXPECT_EQ(cb->mValues.at(0), kTestString)
1091 << "callIsOneway: " << callIsOneway
1092 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001093
Steven Morelandc7d40132021-06-10 03:42:11 +00001094 // since we are severing the connection, we need to go ahead and
1095 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001096 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1097 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1098 }
Steven Moreland659416d2021-05-11 00:47:50 +00001099
Steven Moreland1b304292021-07-15 22:59:34 +00001100 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001101 // need to manually shut it down
1102 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001103
Steven Morelandc7d40132021-06-10 03:42:11 +00001104 proc.expectAlreadyShutdown = true;
1105 }
Steven Moreland659416d2021-05-11 00:47:50 +00001106 }
1107 }
1108}
1109
Steven Moreland195edb82021-06-08 02:44:39 +00001110TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001111 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001112 auto cb = sp<MyBinderRpcCallback>::make();
1113
1114 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1115 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1116}
1117
Steven Morelandc1635952021-04-01 16:20:47 +00001118TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001119 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001120 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001121
1122 // make sure there is some state during crash
1123 // 1. we hold their binder
1124 sp<IBinderRpcSession> session;
1125 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1126 // 2. they hold our binder
1127 sp<IBinder> binder = new BBinder();
1128 EXPECT_OK(proc.rootIface->holdBinder(binder));
1129
1130 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1131 << "Do death cleanup: " << doDeathCleanup;
1132
Steven Morelandaf4ca712021-05-24 23:22:08 +00001133 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001134 }
1135}
1136
Steven Morelandd7302072021-05-15 01:32:04 +00001137TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001138 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001139
1140 // we can't allocate IPCThreadState so actually the first time should
1141 // succeed :(
1142 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1143
1144 // second time! we catch the error :)
1145 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1146
Steven Morelandaf4ca712021-05-24 23:22:08 +00001147 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001148}
1149
Steven Moreland37aff182021-03-26 02:04:16 +00001150TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001151 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001152
1153 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1154 ASSERT_NE(binder, nullptr);
1155
1156 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1157}
1158
1159TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001160 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001161
1162 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1163 ASSERT_NE(binder, nullptr);
1164
1165 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1166 ASSERT_NE(ndkBinder, nullptr);
1167
1168 std::string out;
1169 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1170 ASSERT_TRUE(status.isOk()) << status.getDescription();
1171 ASSERT_EQ("aoeuaoeu", out);
1172}
1173
Steven Moreland5553ac42020-11-11 02:14:45 +00001174ssize_t countFds() {
1175 DIR* dir = opendir("/proc/self/fd/");
1176 if (dir == nullptr) return -1;
1177 ssize_t ret = 0;
1178 dirent* ent;
1179 while ((ent = readdir(dir)) != nullptr) ret++;
1180 closedir(dir);
1181 return ret;
1182}
1183
Steven Morelandc1635952021-04-01 16:20:47 +00001184TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001185 ssize_t beforeFds = countFds();
1186 ASSERT_GE(beforeFds, 0);
1187 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001188 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001189 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1190 }
1191 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1192}
1193
Steven Morelandda573042021-06-12 01:13:45 +00001194static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001195 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001196 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001197 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001198 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001199 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandda573042021-06-12 01:13:45 +00001200 server->start();
1201
Yifan Hong702115c2021-06-24 15:39:18 -07001202 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001203 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001204 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001205 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1206 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001207}
1208
1209static std::vector<SocketType> testSocketTypes() {
Steven Moreland4198a122021-08-03 17:37:58 -07001210 std::vector<SocketType> ret = {SocketType::PRECONNECTED, SocketType::UNIX, SocketType::INET};
Steven Morelandda573042021-06-12 01:13:45 +00001211
1212 static bool hasVsockLoopback = testSupportVsockLoopback();
1213
1214 if (hasVsockLoopback) {
1215 ret.push_back(SocketType::VSOCK);
1216 }
1217
1218 return ret;
1219}
1220
Yifan Hong702115c2021-06-24 15:39:18 -07001221INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1222 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1223 ::testing::ValuesIn(RpcSecurityValues())),
1224 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001225
Yifan Hong702115c2021-06-24 15:39:18 -07001226class BinderRpcServerRootObject
1227 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001228
1229TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1230 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1231 auto setRootObject = [](bool isStrong) -> SetFn {
1232 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1233 };
1234
Yifan Hong702115c2021-06-24 15:39:18 -07001235 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1236 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001237 auto binder1 = sp<BBinder>::make();
1238 IBinder* binderRaw1 = binder1.get();
1239 setRootObject(isStrong1)(server.get(), binder1);
1240 EXPECT_EQ(binderRaw1, server->getRootObject());
1241 binder1.clear();
1242 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1243
1244 auto binder2 = sp<BBinder>::make();
1245 IBinder* binderRaw2 = binder2.get();
1246 setRootObject(isStrong2)(server.get(), binder2);
1247 EXPECT_EQ(binderRaw2, server->getRootObject());
1248 binder2.clear();
1249 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1250}
1251
1252INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001253 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1254 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001255
Yifan Hong1a235852021-05-13 16:07:47 -07001256class OneOffSignal {
1257public:
1258 // If notify() was previously called, or is called within |duration|, return true; else false.
1259 template <typename R, typename P>
1260 bool wait(std::chrono::duration<R, P> duration) {
1261 std::unique_lock<std::mutex> lock(mMutex);
1262 return mCv.wait_for(lock, duration, [this] { return mValue; });
1263 }
1264 void notify() {
1265 std::unique_lock<std::mutex> lock(mMutex);
1266 mValue = true;
1267 lock.unlock();
1268 mCv.notify_all();
1269 }
1270
1271private:
1272 std::mutex mMutex;
1273 std::condition_variable mCv;
1274 bool mValue = false;
1275};
1276
Yifan Hong702115c2021-06-24 15:39:18 -07001277TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001278 auto addr = allocateSocketAddress();
1279 unlink(addr.c_str());
Yifan Hong702115c2021-06-24 15:39:18 -07001280 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong1a235852021-05-13 16:07:47 -07001281 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001282 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001283 auto joinEnds = std::make_shared<OneOffSignal>();
1284
1285 // If things are broken and the thread never stops, don't block other tests. Because the thread
1286 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1287 // shared pointers are passed.
1288 std::thread([server, joinEnds] {
1289 server->join();
1290 joinEnds->notify();
1291 }).detach();
1292
1293 bool shutdown = false;
1294 for (int i = 0; i < 10 && !shutdown; i++) {
1295 usleep(300 * 1000); // 300ms; total 3s
1296 if (server->shutdown()) shutdown = true;
1297 }
1298 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1299
1300 ASSERT_TRUE(joinEnds->wait(2s))
1301 << "After server->shutdown() returns true, join() did not stop after 2s";
1302}
1303
Yifan Hong194acf22021-06-29 18:44:56 -07001304TEST(BinderRpc, Java) {
1305#if !defined(__ANDROID__)
1306 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1307 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1308 "to binderHostDeviceTest. Hence, just disable this test on host.";
1309#endif // !__ANDROID__
1310 sp<IServiceManager> sm = defaultServiceManager();
1311 ASSERT_NE(nullptr, sm);
1312 // Any Java service with non-empty getInterfaceDescriptor() would do.
1313 // Let's pick batteryproperties.
1314 auto binder = sm->checkService(String16("batteryproperties"));
1315 ASSERT_NE(nullptr, binder);
1316 auto descriptor = binder->getInterfaceDescriptor();
1317 ASSERT_GE(descriptor.size(), 0);
1318 ASSERT_EQ(OK, binder->pingBinder());
1319
1320 auto rpcServer = RpcServer::make();
1321 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1322 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001323 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001324 auto socket = rpcServer->releaseServer();
1325
1326 auto keepAlive = sp<BBinder>::make();
1327 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1328
1329 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001330 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001331 auto rpcBinder = rpcSession->getRootObject();
1332 ASSERT_NE(nullptr, rpcBinder);
1333
1334 ASSERT_EQ(OK, rpcBinder->pingBinder());
1335
1336 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1337 << "getInterfaceDescriptor should not crash system_server";
1338 ASSERT_EQ(OK, rpcBinder->pingBinder());
1339}
1340
Yifan Hong702115c2021-06-24 15:39:18 -07001341INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1342 BinderRpcSimple::PrintTestParam);
1343
Steven Morelandc1635952021-04-01 16:20:47 +00001344} // namespace android
1345
1346int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001347 ::testing::InitGoogleTest(&argc, argv);
1348 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1349 return RUN_ALL_TESTS();
1350}