blob: 36a6804bcd1dcef1e32d83839e5da4a2a1826a49 [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());
92 ASSERT_TRUE(server->setupExternalServer(std::move(sink)));
93 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 Moreland611d15f2021-05-01 01:28:27 +0000487 CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000488 break;
489 case SocketType::VSOCK:
Steven Moreland611d15f2021-05-01 01:28:27 +0000490 CHECK(server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000491 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700492 case SocketType::INET: {
Devin Mooref3b9c4f2021-08-03 15:50:13 +0000493 CHECK(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 Moreland4313d7e2021-07-15 23:41:22 +0000519 for (size_t i = 0; i < options.numSessions; i++) {
Yifan Hong702115c2021-06-24 15:39:18 -0700520 sp<RpcSession> session = RpcSession::make(newFactory(rpcSecurity));
Steven Moreland4313d7e2021-07-15 23:41:22 +0000521 session->setMaxThreads(options.numIncomingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000522
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000523 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700524 case SocketType::PRECONNECTED:
525 if (session->setupPreconnectedClient({}, [=]() {
526 return connectToUds(addr.c_str());
527 }))
528 goto success;
529 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000530 case SocketType::UNIX:
531 if (session->setupUnixDomainClient(addr.c_str())) goto success;
532 break;
533 case SocketType::VSOCK:
534 if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
535 break;
536 case SocketType::INET:
537 if (session->setupInetClient("127.0.0.1", outPort)) goto success;
538 break;
539 default:
540 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000541 }
Steven Moreland736664b2021-05-01 04:27:25 +0000542 LOG_ALWAYS_FATAL("Could not connect");
543 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000544 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000545 }
Steven Morelandc1635952021-04-01 16:20:47 +0000546 return ret;
547 }
548
Steven Moreland4313d7e2021-07-15 23:41:22 +0000549 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000550 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000551 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000552 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000553 sp<MyBinderRpcTest> service =
554 new MyBinderRpcTest;
555 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000556 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000557 }),
558 };
559
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000560 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000561 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
562
563 return ret;
564 }
565};
566
Steven Morelandc1635952021-04-01 16:20:47 +0000567TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000568 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000569 ASSERT_NE(proc.rootBinder, nullptr);
570 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
571}
572
Steven Moreland4cf688f2021-03-31 01:48:58 +0000573TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000574 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000575 ASSERT_NE(proc.rootBinder, nullptr);
576 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
577}
578
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000579TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000580 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000581 for (auto session : proc.proc.sessions) {
582 ASSERT_NE(nullptr, session.root);
583 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000584 }
585}
586
Steven Morelandc1635952021-04-01 16:20:47 +0000587TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000588 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000589 Parcel data;
590 Parcel reply;
591 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
592}
593
Steven Moreland67753c32021-04-02 18:45:19 +0000594TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000595 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000596
597 Parcel p1;
598 p1.markForBinder(proc.rootBinder);
599 p1.writeInt32(3);
600
601 Parcel p2;
602
603 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
604 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
605}
606
Steven Morelandc1635952021-04-01 16:20:47 +0000607TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000608 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000609 Parcel data;
610 data.markForBinder(proc.rootBinder);
611 Parcel reply;
612 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
613}
614
Steven Morelandc1635952021-04-01 16:20:47 +0000615TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000616 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000617 EXPECT_OK(proc.rootIface->sendString("asdf"));
618}
619
Steven Morelandc1635952021-04-01 16:20:47 +0000620TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000621 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000622 std::string doubled;
623 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
624 EXPECT_EQ("cool cool ", doubled);
625}
626
Steven Morelandc1635952021-04-01 16:20:47 +0000627TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000628 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000629 std::string single = std::string(1024, 'a');
630 std::string doubled;
631 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
632 EXPECT_EQ(single + single, doubled);
633}
634
Steven Morelandc1635952021-04-01 16:20:47 +0000635TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000636 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000637
638 int32_t pingResult;
639 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
640 EXPECT_EQ(OK, pingResult);
641
642 EXPECT_EQ(0, MyBinderRpcSession::gNum);
643}
644
Steven Morelandc1635952021-04-01 16:20:47 +0000645TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000646 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000647
648 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
649 sp<IBinder> outBinder;
650 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
651 EXPECT_EQ(inBinder, outBinder);
652
653 wp<IBinder> weak = inBinder;
654 inBinder = nullptr;
655 outBinder = nullptr;
656
657 // Force reading a reply, to process any pending dec refs from the other
658 // process (the other process will process dec refs there before processing
659 // the ping here).
660 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
661
662 EXPECT_EQ(nullptr, weak.promote());
663
664 EXPECT_EQ(0, MyBinderRpcSession::gNum);
665}
666
Steven Morelandc1635952021-04-01 16:20:47 +0000667TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000668 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000669
670 sp<IBinderRpcSession> session;
671 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
672
673 sp<IBinder> inBinder = IInterface::asBinder(session);
674 sp<IBinder> outBinder;
675 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
676 EXPECT_EQ(inBinder, outBinder);
677
678 wp<IBinder> weak = inBinder;
679 session = nullptr;
680 inBinder = nullptr;
681 outBinder = nullptr;
682
683 // Force reading a reply, to process any pending dec refs from the other
684 // process (the other process will process dec refs there before processing
685 // the ping here).
686 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
687
688 EXPECT_EQ(nullptr, weak.promote());
689}
690
Steven Morelandc1635952021-04-01 16:20:47 +0000691TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000692 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000693
694 sp<IBinder> outBinder;
695 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
696 EXPECT_EQ(nullptr, outBinder);
697}
698
Steven Morelandc1635952021-04-01 16:20:47 +0000699TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000700 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000701
702 IBinder* ptr = nullptr;
703 {
704 sp<IBinder> binder = new BBinder();
705 ptr = binder.get();
706 EXPECT_OK(proc.rootIface->holdBinder(binder));
707 }
708
709 sp<IBinder> held;
710 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
711
712 EXPECT_EQ(held.get(), ptr);
713
714 // stop holding binder, because we test to make sure references are cleaned
715 // up
716 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
717 // and flush ref counts
718 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
719}
720
721// START TESTS FOR LIMITATIONS OF SOCKET BINDER
722// These are behavioral differences form regular binder, where certain usecases
723// aren't supported.
724
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000725TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000726 auto proc1 = createRpcTestSocketServerProcess({});
727 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000728
729 sp<IBinder> outBinder;
730 EXPECT_EQ(INVALID_OPERATION,
731 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
732}
733
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000734TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000735 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000736
737 sp<IBinder> outBinder;
738 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000739 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000740 .transactionError());
741}
742
Steven Morelandc1635952021-04-01 16:20:47 +0000743TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000744 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000745
746 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
747 sp<IBinder> outBinder;
748 EXPECT_EQ(INVALID_OPERATION,
749 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
750}
751
Steven Morelandc1635952021-04-01 16:20:47 +0000752TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000753 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000754
755 // for historical reasons, IServiceManager interface only returns the
756 // exception code
757 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
758 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
759}
760
761// END TESTS FOR LIMITATIONS OF SOCKET BINDER
762
Steven Morelandc1635952021-04-01 16:20:47 +0000763TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000764 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000765
766 sp<IBinder> outBinder;
767 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
768 EXPECT_EQ(proc.rootBinder, outBinder);
769}
770
Steven Morelandc1635952021-04-01 16:20:47 +0000771TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000772 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000773
774 auto nastyNester = sp<MyBinderRpcTest>::make();
775 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
776
777 wp<IBinder> weak = nastyNester;
778 nastyNester = nullptr;
779 EXPECT_EQ(nullptr, weak.promote());
780}
781
Steven Morelandc1635952021-04-01 16:20:47 +0000782TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000783 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000784
785 sp<IBinder> a;
786 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
787
788 sp<IBinder> b;
789 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
790
791 EXPECT_EQ(a, b);
792}
793
Steven Morelandc1635952021-04-01 16:20:47 +0000794TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000795 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000796
797 sp<IBinder> a;
798 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
799 wp<IBinder> weak = a;
800 a = nullptr;
801
802 sp<IBinder> b;
803 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
804
805 // this is the wrong behavior, since BpBinder
806 // doesn't implement onIncStrongAttempted
807 // but make sure there is no crash
808 EXPECT_EQ(nullptr, weak.promote());
809
810 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
811
812 // In order to fix this:
813 // - need to have incStrongAttempted reflected across IPC boundary (wait for
814 // response to promote - round trip...)
815 // - sendOnLastWeakRef, to delete entries out of RpcState table
816 EXPECT_EQ(b, weak.promote());
817}
818
819#define expectSessions(expected, iface) \
820 do { \
821 int session; \
822 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
823 EXPECT_EQ(expected, session); \
824 } while (false)
825
Steven Morelandc1635952021-04-01 16:20:47 +0000826TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000827 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000828
829 sp<IBinderRpcSession> session;
830 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
831 std::string out;
832 EXPECT_OK(session->getName(&out));
833 EXPECT_EQ("aoeu", out);
834
835 expectSessions(1, proc.rootIface);
836 session = nullptr;
837 expectSessions(0, proc.rootIface);
838}
839
Steven Morelandc1635952021-04-01 16:20:47 +0000840TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000841 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000842
843 std::vector<sp<IBinderRpcSession>> sessions;
844
845 for (size_t i = 0; i < 15; i++) {
846 expectSessions(i, proc.rootIface);
847 sp<IBinderRpcSession> session;
848 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
849 sessions.push_back(session);
850 }
851 expectSessions(sessions.size(), proc.rootIface);
852 for (size_t i = 0; i < sessions.size(); i++) {
853 std::string out;
854 EXPECT_OK(sessions.at(i)->getName(&out));
855 EXPECT_EQ(std::to_string(i), out);
856 }
857 expectSessions(sessions.size(), proc.rootIface);
858
859 while (!sessions.empty()) {
860 sessions.pop_back();
861 expectSessions(sessions.size(), proc.rootIface);
862 }
863 expectSessions(0, proc.rootIface);
864}
865
866size_t epochMillis() {
867 using std::chrono::duration_cast;
868 using std::chrono::milliseconds;
869 using std::chrono::seconds;
870 using std::chrono::system_clock;
871 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
872}
873
Steven Morelandc1635952021-04-01 16:20:47 +0000874TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000875 constexpr size_t kNumThreads = 10;
876
Steven Moreland4313d7e2021-07-15 23:41:22 +0000877 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000878
879 EXPECT_OK(proc.rootIface->lock());
880
881 // block all but one thread taking locks
882 std::vector<std::thread> ts;
883 for (size_t i = 0; i < kNumThreads - 1; i++) {
884 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
885 }
886
887 usleep(100000); // give chance for calls on other threads
888
889 // other calls still work
890 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
891
892 constexpr size_t blockTimeMs = 500;
893 size_t epochMsBefore = epochMillis();
894 // after this, we should never see a response within this time
895 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
896
897 // this call should be blocked for blockTimeMs
898 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
899
900 size_t epochMsAfter = epochMillis();
901 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
902
903 for (auto& t : ts) t.join();
904}
905
Steven Morelandc1635952021-04-01 16:20:47 +0000906TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000907 constexpr size_t kNumThreads = 10;
908 constexpr size_t kNumCalls = kNumThreads + 3;
909 constexpr size_t kSleepMs = 500;
910
Steven Moreland4313d7e2021-07-15 23:41:22 +0000911 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000912
913 size_t epochMsBefore = epochMillis();
914
915 std::vector<std::thread> ts;
916 for (size_t i = 0; i < kNumCalls; i++) {
917 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
918 }
919
920 for (auto& t : ts) t.join();
921
922 size_t epochMsAfter = epochMillis();
923
924 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
925
926 // Potential flake, but make sure calls are handled in parallel.
927 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
928}
929
Steven Morelandc1635952021-04-01 16:20:47 +0000930TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000931 constexpr size_t kNumClientThreads = 10;
932 constexpr size_t kNumServerThreads = 10;
933 constexpr size_t kNumCalls = 100;
934
Steven Moreland4313d7e2021-07-15 23:41:22 +0000935 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000936
937 std::vector<std::thread> threads;
938 for (size_t i = 0; i < kNumClientThreads; i++) {
939 threads.push_back(std::thread([&] {
940 for (size_t j = 0; j < kNumCalls; j++) {
941 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000942 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000943 EXPECT_EQ(proc.rootBinder, out);
944 }
945 }));
946 }
947
948 for (auto& t : threads) t.join();
949}
950
Steven Morelandc6046982021-04-20 00:49:42 +0000951TEST_P(BinderRpc, OnewayStressTest) {
952 constexpr size_t kNumClientThreads = 10;
953 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000954 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000955
Steven Moreland4313d7e2021-07-15 23:41:22 +0000956 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000957
958 std::vector<std::thread> threads;
959 for (size_t i = 0; i < kNumClientThreads; i++) {
960 threads.push_back(std::thread([&] {
961 for (size_t j = 0; j < kNumCalls; j++) {
962 EXPECT_OK(proc.rootIface->sendString("a"));
963 }
964
965 // check threads are not stuck
966 EXPECT_OK(proc.rootIface->sleepMs(250));
967 }));
968 }
969
970 for (auto& t : threads) t.join();
971}
972
Steven Morelandc1635952021-04-01 16:20:47 +0000973TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000974 constexpr size_t kReallyLongTimeMs = 100;
975 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
976
Steven Moreland4313d7e2021-07-15 23:41:22 +0000977 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000978
979 size_t epochMsBefore = epochMillis();
980
981 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
982
983 size_t epochMsAfter = epochMillis();
984 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
985}
986
Steven Morelandc1635952021-04-01 16:20:47 +0000987TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000988 constexpr size_t kNumSleeps = 10;
989 constexpr size_t kNumExtraServerThreads = 4;
990 constexpr size_t kSleepMs = 50;
991
992 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000993 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000994
995 EXPECT_OK(proc.rootIface->lock());
996
997 for (size_t i = 0; i < kNumSleeps; i++) {
998 // these should be processed serially
999 proc.rootIface->sleepMsAsync(kSleepMs);
1000 }
1001 // should also be processesed serially
1002 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1003
1004 size_t epochMsBefore = epochMillis();
1005 EXPECT_OK(proc.rootIface->lockUnlock());
1006 size_t epochMsAfter = epochMillis();
1007
1008 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001009
1010 // pending oneway transactions hold ref, make sure we read data on all
1011 // sockets
1012 std::vector<std::thread> threads;
1013 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
1014 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
1015 }
1016 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +00001017}
1018
Steven Morelandd45be622021-06-04 02:19:37 +00001019TEST_P(BinderRpc, OnewayCallExhaustion) {
1020 constexpr size_t kNumClients = 2;
1021 constexpr size_t kTooLongMs = 1000;
1022
Steven Moreland4313d7e2021-07-15 23:41:22 +00001023 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001024
1025 // Build up oneway calls on the second session to make sure it terminates
1026 // and shuts down. The first session should be unaffected (proc destructor
1027 // checks the first session).
1028 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1029
1030 std::vector<std::thread> threads;
1031 for (size_t i = 0; i < kNumClients; i++) {
1032 // one of these threads will get stuck queueing a transaction once the
1033 // socket fills up, the other will be able to fill up transactions on
1034 // this object
1035 threads.push_back(std::thread([&] {
1036 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1037 }
1038 }));
1039 }
1040 for (auto& t : threads) t.join();
1041
1042 Status status = iface->sleepMsAsync(kTooLongMs);
1043 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1044
Steven Moreland798e0d12021-07-14 23:19:25 +00001045 // now that it has died, wait for the remote session to shutdown
1046 std::vector<int32_t> remoteCounts;
1047 do {
1048 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1049 } while (remoteCounts.size() == kNumClients);
1050
Steven Morelandd45be622021-06-04 02:19:37 +00001051 // the second session should be shutdown in the other process by the time we
1052 // are able to join above (it'll only be hung up once it finishes processing
1053 // any pending commands). We need to erase this session from the record
1054 // here, so that the destructor for our session won't check that this
1055 // session is valid, but we still want it to test the other session.
1056 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1057}
1058
Steven Moreland659416d2021-05-11 00:47:50 +00001059TEST_P(BinderRpc, Callbacks) {
1060 const static std::string kTestString = "good afternoon!";
1061
Steven Morelandc7d40132021-06-10 03:42:11 +00001062 for (bool callIsOneway : {true, false}) {
1063 for (bool callbackIsOneway : {true, false}) {
1064 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001065 auto proc = createRpcTestSocketServerProcess(
1066 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001067 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001068
Steven Morelandc7d40132021-06-10 03:42:11 +00001069 if (callIsOneway) {
1070 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1071 kTestString));
1072 } else {
1073 EXPECT_OK(
1074 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1075 }
Steven Moreland659416d2021-05-11 00:47:50 +00001076
Steven Morelandc7d40132021-06-10 03:42:11 +00001077 using std::literals::chrono_literals::operator""s;
1078 std::unique_lock<std::mutex> _l(cb->mMutex);
1079 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001080
Steven Morelandc7d40132021-06-10 03:42:11 +00001081 EXPECT_EQ(cb->mValues.size(), 1)
1082 << "callIsOneway: " << callIsOneway
1083 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1084 if (cb->mValues.empty()) continue;
1085 EXPECT_EQ(cb->mValues.at(0), kTestString)
1086 << "callIsOneway: " << callIsOneway
1087 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001088
Steven Morelandc7d40132021-06-10 03:42:11 +00001089 // since we are severing the connection, we need to go ahead and
1090 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001091 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1092 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1093 }
Steven Moreland659416d2021-05-11 00:47:50 +00001094
Steven Moreland1b304292021-07-15 22:59:34 +00001095 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001096 // need to manually shut it down
1097 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001098
Steven Morelandc7d40132021-06-10 03:42:11 +00001099 proc.expectAlreadyShutdown = true;
1100 }
Steven Moreland659416d2021-05-11 00:47:50 +00001101 }
1102 }
1103}
1104
Steven Moreland195edb82021-06-08 02:44:39 +00001105TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001106 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001107 auto cb = sp<MyBinderRpcCallback>::make();
1108
1109 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1110 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1111}
1112
Steven Morelandc1635952021-04-01 16:20:47 +00001113TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001114 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001115 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001116
1117 // make sure there is some state during crash
1118 // 1. we hold their binder
1119 sp<IBinderRpcSession> session;
1120 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1121 // 2. they hold our binder
1122 sp<IBinder> binder = new BBinder();
1123 EXPECT_OK(proc.rootIface->holdBinder(binder));
1124
1125 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1126 << "Do death cleanup: " << doDeathCleanup;
1127
Steven Morelandaf4ca712021-05-24 23:22:08 +00001128 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001129 }
1130}
1131
Steven Morelandd7302072021-05-15 01:32:04 +00001132TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001133 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001134
1135 // we can't allocate IPCThreadState so actually the first time should
1136 // succeed :(
1137 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1138
1139 // second time! we catch the error :)
1140 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1141
Steven Morelandaf4ca712021-05-24 23:22:08 +00001142 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001143}
1144
Steven Moreland37aff182021-03-26 02:04:16 +00001145TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001146 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001147
1148 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1149 ASSERT_NE(binder, nullptr);
1150
1151 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1152}
1153
1154TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001155 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001156
1157 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1158 ASSERT_NE(binder, nullptr);
1159
1160 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1161 ASSERT_NE(ndkBinder, nullptr);
1162
1163 std::string out;
1164 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1165 ASSERT_TRUE(status.isOk()) << status.getDescription();
1166 ASSERT_EQ("aoeuaoeu", out);
1167}
1168
Steven Moreland5553ac42020-11-11 02:14:45 +00001169ssize_t countFds() {
1170 DIR* dir = opendir("/proc/self/fd/");
1171 if (dir == nullptr) return -1;
1172 ssize_t ret = 0;
1173 dirent* ent;
1174 while ((ent = readdir(dir)) != nullptr) ret++;
1175 closedir(dir);
1176 return ret;
1177}
1178
Steven Morelandc1635952021-04-01 16:20:47 +00001179TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001180 ssize_t beforeFds = countFds();
1181 ASSERT_GE(beforeFds, 0);
1182 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001183 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001184 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1185 }
1186 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1187}
1188
Steven Morelandda573042021-06-12 01:13:45 +00001189static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001190 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001191 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001192 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001193 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1194 CHECK(server->setupVsockServer(vsockPort));
1195 server->start();
1196
Yifan Hong702115c2021-06-24 15:39:18 -07001197 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001198 bool okay = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001199 while (!server->shutdown()) usleep(10000);
Steven Morelandda573042021-06-12 01:13:45 +00001200 ALOGE("Detected vsock loopback supported: %d", okay);
1201 return okay;
1202}
1203
1204static std::vector<SocketType> testSocketTypes() {
Steven Moreland4198a122021-08-03 17:37:58 -07001205 std::vector<SocketType> ret = {SocketType::PRECONNECTED, SocketType::UNIX, SocketType::INET};
Steven Morelandda573042021-06-12 01:13:45 +00001206
1207 static bool hasVsockLoopback = testSupportVsockLoopback();
1208
1209 if (hasVsockLoopback) {
1210 ret.push_back(SocketType::VSOCK);
1211 }
1212
1213 return ret;
1214}
1215
Yifan Hong702115c2021-06-24 15:39:18 -07001216INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1217 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1218 ::testing::ValuesIn(RpcSecurityValues())),
1219 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001220
Yifan Hong702115c2021-06-24 15:39:18 -07001221class BinderRpcServerRootObject
1222 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001223
1224TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1225 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1226 auto setRootObject = [](bool isStrong) -> SetFn {
1227 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1228 };
1229
Yifan Hong702115c2021-06-24 15:39:18 -07001230 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1231 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001232 auto binder1 = sp<BBinder>::make();
1233 IBinder* binderRaw1 = binder1.get();
1234 setRootObject(isStrong1)(server.get(), binder1);
1235 EXPECT_EQ(binderRaw1, server->getRootObject());
1236 binder1.clear();
1237 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1238
1239 auto binder2 = sp<BBinder>::make();
1240 IBinder* binderRaw2 = binder2.get();
1241 setRootObject(isStrong2)(server.get(), binder2);
1242 EXPECT_EQ(binderRaw2, server->getRootObject());
1243 binder2.clear();
1244 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1245}
1246
1247INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001248 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1249 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001250
Yifan Hong1a235852021-05-13 16:07:47 -07001251class OneOffSignal {
1252public:
1253 // If notify() was previously called, or is called within |duration|, return true; else false.
1254 template <typename R, typename P>
1255 bool wait(std::chrono::duration<R, P> duration) {
1256 std::unique_lock<std::mutex> lock(mMutex);
1257 return mCv.wait_for(lock, duration, [this] { return mValue; });
1258 }
1259 void notify() {
1260 std::unique_lock<std::mutex> lock(mMutex);
1261 mValue = true;
1262 lock.unlock();
1263 mCv.notify_all();
1264 }
1265
1266private:
1267 std::mutex mMutex;
1268 std::condition_variable mCv;
1269 bool mValue = false;
1270};
1271
Yifan Hong702115c2021-06-24 15:39:18 -07001272TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001273 auto addr = allocateSocketAddress();
1274 unlink(addr.c_str());
Yifan Hong702115c2021-06-24 15:39:18 -07001275 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong1a235852021-05-13 16:07:47 -07001276 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1277 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1278 auto joinEnds = std::make_shared<OneOffSignal>();
1279
1280 // If things are broken and the thread never stops, don't block other tests. Because the thread
1281 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1282 // shared pointers are passed.
1283 std::thread([server, joinEnds] {
1284 server->join();
1285 joinEnds->notify();
1286 }).detach();
1287
1288 bool shutdown = false;
1289 for (int i = 0; i < 10 && !shutdown; i++) {
1290 usleep(300 * 1000); // 300ms; total 3s
1291 if (server->shutdown()) shutdown = true;
1292 }
1293 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1294
1295 ASSERT_TRUE(joinEnds->wait(2s))
1296 << "After server->shutdown() returns true, join() did not stop after 2s";
1297}
1298
Yifan Hong194acf22021-06-29 18:44:56 -07001299TEST(BinderRpc, Java) {
1300#if !defined(__ANDROID__)
1301 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1302 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1303 "to binderHostDeviceTest. Hence, just disable this test on host.";
1304#endif // !__ANDROID__
1305 sp<IServiceManager> sm = defaultServiceManager();
1306 ASSERT_NE(nullptr, sm);
1307 // Any Java service with non-empty getInterfaceDescriptor() would do.
1308 // Let's pick batteryproperties.
1309 auto binder = sm->checkService(String16("batteryproperties"));
1310 ASSERT_NE(nullptr, binder);
1311 auto descriptor = binder->getInterfaceDescriptor();
1312 ASSERT_GE(descriptor.size(), 0);
1313 ASSERT_EQ(OK, binder->pingBinder());
1314
1315 auto rpcServer = RpcServer::make();
1316 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1317 unsigned int port;
Devin Mooref3b9c4f2021-08-03 15:50:13 +00001318 ASSERT_TRUE(rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001319 auto socket = rpcServer->releaseServer();
1320
1321 auto keepAlive = sp<BBinder>::make();
1322 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1323
1324 auto rpcSession = RpcSession::make();
1325 ASSERT_TRUE(rpcSession->setupInetClient("127.0.0.1", port));
1326 auto rpcBinder = rpcSession->getRootObject();
1327 ASSERT_NE(nullptr, rpcBinder);
1328
1329 ASSERT_EQ(OK, rpcBinder->pingBinder());
1330
1331 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1332 << "getInterfaceDescriptor should not crash system_server";
1333 ASSERT_EQ(OK, rpcBinder->pingBinder());
1334}
1335
Yifan Hong702115c2021-06-24 15:39:18 -07001336INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1337 BinderRpcSimple::PrintTestParam);
1338
Steven Morelandc1635952021-04-01 16:20:47 +00001339} // namespace android
1340
1341int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001342 ::testing::InitGoogleTest(&argc, argv);
1343 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1344 return RUN_ALL_TESTS();
1345}