blob: 6c56a4dfa6497909fdce245d16281e28b8ff4b56 [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);
55
Yifan Hong702115c2021-06-24 15:39:18 -070056enum class RpcSecurity { RAW };
57
58static inline std::vector<RpcSecurity> RpcSecurityValues() {
59 return {RpcSecurity::RAW};
60}
61
62static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(RpcSecurity rpcSecurity) {
63 switch (rpcSecurity) {
64 case RpcSecurity::RAW:
65 return RpcTransportCtxFactoryRaw::make();
66 default:
67 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
68 }
69}
70
Steven Moreland1fda67b2021-04-02 18:35:50 +000071TEST(BinderRpcParcel, EntireParcelFormatted) {
72 Parcel p;
73 p.writeInt32(3);
74
75 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
76}
77
Yifan Hong702115c2021-06-24 15:39:18 -070078class BinderRpcSimple : public ::testing::TestWithParam<RpcSecurity> {
79public:
80 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
81 return newFactory(info.param)->toCString();
82 }
83};
84
85TEST_P(BinderRpcSimple, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -070086 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
87 int sinkFd = sink.get();
Yifan Hong702115c2021-06-24 15:39:18 -070088 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -070089 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
90 ASSERT_FALSE(server->hasServer());
91 ASSERT_TRUE(server->setupExternalServer(std::move(sink)));
92 ASSERT_TRUE(server->hasServer());
93 base::unique_fd retrieved = server->releaseServer();
94 ASSERT_FALSE(server->hasServer());
95 ASSERT_EQ(sinkFd, retrieved.get());
96}
97
Steven Morelandbf57bce2021-07-26 15:26:12 -070098TEST(BinderRpc, CannotUseNextWireVersion) {
99 auto session = RpcSession::make();
100 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
101 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
102 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
103 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
104}
105
106TEST(BinderRpc, CanUseExperimentalWireVersion) {
107 auto session = RpcSession::make();
108 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
109}
110
Steven Moreland5553ac42020-11-11 02:14:45 +0000111using android::binder::Status;
112
113#define EXPECT_OK(status) \
114 do { \
115 Status stat = (status); \
116 EXPECT_TRUE(stat.isOk()) << stat; \
117 } while (false)
118
119class MyBinderRpcSession : public BnBinderRpcSession {
120public:
121 static std::atomic<int32_t> gNum;
122
123 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
124 Status getName(std::string* name) override {
125 *name = mName;
126 return Status::ok();
127 }
128 ~MyBinderRpcSession() { gNum--; }
129
130private:
131 std::string mName;
132};
133std::atomic<int32_t> MyBinderRpcSession::gNum;
134
Steven Moreland659416d2021-05-11 00:47:50 +0000135class MyBinderRpcCallback : public BnBinderRpcCallback {
136 Status sendCallback(const std::string& value) {
137 std::unique_lock _l(mMutex);
138 mValues.push_back(value);
139 _l.unlock();
140 mCv.notify_one();
141 return Status::ok();
142 }
143 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
144
145public:
146 std::mutex mMutex;
147 std::condition_variable mCv;
148 std::vector<std::string> mValues;
149};
150
Steven Moreland5553ac42020-11-11 02:14:45 +0000151class MyBinderRpcTest : public BnBinderRpcTest {
152public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000153 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +0000154
155 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000156 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000157 return Status::ok();
158 }
159 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000160 *strstr = str + str;
161 return Status::ok();
162 }
Steven Moreland736664b2021-05-01 04:27:25 +0000163 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000164 sp<RpcServer> spServer = server.promote();
165 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000166 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
167 }
Steven Moreland736664b2021-05-01 04:27:25 +0000168 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000169 for (auto session : spServer->listSessions()) {
170 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000171 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000172 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000173 return Status::ok();
174 }
175 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
176 if (binder == nullptr) {
177 std::cout << "Received null binder!" << std::endl;
178 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
179 }
180 *out = binder->pingBinder();
181 return Status::ok();
182 }
183 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
184 *out = binder;
185 return Status::ok();
186 }
187 static sp<IBinder> mHeldBinder;
188 Status holdBinder(const sp<IBinder>& binder) override {
189 mHeldBinder = binder;
190 return Status::ok();
191 }
192 Status getHeldBinder(sp<IBinder>* held) override {
193 *held = mHeldBinder;
194 return Status::ok();
195 }
196 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
197 if (count <= 0) return Status::ok();
198 return binder->nestMe(this, count - 1);
199 }
200 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
201 static sp<IBinder> binder = new BBinder;
202 *out = binder;
203 return Status::ok();
204 }
205 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
206 *out = new MyBinderRpcSession(name);
207 return Status::ok();
208 }
209 Status getNumOpenSessions(int32_t* out) override {
210 *out = MyBinderRpcSession::gNum;
211 return Status::ok();
212 }
213
214 std::mutex blockMutex;
215 Status lock() override {
216 blockMutex.lock();
217 return Status::ok();
218 }
219 Status unlockInMsAsync(int32_t ms) override {
220 usleep(ms * 1000);
221 blockMutex.unlock();
222 return Status::ok();
223 }
224 Status lockUnlock() override {
225 std::lock_guard<std::mutex> _l(blockMutex);
226 return Status::ok();
227 }
228
229 Status sleepMs(int32_t ms) override {
230 usleep(ms * 1000);
231 return Status::ok();
232 }
233
234 Status sleepMsAsync(int32_t ms) override {
235 // In-process binder calls are asynchronous, but the call to this method
236 // is synchronous wrt its client. This in/out-process threading model
237 // diffentiation is a classic binder leaky abstraction (for better or
238 // worse) and is preserved here the way binder sockets plugs itself
239 // into BpBinder, as nothing is changed at the higher levels
240 // (IInterface) which result in this behavior.
241 return sleepMs(ms);
242 }
243
Steven Moreland659416d2021-05-11 00:47:50 +0000244 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
245 const std::string& value) override {
246 if (callback == nullptr) {
247 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
248 }
249
250 if (delayed) {
251 std::thread([=]() {
252 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000253 Status status = doCallback(callback, oneway, false, value);
254 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000255 }).detach();
256 return Status::ok();
257 }
258
259 if (oneway) {
260 return callback->sendOnewayCallback(value);
261 }
262
263 return callback->sendCallback(value);
264 }
265
Steven Morelandc7d40132021-06-10 03:42:11 +0000266 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
267 const std::string& value) override {
268 return doCallback(callback, oneway, delayed, value);
269 }
270
Steven Moreland5553ac42020-11-11 02:14:45 +0000271 Status die(bool cleanup) override {
272 if (cleanup) {
273 exit(1);
274 } else {
275 _exit(1);
276 }
277 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000278
279 Status scheduleShutdown() override {
280 sp<RpcServer> strongServer = server.promote();
281 if (strongServer == nullptr) {
282 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
283 }
284 std::thread([=] {
285 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
286 }).detach();
287 return Status::ok();
288 }
289
Steven Morelandd7302072021-05-15 01:32:04 +0000290 Status useKernelBinderCallingId() override {
291 // this is WRONG! It does not make sense when using RPC binder, and
292 // because it is SO wrong, and so much code calls this, it should abort!
293
294 (void)IPCThreadState::self()->getCallingPid();
295 return Status::ok();
296 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000297};
298sp<IBinder> MyBinderRpcTest::mHeldBinder;
299
300class Process {
301public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700302 Process(Process&&) = default;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700303 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */)>& f) {
304 android::base::unique_fd writeEnd;
305 CHECK(android::base::Pipe(&mReadEnd, &writeEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000306 if (0 == (mPid = fork())) {
307 // racey: assume parent doesn't crash before this is set
308 prctl(PR_SET_PDEATHSIG, SIGHUP);
309
Yifan Hong0f58fb92021-06-16 16:09:23 -0700310 f(writeEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000311
312 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000313 }
314 }
315 ~Process() {
316 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000317 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000318 }
319 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700320 android::base::borrowed_fd readEnd() { return mReadEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000321
322private:
323 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700324 android::base::unique_fd mReadEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000325};
326
327static std::string allocateSocketAddress() {
328 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000329 std::string temp = getenv("TMPDIR") ?: "/tmp";
330 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000331};
332
Steven Morelandda573042021-06-12 01:13:45 +0000333static unsigned int allocateVsockPort() {
334 static unsigned int vsockPort = 3456;
335 return vsockPort++;
336}
337
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000338struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000339 // reference to process hosting a socket server
340 Process host;
341
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000342 struct SessionInfo {
343 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000344 sp<IBinder> root;
345 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000346
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000347 // client session objects associated with other process
348 // each one represents a separate session
349 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000350
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000351 ProcessSession(ProcessSession&&) = default;
352 ~ProcessSession() {
353 for (auto& session : sessions) {
354 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000355 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000356
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000357 for (auto& info : sessions) {
358 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000359
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000360 EXPECT_NE(nullptr, session);
361 EXPECT_NE(nullptr, session->state());
362 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000363
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000364 wp<RpcSession> weakSession = session;
365 session = nullptr;
366 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000367 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000368 }
369};
370
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000371// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000372// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000373struct BinderRpcTestProcessSession {
374 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000375
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000376 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000377 sp<IBinder> rootBinder;
378
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000379 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000380 sp<IBinderRpcTest> rootIface;
381
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000382 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000383 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000384
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000385 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
386 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000387 EXPECT_NE(nullptr, rootIface);
388 if (rootIface == nullptr) return;
389
Steven Morelandaf4ca712021-05-24 23:22:08 +0000390 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000391 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000392 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000393 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000394 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000395 for (auto remoteCount : remoteCounts) {
396 EXPECT_EQ(remoteCount, 1);
397 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000398
Steven Moreland798e0d12021-07-14 23:19:25 +0000399 // even though it is on another thread, shutdown races with
400 // the transaction reply being written
401 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
402 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
403 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000404 }
405
406 rootIface = nullptr;
407 rootBinder = nullptr;
408 }
409};
410
Steven Morelandc1635952021-04-01 16:20:47 +0000411enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700412 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000413 UNIX,
414 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700415 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000416};
Yifan Hong702115c2021-06-24 15:39:18 -0700417static inline std::string PrintToString(SocketType socketType) {
418 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700419 case SocketType::PRECONNECTED:
420 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000421 case SocketType::UNIX:
422 return "unix_domain_socket";
423 case SocketType::VSOCK:
424 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700425 case SocketType::INET:
426 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000427 default:
428 LOG_ALWAYS_FATAL("Unknown socket type");
429 return "";
430 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000431}
Steven Morelandda573042021-06-12 01:13:45 +0000432
Steven Moreland4198a122021-08-03 17:37:58 -0700433static base::unique_fd connectToUds(const char* addrStr) {
434 UnixSocketAddress addr(addrStr);
435 base::unique_fd serverFd(
436 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
437 int savedErrno = errno;
438 CHECK(serverFd.ok()) << "Could not create socket " << addrStr << ": " << strerror(savedErrno);
439
440 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
441 int savedErrno = errno;
442 LOG(FATAL) << "Could not connect to socket " << addrStr << ": " << strerror(savedErrno);
443 }
444 return serverFd;
445}
446
Yifan Hong702115c2021-06-24 15:39:18 -0700447class BinderRpc : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000448public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000449 struct Options {
450 size_t numThreads = 1;
451 size_t numSessions = 1;
452 size_t numIncomingConnections = 0;
453 };
454
Yifan Hong702115c2021-06-24 15:39:18 -0700455 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
456 auto [type, security] = info.param;
457 return PrintToString(type) + "_" + newFactory(security)->toCString();
458 }
459
Steven Morelandc1635952021-04-01 16:20:47 +0000460 // This creates a new process serving an interface on a certain number of
461 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000462 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000463 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
464 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000465
Yifan Hong702115c2021-06-24 15:39:18 -0700466 SocketType socketType = std::get<0>(GetParam());
467 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000468
Steven Morelandda573042021-06-12 01:13:45 +0000469 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000470 std::string addr = allocateSocketAddress();
471 unlink(addr.c_str());
Steven Morelandc1635952021-04-01 16:20:47 +0000472
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000473 auto ret = ProcessSession{
Yifan Hong0f58fb92021-06-16 16:09:23 -0700474 .host = Process([&](android::base::borrowed_fd writeEnd) {
Yifan Hong702115c2021-06-24 15:39:18 -0700475 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity));
Steven Morelandc1635952021-04-01 16:20:47 +0000476
477 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000478 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000479
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000480 unsigned int outPort = 0;
481
Steven Morelandc1635952021-04-01 16:20:47 +0000482 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700483 case SocketType::PRECONNECTED:
484 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000485 case SocketType::UNIX:
Steven Moreland611d15f2021-05-01 01:28:27 +0000486 CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000487 break;
488 case SocketType::VSOCK:
Steven Moreland611d15f2021-05-01 01:28:27 +0000489 CHECK(server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000490 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700491 case SocketType::INET: {
Steven Moreland611d15f2021-05-01 01:28:27 +0000492 CHECK(server->setupInetServer(0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700493 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700494 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700495 }
Steven Morelandc1635952021-04-01 16:20:47 +0000496 default:
497 LOG_ALWAYS_FATAL("Unknown socket type");
498 }
499
Yifan Hong0f58fb92021-06-16 16:09:23 -0700500 CHECK(android::base::WriteFully(writeEnd, &outPort, sizeof(outPort)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000501
Steven Moreland611d15f2021-05-01 01:28:27 +0000502 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000503
Steven Morelandf137de92021-04-24 01:54:26 +0000504 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000505
506 // Another thread calls shutdown. Wait for it to complete.
507 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000508 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000509 };
510
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000511 // always read socket, so that we have waited for the server to start
512 unsigned int outPort = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700513 CHECK(android::base::ReadFully(ret.host.readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700514 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000515 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700516 }
517
Steven Moreland4313d7e2021-07-15 23:41:22 +0000518 for (size_t i = 0; i < options.numSessions; i++) {
Yifan Hong702115c2021-06-24 15:39:18 -0700519 sp<RpcSession> session = RpcSession::make(newFactory(rpcSecurity));
Steven Moreland4313d7e2021-07-15 23:41:22 +0000520 session->setMaxThreads(options.numIncomingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000521
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000522 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700523 case SocketType::PRECONNECTED:
524 if (session->setupPreconnectedClient({}, [=]() {
525 return connectToUds(addr.c_str());
526 }))
527 goto success;
528 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000529 case SocketType::UNIX:
530 if (session->setupUnixDomainClient(addr.c_str())) goto success;
531 break;
532 case SocketType::VSOCK:
533 if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
534 break;
535 case SocketType::INET:
536 if (session->setupInetClient("127.0.0.1", outPort)) goto success;
537 break;
538 default:
539 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000540 }
Steven Moreland736664b2021-05-01 04:27:25 +0000541 LOG_ALWAYS_FATAL("Could not connect");
542 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000543 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000544 }
Steven Morelandc1635952021-04-01 16:20:47 +0000545 return ret;
546 }
547
Steven Moreland4313d7e2021-07-15 23:41:22 +0000548 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000549 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000550 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000551 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000552 sp<MyBinderRpcTest> service =
553 new MyBinderRpcTest;
554 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000555 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000556 }),
557 };
558
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000559 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000560 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
561
562 return ret;
563 }
564};
565
Steven Morelandc1635952021-04-01 16:20:47 +0000566TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000567 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000568 ASSERT_NE(proc.rootBinder, nullptr);
569 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
570}
571
Steven Moreland4cf688f2021-03-31 01:48:58 +0000572TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000573 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000574 ASSERT_NE(proc.rootBinder, nullptr);
575 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
576}
577
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000578TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000579 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000580 for (auto session : proc.proc.sessions) {
581 ASSERT_NE(nullptr, session.root);
582 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000583 }
584}
585
Steven Morelandc1635952021-04-01 16:20:47 +0000586TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000587 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000588 Parcel data;
589 Parcel reply;
590 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
591}
592
Steven Moreland67753c32021-04-02 18:45:19 +0000593TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000594 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000595
596 Parcel p1;
597 p1.markForBinder(proc.rootBinder);
598 p1.writeInt32(3);
599
600 Parcel p2;
601
602 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
603 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
604}
605
Steven Morelandc1635952021-04-01 16:20:47 +0000606TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000607 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000608 Parcel data;
609 data.markForBinder(proc.rootBinder);
610 Parcel reply;
611 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
612}
613
Steven Morelandc1635952021-04-01 16:20:47 +0000614TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000615 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000616 EXPECT_OK(proc.rootIface->sendString("asdf"));
617}
618
Steven Morelandc1635952021-04-01 16:20:47 +0000619TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000620 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000621 std::string doubled;
622 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
623 EXPECT_EQ("cool cool ", doubled);
624}
625
Steven Morelandc1635952021-04-01 16:20:47 +0000626TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000627 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000628 std::string single = std::string(1024, 'a');
629 std::string doubled;
630 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
631 EXPECT_EQ(single + single, doubled);
632}
633
Steven Morelandc1635952021-04-01 16:20:47 +0000634TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000635 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000636
637 int32_t pingResult;
638 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
639 EXPECT_EQ(OK, pingResult);
640
641 EXPECT_EQ(0, MyBinderRpcSession::gNum);
642}
643
Steven Morelandc1635952021-04-01 16:20:47 +0000644TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000645 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000646
647 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
648 sp<IBinder> outBinder;
649 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
650 EXPECT_EQ(inBinder, outBinder);
651
652 wp<IBinder> weak = inBinder;
653 inBinder = nullptr;
654 outBinder = nullptr;
655
656 // Force reading a reply, to process any pending dec refs from the other
657 // process (the other process will process dec refs there before processing
658 // the ping here).
659 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
660
661 EXPECT_EQ(nullptr, weak.promote());
662
663 EXPECT_EQ(0, MyBinderRpcSession::gNum);
664}
665
Steven Morelandc1635952021-04-01 16:20:47 +0000666TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000667 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000668
669 sp<IBinderRpcSession> session;
670 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
671
672 sp<IBinder> inBinder = IInterface::asBinder(session);
673 sp<IBinder> outBinder;
674 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
675 EXPECT_EQ(inBinder, outBinder);
676
677 wp<IBinder> weak = inBinder;
678 session = nullptr;
679 inBinder = nullptr;
680 outBinder = nullptr;
681
682 // Force reading a reply, to process any pending dec refs from the other
683 // process (the other process will process dec refs there before processing
684 // the ping here).
685 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
686
687 EXPECT_EQ(nullptr, weak.promote());
688}
689
Steven Morelandc1635952021-04-01 16:20:47 +0000690TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000691 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000692
693 sp<IBinder> outBinder;
694 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
695 EXPECT_EQ(nullptr, outBinder);
696}
697
Steven Morelandc1635952021-04-01 16:20:47 +0000698TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000699 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000700
701 IBinder* ptr = nullptr;
702 {
703 sp<IBinder> binder = new BBinder();
704 ptr = binder.get();
705 EXPECT_OK(proc.rootIface->holdBinder(binder));
706 }
707
708 sp<IBinder> held;
709 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
710
711 EXPECT_EQ(held.get(), ptr);
712
713 // stop holding binder, because we test to make sure references are cleaned
714 // up
715 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
716 // and flush ref counts
717 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
718}
719
720// START TESTS FOR LIMITATIONS OF SOCKET BINDER
721// These are behavioral differences form regular binder, where certain usecases
722// aren't supported.
723
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000724TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000725 auto proc1 = createRpcTestSocketServerProcess({});
726 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000727
728 sp<IBinder> outBinder;
729 EXPECT_EQ(INVALID_OPERATION,
730 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
731}
732
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000733TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000734 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000735
736 sp<IBinder> outBinder;
737 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000738 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000739 .transactionError());
740}
741
Steven Morelandc1635952021-04-01 16:20:47 +0000742TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000743 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000744
745 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
746 sp<IBinder> outBinder;
747 EXPECT_EQ(INVALID_OPERATION,
748 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
749}
750
Steven Morelandc1635952021-04-01 16:20:47 +0000751TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000752 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000753
754 // for historical reasons, IServiceManager interface only returns the
755 // exception code
756 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
757 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
758}
759
760// END TESTS FOR LIMITATIONS OF SOCKET BINDER
761
Steven Morelandc1635952021-04-01 16:20:47 +0000762TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000763 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000764
765 sp<IBinder> outBinder;
766 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
767 EXPECT_EQ(proc.rootBinder, outBinder);
768}
769
Steven Morelandc1635952021-04-01 16:20:47 +0000770TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000771 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000772
773 auto nastyNester = sp<MyBinderRpcTest>::make();
774 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
775
776 wp<IBinder> weak = nastyNester;
777 nastyNester = nullptr;
778 EXPECT_EQ(nullptr, weak.promote());
779}
780
Steven Morelandc1635952021-04-01 16:20:47 +0000781TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000782 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000783
784 sp<IBinder> a;
785 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
786
787 sp<IBinder> b;
788 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
789
790 EXPECT_EQ(a, b);
791}
792
Steven Morelandc1635952021-04-01 16:20:47 +0000793TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000794 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000795
796 sp<IBinder> a;
797 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
798 wp<IBinder> weak = a;
799 a = nullptr;
800
801 sp<IBinder> b;
802 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
803
804 // this is the wrong behavior, since BpBinder
805 // doesn't implement onIncStrongAttempted
806 // but make sure there is no crash
807 EXPECT_EQ(nullptr, weak.promote());
808
809 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
810
811 // In order to fix this:
812 // - need to have incStrongAttempted reflected across IPC boundary (wait for
813 // response to promote - round trip...)
814 // - sendOnLastWeakRef, to delete entries out of RpcState table
815 EXPECT_EQ(b, weak.promote());
816}
817
818#define expectSessions(expected, iface) \
819 do { \
820 int session; \
821 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
822 EXPECT_EQ(expected, session); \
823 } while (false)
824
Steven Morelandc1635952021-04-01 16:20:47 +0000825TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000826 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000827
828 sp<IBinderRpcSession> session;
829 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
830 std::string out;
831 EXPECT_OK(session->getName(&out));
832 EXPECT_EQ("aoeu", out);
833
834 expectSessions(1, proc.rootIface);
835 session = nullptr;
836 expectSessions(0, proc.rootIface);
837}
838
Steven Morelandc1635952021-04-01 16:20:47 +0000839TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000840 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000841
842 std::vector<sp<IBinderRpcSession>> sessions;
843
844 for (size_t i = 0; i < 15; i++) {
845 expectSessions(i, proc.rootIface);
846 sp<IBinderRpcSession> session;
847 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
848 sessions.push_back(session);
849 }
850 expectSessions(sessions.size(), proc.rootIface);
851 for (size_t i = 0; i < sessions.size(); i++) {
852 std::string out;
853 EXPECT_OK(sessions.at(i)->getName(&out));
854 EXPECT_EQ(std::to_string(i), out);
855 }
856 expectSessions(sessions.size(), proc.rootIface);
857
858 while (!sessions.empty()) {
859 sessions.pop_back();
860 expectSessions(sessions.size(), proc.rootIface);
861 }
862 expectSessions(0, proc.rootIface);
863}
864
865size_t epochMillis() {
866 using std::chrono::duration_cast;
867 using std::chrono::milliseconds;
868 using std::chrono::seconds;
869 using std::chrono::system_clock;
870 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
871}
872
Steven Morelandc1635952021-04-01 16:20:47 +0000873TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000874 constexpr size_t kNumThreads = 10;
875
Steven Moreland4313d7e2021-07-15 23:41:22 +0000876 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000877
878 EXPECT_OK(proc.rootIface->lock());
879
880 // block all but one thread taking locks
881 std::vector<std::thread> ts;
882 for (size_t i = 0; i < kNumThreads - 1; i++) {
883 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
884 }
885
886 usleep(100000); // give chance for calls on other threads
887
888 // other calls still work
889 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
890
891 constexpr size_t blockTimeMs = 500;
892 size_t epochMsBefore = epochMillis();
893 // after this, we should never see a response within this time
894 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
895
896 // this call should be blocked for blockTimeMs
897 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
898
899 size_t epochMsAfter = epochMillis();
900 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
901
902 for (auto& t : ts) t.join();
903}
904
Steven Morelandc1635952021-04-01 16:20:47 +0000905TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000906 constexpr size_t kNumThreads = 10;
907 constexpr size_t kNumCalls = kNumThreads + 3;
908 constexpr size_t kSleepMs = 500;
909
Steven Moreland4313d7e2021-07-15 23:41:22 +0000910 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000911
912 size_t epochMsBefore = epochMillis();
913
914 std::vector<std::thread> ts;
915 for (size_t i = 0; i < kNumCalls; i++) {
916 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
917 }
918
919 for (auto& t : ts) t.join();
920
921 size_t epochMsAfter = epochMillis();
922
923 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
924
925 // Potential flake, but make sure calls are handled in parallel.
926 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
927}
928
Steven Morelandc1635952021-04-01 16:20:47 +0000929TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000930 constexpr size_t kNumClientThreads = 10;
931 constexpr size_t kNumServerThreads = 10;
932 constexpr size_t kNumCalls = 100;
933
Steven Moreland4313d7e2021-07-15 23:41:22 +0000934 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000935
936 std::vector<std::thread> threads;
937 for (size_t i = 0; i < kNumClientThreads; i++) {
938 threads.push_back(std::thread([&] {
939 for (size_t j = 0; j < kNumCalls; j++) {
940 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000941 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000942 EXPECT_EQ(proc.rootBinder, out);
943 }
944 }));
945 }
946
947 for (auto& t : threads) t.join();
948}
949
Steven Morelandc6046982021-04-20 00:49:42 +0000950TEST_P(BinderRpc, OnewayStressTest) {
951 constexpr size_t kNumClientThreads = 10;
952 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000953 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000954
Steven Moreland4313d7e2021-07-15 23:41:22 +0000955 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000956
957 std::vector<std::thread> threads;
958 for (size_t i = 0; i < kNumClientThreads; i++) {
959 threads.push_back(std::thread([&] {
960 for (size_t j = 0; j < kNumCalls; j++) {
961 EXPECT_OK(proc.rootIface->sendString("a"));
962 }
963
964 // check threads are not stuck
965 EXPECT_OK(proc.rootIface->sleepMs(250));
966 }));
967 }
968
969 for (auto& t : threads) t.join();
970}
971
Steven Morelandc1635952021-04-01 16:20:47 +0000972TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000973 constexpr size_t kReallyLongTimeMs = 100;
974 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
975
Steven Moreland4313d7e2021-07-15 23:41:22 +0000976 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000977
978 size_t epochMsBefore = epochMillis();
979
980 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
981
982 size_t epochMsAfter = epochMillis();
983 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
984}
985
Steven Morelandc1635952021-04-01 16:20:47 +0000986TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000987 constexpr size_t kNumSleeps = 10;
988 constexpr size_t kNumExtraServerThreads = 4;
989 constexpr size_t kSleepMs = 50;
990
991 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000992 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000993
994 EXPECT_OK(proc.rootIface->lock());
995
996 for (size_t i = 0; i < kNumSleeps; i++) {
997 // these should be processed serially
998 proc.rootIface->sleepMsAsync(kSleepMs);
999 }
1000 // should also be processesed serially
1001 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1002
1003 size_t epochMsBefore = epochMillis();
1004 EXPECT_OK(proc.rootIface->lockUnlock());
1005 size_t epochMsAfter = epochMillis();
1006
1007 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001008
1009 // pending oneway transactions hold ref, make sure we read data on all
1010 // sockets
1011 std::vector<std::thread> threads;
1012 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
1013 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
1014 }
1015 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +00001016}
1017
Steven Morelandd45be622021-06-04 02:19:37 +00001018TEST_P(BinderRpc, OnewayCallExhaustion) {
1019 constexpr size_t kNumClients = 2;
1020 constexpr size_t kTooLongMs = 1000;
1021
Steven Moreland4313d7e2021-07-15 23:41:22 +00001022 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001023
1024 // Build up oneway calls on the second session to make sure it terminates
1025 // and shuts down. The first session should be unaffected (proc destructor
1026 // checks the first session).
1027 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1028
1029 std::vector<std::thread> threads;
1030 for (size_t i = 0; i < kNumClients; i++) {
1031 // one of these threads will get stuck queueing a transaction once the
1032 // socket fills up, the other will be able to fill up transactions on
1033 // this object
1034 threads.push_back(std::thread([&] {
1035 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1036 }
1037 }));
1038 }
1039 for (auto& t : threads) t.join();
1040
1041 Status status = iface->sleepMsAsync(kTooLongMs);
1042 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1043
Steven Moreland798e0d12021-07-14 23:19:25 +00001044 // now that it has died, wait for the remote session to shutdown
1045 std::vector<int32_t> remoteCounts;
1046 do {
1047 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1048 } while (remoteCounts.size() == kNumClients);
1049
Steven Morelandd45be622021-06-04 02:19:37 +00001050 // the second session should be shutdown in the other process by the time we
1051 // are able to join above (it'll only be hung up once it finishes processing
1052 // any pending commands). We need to erase this session from the record
1053 // here, so that the destructor for our session won't check that this
1054 // session is valid, but we still want it to test the other session.
1055 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1056}
1057
Steven Moreland659416d2021-05-11 00:47:50 +00001058TEST_P(BinderRpc, Callbacks) {
1059 const static std::string kTestString = "good afternoon!";
1060
Steven Morelandc7d40132021-06-10 03:42:11 +00001061 for (bool callIsOneway : {true, false}) {
1062 for (bool callbackIsOneway : {true, false}) {
1063 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001064 auto proc = createRpcTestSocketServerProcess(
1065 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001066 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001067
Steven Morelandc7d40132021-06-10 03:42:11 +00001068 if (callIsOneway) {
1069 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1070 kTestString));
1071 } else {
1072 EXPECT_OK(
1073 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1074 }
Steven Moreland659416d2021-05-11 00:47:50 +00001075
Steven Morelandc7d40132021-06-10 03:42:11 +00001076 using std::literals::chrono_literals::operator""s;
1077 std::unique_lock<std::mutex> _l(cb->mMutex);
1078 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001079
Steven Morelandc7d40132021-06-10 03:42:11 +00001080 EXPECT_EQ(cb->mValues.size(), 1)
1081 << "callIsOneway: " << callIsOneway
1082 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1083 if (cb->mValues.empty()) continue;
1084 EXPECT_EQ(cb->mValues.at(0), kTestString)
1085 << "callIsOneway: " << callIsOneway
1086 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001087
Steven Morelandc7d40132021-06-10 03:42:11 +00001088 // since we are severing the connection, we need to go ahead and
1089 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001090 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1091 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1092 }
Steven Moreland659416d2021-05-11 00:47:50 +00001093
Steven Moreland1b304292021-07-15 22:59:34 +00001094 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001095 // need to manually shut it down
1096 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001097
Steven Morelandc7d40132021-06-10 03:42:11 +00001098 proc.expectAlreadyShutdown = true;
1099 }
Steven Moreland659416d2021-05-11 00:47:50 +00001100 }
1101 }
1102}
1103
Steven Moreland195edb82021-06-08 02:44:39 +00001104TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001105 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001106 auto cb = sp<MyBinderRpcCallback>::make();
1107
1108 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1109 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1110}
1111
Steven Morelandc1635952021-04-01 16:20:47 +00001112TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001113 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001114 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001115
1116 // make sure there is some state during crash
1117 // 1. we hold their binder
1118 sp<IBinderRpcSession> session;
1119 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1120 // 2. they hold our binder
1121 sp<IBinder> binder = new BBinder();
1122 EXPECT_OK(proc.rootIface->holdBinder(binder));
1123
1124 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1125 << "Do death cleanup: " << doDeathCleanup;
1126
Steven Morelandaf4ca712021-05-24 23:22:08 +00001127 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001128 }
1129}
1130
Steven Morelandd7302072021-05-15 01:32:04 +00001131TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001132 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001133
1134 // we can't allocate IPCThreadState so actually the first time should
1135 // succeed :(
1136 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1137
1138 // second time! we catch the error :)
1139 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1140
Steven Morelandaf4ca712021-05-24 23:22:08 +00001141 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001142}
1143
Steven Moreland37aff182021-03-26 02:04:16 +00001144TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001145 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001146
1147 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1148 ASSERT_NE(binder, nullptr);
1149
1150 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1151}
1152
1153TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001154 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001155
1156 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1157 ASSERT_NE(binder, nullptr);
1158
1159 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1160 ASSERT_NE(ndkBinder, nullptr);
1161
1162 std::string out;
1163 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1164 ASSERT_TRUE(status.isOk()) << status.getDescription();
1165 ASSERT_EQ("aoeuaoeu", out);
1166}
1167
Steven Moreland5553ac42020-11-11 02:14:45 +00001168ssize_t countFds() {
1169 DIR* dir = opendir("/proc/self/fd/");
1170 if (dir == nullptr) return -1;
1171 ssize_t ret = 0;
1172 dirent* ent;
1173 while ((ent = readdir(dir)) != nullptr) ret++;
1174 closedir(dir);
1175 return ret;
1176}
1177
Steven Morelandc1635952021-04-01 16:20:47 +00001178TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001179 ssize_t beforeFds = countFds();
1180 ASSERT_GE(beforeFds, 0);
1181 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001182 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001183 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1184 }
1185 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1186}
1187
Steven Morelandda573042021-06-12 01:13:45 +00001188static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001189 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001190 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001191 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001192 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1193 CHECK(server->setupVsockServer(vsockPort));
1194 server->start();
1195
Yifan Hong702115c2021-06-24 15:39:18 -07001196 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001197 bool okay = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001198 while (!server->shutdown()) usleep(10000);
Steven Morelandda573042021-06-12 01:13:45 +00001199 ALOGE("Detected vsock loopback supported: %d", okay);
1200 return okay;
1201}
1202
1203static std::vector<SocketType> testSocketTypes() {
Steven Moreland4198a122021-08-03 17:37:58 -07001204 std::vector<SocketType> ret = {SocketType::PRECONNECTED, SocketType::UNIX, SocketType::INET};
Steven Morelandda573042021-06-12 01:13:45 +00001205
1206 static bool hasVsockLoopback = testSupportVsockLoopback();
1207
1208 if (hasVsockLoopback) {
1209 ret.push_back(SocketType::VSOCK);
1210 }
1211
1212 return ret;
1213}
1214
Yifan Hong702115c2021-06-24 15:39:18 -07001215INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1216 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1217 ::testing::ValuesIn(RpcSecurityValues())),
1218 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001219
Yifan Hong702115c2021-06-24 15:39:18 -07001220class BinderRpcServerRootObject
1221 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001222
1223TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1224 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1225 auto setRootObject = [](bool isStrong) -> SetFn {
1226 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1227 };
1228
Yifan Hong702115c2021-06-24 15:39:18 -07001229 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1230 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001231 auto binder1 = sp<BBinder>::make();
1232 IBinder* binderRaw1 = binder1.get();
1233 setRootObject(isStrong1)(server.get(), binder1);
1234 EXPECT_EQ(binderRaw1, server->getRootObject());
1235 binder1.clear();
1236 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1237
1238 auto binder2 = sp<BBinder>::make();
1239 IBinder* binderRaw2 = binder2.get();
1240 setRootObject(isStrong2)(server.get(), binder2);
1241 EXPECT_EQ(binderRaw2, server->getRootObject());
1242 binder2.clear();
1243 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1244}
1245
1246INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001247 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1248 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001249
Yifan Hong1a235852021-05-13 16:07:47 -07001250class OneOffSignal {
1251public:
1252 // If notify() was previously called, or is called within |duration|, return true; else false.
1253 template <typename R, typename P>
1254 bool wait(std::chrono::duration<R, P> duration) {
1255 std::unique_lock<std::mutex> lock(mMutex);
1256 return mCv.wait_for(lock, duration, [this] { return mValue; });
1257 }
1258 void notify() {
1259 std::unique_lock<std::mutex> lock(mMutex);
1260 mValue = true;
1261 lock.unlock();
1262 mCv.notify_all();
1263 }
1264
1265private:
1266 std::mutex mMutex;
1267 std::condition_variable mCv;
1268 bool mValue = false;
1269};
1270
Yifan Hong702115c2021-06-24 15:39:18 -07001271TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001272 auto addr = allocateSocketAddress();
1273 unlink(addr.c_str());
Yifan Hong702115c2021-06-24 15:39:18 -07001274 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong1a235852021-05-13 16:07:47 -07001275 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1276 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1277 auto joinEnds = std::make_shared<OneOffSignal>();
1278
1279 // If things are broken and the thread never stops, don't block other tests. Because the thread
1280 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1281 // shared pointers are passed.
1282 std::thread([server, joinEnds] {
1283 server->join();
1284 joinEnds->notify();
1285 }).detach();
1286
1287 bool shutdown = false;
1288 for (int i = 0; i < 10 && !shutdown; i++) {
1289 usleep(300 * 1000); // 300ms; total 3s
1290 if (server->shutdown()) shutdown = true;
1291 }
1292 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1293
1294 ASSERT_TRUE(joinEnds->wait(2s))
1295 << "After server->shutdown() returns true, join() did not stop after 2s";
1296}
1297
Yifan Hong194acf22021-06-29 18:44:56 -07001298TEST(BinderRpc, Java) {
1299#if !defined(__ANDROID__)
1300 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1301 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1302 "to binderHostDeviceTest. Hence, just disable this test on host.";
1303#endif // !__ANDROID__
1304 sp<IServiceManager> sm = defaultServiceManager();
1305 ASSERT_NE(nullptr, sm);
1306 // Any Java service with non-empty getInterfaceDescriptor() would do.
1307 // Let's pick batteryproperties.
1308 auto binder = sm->checkService(String16("batteryproperties"));
1309 ASSERT_NE(nullptr, binder);
1310 auto descriptor = binder->getInterfaceDescriptor();
1311 ASSERT_GE(descriptor.size(), 0);
1312 ASSERT_EQ(OK, binder->pingBinder());
1313
1314 auto rpcServer = RpcServer::make();
1315 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1316 unsigned int port;
1317 ASSERT_TRUE(rpcServer->setupInetServer(0, &port));
1318 auto socket = rpcServer->releaseServer();
1319
1320 auto keepAlive = sp<BBinder>::make();
1321 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1322
1323 auto rpcSession = RpcSession::make();
1324 ASSERT_TRUE(rpcSession->setupInetClient("127.0.0.1", port));
1325 auto rpcBinder = rpcSession->getRootObject();
1326 ASSERT_NE(nullptr, rpcBinder);
1327
1328 ASSERT_EQ(OK, rpcBinder->pingBinder());
1329
1330 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1331 << "getInterfaceDescriptor should not crash system_server";
1332 ASSERT_EQ(OK, rpcBinder->pingBinder());
1333}
1334
Yifan Hong702115c2021-06-24 15:39:18 -07001335INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1336 BinderRpcSimple::PrintTestParam);
1337
Steven Morelandc1635952021-04-01 16:20:47 +00001338} // namespace android
1339
1340int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001341 ::testing::InitGoogleTest(&argc, argv);
1342 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1343 return RUN_ALL_TESTS();
1344}