blob: 35db4444d51f9a605b83e8d0880b59a5454dc78a [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>
Yifan Hong92409752021-07-30 21:25:32 -070034#include <binder/RpcTransportTls.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000035#include <gtest/gtest.h>
36
Steven Morelandc1635952021-04-01 16:20:47 +000037#include <chrono>
38#include <cstdlib>
39#include <iostream>
40#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000041#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000042
Steven Morelandc1635952021-04-01 16:20:47 +000043#include <sys/prctl.h>
44#include <unistd.h>
45
Steven Moreland4198a122021-08-03 17:37:58 -070046#include "../RpcSocketAddress.h" // for testing preconnected clients
Steven Morelandbd5002b2021-05-04 23:12:56 +000047#include "../RpcState.h" // for debugging
48#include "../vm_sockets.h" // for VMADDR_*
Steven Moreland5553ac42020-11-11 02:14:45 +000049
Yifan Hong1a235852021-05-13 16:07:47 -070050using namespace std::chrono_literals;
51
Steven Moreland5553ac42020-11-11 02:14:45 +000052namespace android {
53
Steven Morelandbf57bce2021-07-26 15:26:12 -070054static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
55 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Devin Mooref3b9c4f2021-08-03 15:50:13 +000056const char* kLocalInetAddress = "127.0.0.1";
Steven Morelandbf57bce2021-07-26 15:26:12 -070057
Yifan Hong92409752021-07-30 21:25:32 -070058enum class RpcSecurity { RAW, TLS };
Yifan Hong702115c2021-06-24 15:39:18 -070059
60static inline std::vector<RpcSecurity> RpcSecurityValues() {
Yifan Hong92409752021-07-30 21:25:32 -070061 return {RpcSecurity::RAW, RpcSecurity::TLS};
Yifan Hong702115c2021-06-24 15:39:18 -070062}
63
64static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(RpcSecurity rpcSecurity) {
65 switch (rpcSecurity) {
66 case RpcSecurity::RAW:
67 return RpcTransportCtxFactoryRaw::make();
Yifan Hong92409752021-07-30 21:25:32 -070068 case RpcSecurity::TLS:
69 return RpcTransportCtxFactoryTls::make();
Yifan Hong702115c2021-06-24 15:39:18 -070070 default:
71 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
72 }
73}
74
Steven Moreland1fda67b2021-04-02 18:35:50 +000075TEST(BinderRpcParcel, EntireParcelFormatted) {
76 Parcel p;
77 p.writeInt32(3);
78
79 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
80}
81
Yifan Hong702115c2021-06-24 15:39:18 -070082class BinderRpcSimple : public ::testing::TestWithParam<RpcSecurity> {
83public:
84 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
85 return newFactory(info.param)->toCString();
86 }
87};
88
89TEST_P(BinderRpcSimple, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -070090 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
91 int sinkFd = sink.get();
Yifan Hong702115c2021-06-24 15:39:18 -070092 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -070093 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
94 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -070095 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -070096 ASSERT_TRUE(server->hasServer());
97 base::unique_fd retrieved = server->releaseServer();
98 ASSERT_FALSE(server->hasServer());
99 ASSERT_EQ(sinkFd, retrieved.get());
100}
101
Steven Morelandbf57bce2021-07-26 15:26:12 -0700102TEST(BinderRpc, CannotUseNextWireVersion) {
103 auto session = RpcSession::make();
104 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
105 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
106 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
107 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
108}
109
110TEST(BinderRpc, CanUseExperimentalWireVersion) {
111 auto session = RpcSession::make();
112 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
113}
114
Steven Moreland5553ac42020-11-11 02:14:45 +0000115using android::binder::Status;
116
117#define EXPECT_OK(status) \
118 do { \
119 Status stat = (status); \
120 EXPECT_TRUE(stat.isOk()) << stat; \
121 } while (false)
122
123class MyBinderRpcSession : public BnBinderRpcSession {
124public:
125 static std::atomic<int32_t> gNum;
126
127 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
128 Status getName(std::string* name) override {
129 *name = mName;
130 return Status::ok();
131 }
132 ~MyBinderRpcSession() { gNum--; }
133
134private:
135 std::string mName;
136};
137std::atomic<int32_t> MyBinderRpcSession::gNum;
138
Steven Moreland659416d2021-05-11 00:47:50 +0000139class MyBinderRpcCallback : public BnBinderRpcCallback {
140 Status sendCallback(const std::string& value) {
141 std::unique_lock _l(mMutex);
142 mValues.push_back(value);
143 _l.unlock();
144 mCv.notify_one();
145 return Status::ok();
146 }
147 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
148
149public:
150 std::mutex mMutex;
151 std::condition_variable mCv;
152 std::vector<std::string> mValues;
153};
154
Steven Moreland5553ac42020-11-11 02:14:45 +0000155class MyBinderRpcTest : public BnBinderRpcTest {
156public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000157 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +0000158
159 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000160 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000161 return Status::ok();
162 }
163 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000164 *strstr = str + str;
165 return Status::ok();
166 }
Steven Moreland736664b2021-05-01 04:27:25 +0000167 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000168 sp<RpcServer> spServer = server.promote();
169 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000170 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
171 }
Steven Moreland736664b2021-05-01 04:27:25 +0000172 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000173 for (auto session : spServer->listSessions()) {
174 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000175 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000176 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000177 return Status::ok();
178 }
179 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
180 if (binder == nullptr) {
181 std::cout << "Received null binder!" << std::endl;
182 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
183 }
184 *out = binder->pingBinder();
185 return Status::ok();
186 }
187 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
188 *out = binder;
189 return Status::ok();
190 }
191 static sp<IBinder> mHeldBinder;
192 Status holdBinder(const sp<IBinder>& binder) override {
193 mHeldBinder = binder;
194 return Status::ok();
195 }
196 Status getHeldBinder(sp<IBinder>* held) override {
197 *held = mHeldBinder;
198 return Status::ok();
199 }
200 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
201 if (count <= 0) return Status::ok();
202 return binder->nestMe(this, count - 1);
203 }
204 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
205 static sp<IBinder> binder = new BBinder;
206 *out = binder;
207 return Status::ok();
208 }
209 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
210 *out = new MyBinderRpcSession(name);
211 return Status::ok();
212 }
213 Status getNumOpenSessions(int32_t* out) override {
214 *out = MyBinderRpcSession::gNum;
215 return Status::ok();
216 }
217
218 std::mutex blockMutex;
219 Status lock() override {
220 blockMutex.lock();
221 return Status::ok();
222 }
223 Status unlockInMsAsync(int32_t ms) override {
224 usleep(ms * 1000);
225 blockMutex.unlock();
226 return Status::ok();
227 }
228 Status lockUnlock() override {
229 std::lock_guard<std::mutex> _l(blockMutex);
230 return Status::ok();
231 }
232
233 Status sleepMs(int32_t ms) override {
234 usleep(ms * 1000);
235 return Status::ok();
236 }
237
238 Status sleepMsAsync(int32_t ms) override {
239 // In-process binder calls are asynchronous, but the call to this method
240 // is synchronous wrt its client. This in/out-process threading model
241 // diffentiation is a classic binder leaky abstraction (for better or
242 // worse) and is preserved here the way binder sockets plugs itself
243 // into BpBinder, as nothing is changed at the higher levels
244 // (IInterface) which result in this behavior.
245 return sleepMs(ms);
246 }
247
Steven Moreland659416d2021-05-11 00:47:50 +0000248 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
249 const std::string& value) override {
250 if (callback == nullptr) {
251 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
252 }
253
254 if (delayed) {
255 std::thread([=]() {
256 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000257 Status status = doCallback(callback, oneway, false, value);
258 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000259 }).detach();
260 return Status::ok();
261 }
262
263 if (oneway) {
264 return callback->sendOnewayCallback(value);
265 }
266
267 return callback->sendCallback(value);
268 }
269
Steven Morelandc7d40132021-06-10 03:42:11 +0000270 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
271 const std::string& value) override {
272 return doCallback(callback, oneway, delayed, value);
273 }
274
Steven Moreland5553ac42020-11-11 02:14:45 +0000275 Status die(bool cleanup) override {
276 if (cleanup) {
277 exit(1);
278 } else {
279 _exit(1);
280 }
281 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000282
283 Status scheduleShutdown() override {
284 sp<RpcServer> strongServer = server.promote();
285 if (strongServer == nullptr) {
286 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
287 }
288 std::thread([=] {
289 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
290 }).detach();
291 return Status::ok();
292 }
293
Steven Morelandd7302072021-05-15 01:32:04 +0000294 Status useKernelBinderCallingId() override {
295 // this is WRONG! It does not make sense when using RPC binder, and
296 // because it is SO wrong, and so much code calls this, it should abort!
297
298 (void)IPCThreadState::self()->getCallingPid();
299 return Status::ok();
300 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000301};
302sp<IBinder> MyBinderRpcTest::mHeldBinder;
303
304class Process {
305public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700306 Process(Process&&) = default;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700307 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */)>& f) {
308 android::base::unique_fd writeEnd;
309 CHECK(android::base::Pipe(&mReadEnd, &writeEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000310 if (0 == (mPid = fork())) {
311 // racey: assume parent doesn't crash before this is set
312 prctl(PR_SET_PDEATHSIG, SIGHUP);
313
Yifan Hong0f58fb92021-06-16 16:09:23 -0700314 f(writeEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000315
316 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000317 }
318 }
319 ~Process() {
320 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000321 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000322 }
323 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700324 android::base::borrowed_fd readEnd() { return mReadEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000325
326private:
327 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700328 android::base::unique_fd mReadEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000329};
330
331static std::string allocateSocketAddress() {
332 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000333 std::string temp = getenv("TMPDIR") ?: "/tmp";
334 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000335};
336
Steven Morelandda573042021-06-12 01:13:45 +0000337static unsigned int allocateVsockPort() {
338 static unsigned int vsockPort = 3456;
339 return vsockPort++;
340}
341
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000342struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000343 // reference to process hosting a socket server
344 Process host;
345
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000346 struct SessionInfo {
347 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000348 sp<IBinder> root;
349 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000350
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000351 // client session objects associated with other process
352 // each one represents a separate session
353 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000354
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000355 ProcessSession(ProcessSession&&) = default;
356 ~ProcessSession() {
357 for (auto& session : sessions) {
358 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000359 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000360
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000361 for (auto& info : sessions) {
362 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000363
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000364 EXPECT_NE(nullptr, session);
365 EXPECT_NE(nullptr, session->state());
366 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000367
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000368 wp<RpcSession> weakSession = session;
369 session = nullptr;
370 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000371 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000372 }
373};
374
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000375// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000376// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000377struct BinderRpcTestProcessSession {
378 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000379
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000380 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000381 sp<IBinder> rootBinder;
382
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000383 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000384 sp<IBinderRpcTest> rootIface;
385
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000386 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000387 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000388
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000389 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
390 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000391 EXPECT_NE(nullptr, rootIface);
392 if (rootIface == nullptr) return;
393
Steven Morelandaf4ca712021-05-24 23:22:08 +0000394 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000395 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000396 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000397 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000398 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000399 for (auto remoteCount : remoteCounts) {
400 EXPECT_EQ(remoteCount, 1);
401 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000402
Steven Moreland798e0d12021-07-14 23:19:25 +0000403 // even though it is on another thread, shutdown races with
404 // the transaction reply being written
405 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
406 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
407 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000408 }
409
410 rootIface = nullptr;
411 rootBinder = nullptr;
412 }
413};
414
Steven Morelandc1635952021-04-01 16:20:47 +0000415enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700416 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000417 UNIX,
418 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700419 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000420};
Yifan Hong702115c2021-06-24 15:39:18 -0700421static inline std::string PrintToString(SocketType socketType) {
422 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700423 case SocketType::PRECONNECTED:
424 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000425 case SocketType::UNIX:
426 return "unix_domain_socket";
427 case SocketType::VSOCK:
428 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700429 case SocketType::INET:
430 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000431 default:
432 LOG_ALWAYS_FATAL("Unknown socket type");
433 return "";
434 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000435}
Steven Morelandda573042021-06-12 01:13:45 +0000436
Steven Moreland4198a122021-08-03 17:37:58 -0700437static base::unique_fd connectToUds(const char* addrStr) {
438 UnixSocketAddress addr(addrStr);
439 base::unique_fd serverFd(
440 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
441 int savedErrno = errno;
442 CHECK(serverFd.ok()) << "Could not create socket " << addrStr << ": " << strerror(savedErrno);
443
444 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
445 int savedErrno = errno;
446 LOG(FATAL) << "Could not connect to socket " << addrStr << ": " << strerror(savedErrno);
447 }
448 return serverFd;
449}
450
Yifan Hong702115c2021-06-24 15:39:18 -0700451class BinderRpc : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000452public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000453 struct Options {
454 size_t numThreads = 1;
455 size_t numSessions = 1;
456 size_t numIncomingConnections = 0;
457 };
458
Yifan Hong702115c2021-06-24 15:39:18 -0700459 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
460 auto [type, security] = info.param;
461 return PrintToString(type) + "_" + newFactory(security)->toCString();
462 }
463
Steven Morelandc1635952021-04-01 16:20:47 +0000464 // This creates a new process serving an interface on a certain number of
465 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000466 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000467 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
468 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000469
Yifan Hong702115c2021-06-24 15:39:18 -0700470 SocketType socketType = std::get<0>(GetParam());
471 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000472
Steven Morelandda573042021-06-12 01:13:45 +0000473 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000474 std::string addr = allocateSocketAddress();
475 unlink(addr.c_str());
Steven Morelandc1635952021-04-01 16:20:47 +0000476
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000477 auto ret = ProcessSession{
Yifan Hong0f58fb92021-06-16 16:09:23 -0700478 .host = Process([&](android::base::borrowed_fd writeEnd) {
Yifan Hong702115c2021-06-24 15:39:18 -0700479 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity));
Steven Morelandc1635952021-04-01 16:20:47 +0000480
481 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000482 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000483
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000484 unsigned int outPort = 0;
485
Steven Morelandc1635952021-04-01 16:20:47 +0000486 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700487 case SocketType::PRECONNECTED:
488 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000489 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700490 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000491 break;
492 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700493 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000494 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700495 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700496 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700497 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700498 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700499 }
Steven Morelandc1635952021-04-01 16:20:47 +0000500 default:
501 LOG_ALWAYS_FATAL("Unknown socket type");
502 }
503
Yifan Hong0f58fb92021-06-16 16:09:23 -0700504 CHECK(android::base::WriteFully(writeEnd, &outPort, sizeof(outPort)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000505
Steven Moreland611d15f2021-05-01 01:28:27 +0000506 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000507
Steven Morelandf137de92021-04-24 01:54:26 +0000508 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000509
510 // Another thread calls shutdown. Wait for it to complete.
511 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000512 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000513 };
514
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000515 // always read socket, so that we have waited for the server to start
516 unsigned int outPort = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700517 CHECK(android::base::ReadFully(ret.host.readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700518 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000519 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700520 }
521
Steven Moreland2372f9d2021-08-05 15:42:01 -0700522 status_t status;
523
Steven Moreland4313d7e2021-07-15 23:41:22 +0000524 for (size_t i = 0; i < options.numSessions; i++) {
Yifan Hong702115c2021-06-24 15:39:18 -0700525 sp<RpcSession> session = RpcSession::make(newFactory(rpcSecurity));
Steven Moreland4313d7e2021-07-15 23:41:22 +0000526 session->setMaxThreads(options.numIncomingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000527
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000528 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700529 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700530 status = session->setupPreconnectedClient({}, [=]() {
531 return connectToUds(addr.c_str());
532 });
533 if (status == OK) goto success;
Steven Moreland4198a122021-08-03 17:37:58 -0700534 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000535 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700536 status = session->setupUnixDomainClient(addr.c_str());
537 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000538 break;
539 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700540 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
541 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000542 break;
543 case SocketType::INET:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700544 status = session->setupInetClient("127.0.0.1", outPort);
545 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000546 break;
547 default:
548 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000549 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700550 LOG_ALWAYS_FATAL("Could not connect %s", statusToString(status).c_str());
Steven Moreland736664b2021-05-01 04:27:25 +0000551 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000552 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000553 }
Steven Morelandc1635952021-04-01 16:20:47 +0000554 return ret;
555 }
556
Steven Moreland4313d7e2021-07-15 23:41:22 +0000557 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000558 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000559 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000560 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000561 sp<MyBinderRpcTest> service =
562 new MyBinderRpcTest;
563 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000564 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000565 }),
566 };
567
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000568 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000569 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
570
571 return ret;
572 }
573};
574
Steven Morelandc1635952021-04-01 16:20:47 +0000575TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000576 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000577 ASSERT_NE(proc.rootBinder, nullptr);
578 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
579}
580
Steven Moreland4cf688f2021-03-31 01:48:58 +0000581TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000582 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000583 ASSERT_NE(proc.rootBinder, nullptr);
584 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
585}
586
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000587TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000588 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000589 for (auto session : proc.proc.sessions) {
590 ASSERT_NE(nullptr, session.root);
591 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000592 }
593}
594
Steven Morelandc1635952021-04-01 16:20:47 +0000595TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000596 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000597 Parcel data;
598 Parcel reply;
599 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
600}
601
Steven Moreland67753c32021-04-02 18:45:19 +0000602TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000603 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000604
605 Parcel p1;
606 p1.markForBinder(proc.rootBinder);
607 p1.writeInt32(3);
608
609 Parcel p2;
610
611 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
612 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
613}
614
Steven Morelandc1635952021-04-01 16:20:47 +0000615TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000616 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000617 Parcel data;
618 data.markForBinder(proc.rootBinder);
619 Parcel reply;
620 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
621}
622
Steven Morelandc1635952021-04-01 16:20:47 +0000623TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000624 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000625 EXPECT_OK(proc.rootIface->sendString("asdf"));
626}
627
Steven Morelandc1635952021-04-01 16:20:47 +0000628TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000629 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000630 std::string doubled;
631 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
632 EXPECT_EQ("cool cool ", doubled);
633}
634
Steven Morelandc1635952021-04-01 16:20:47 +0000635TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000636 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000637 std::string single = std::string(1024, 'a');
638 std::string doubled;
639 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
640 EXPECT_EQ(single + single, doubled);
641}
642
Steven Morelandc1635952021-04-01 16:20:47 +0000643TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000644 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000645
646 int32_t pingResult;
647 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
648 EXPECT_EQ(OK, pingResult);
649
650 EXPECT_EQ(0, MyBinderRpcSession::gNum);
651}
652
Steven Morelandc1635952021-04-01 16:20:47 +0000653TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000654 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000655
656 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
657 sp<IBinder> outBinder;
658 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
659 EXPECT_EQ(inBinder, outBinder);
660
661 wp<IBinder> weak = inBinder;
662 inBinder = nullptr;
663 outBinder = nullptr;
664
665 // Force reading a reply, to process any pending dec refs from the other
666 // process (the other process will process dec refs there before processing
667 // the ping here).
668 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
669
670 EXPECT_EQ(nullptr, weak.promote());
671
672 EXPECT_EQ(0, MyBinderRpcSession::gNum);
673}
674
Steven Morelandc1635952021-04-01 16:20:47 +0000675TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000676 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000677
678 sp<IBinderRpcSession> session;
679 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
680
681 sp<IBinder> inBinder = IInterface::asBinder(session);
682 sp<IBinder> outBinder;
683 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
684 EXPECT_EQ(inBinder, outBinder);
685
686 wp<IBinder> weak = inBinder;
687 session = nullptr;
688 inBinder = nullptr;
689 outBinder = nullptr;
690
691 // Force reading a reply, to process any pending dec refs from the other
692 // process (the other process will process dec refs there before processing
693 // the ping here).
694 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
695
696 EXPECT_EQ(nullptr, weak.promote());
697}
698
Steven Morelandc1635952021-04-01 16:20:47 +0000699TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000700 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000701
702 sp<IBinder> outBinder;
703 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
704 EXPECT_EQ(nullptr, outBinder);
705}
706
Steven Morelandc1635952021-04-01 16:20:47 +0000707TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000708 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000709
710 IBinder* ptr = nullptr;
711 {
712 sp<IBinder> binder = new BBinder();
713 ptr = binder.get();
714 EXPECT_OK(proc.rootIface->holdBinder(binder));
715 }
716
717 sp<IBinder> held;
718 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
719
720 EXPECT_EQ(held.get(), ptr);
721
722 // stop holding binder, because we test to make sure references are cleaned
723 // up
724 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
725 // and flush ref counts
726 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
727}
728
729// START TESTS FOR LIMITATIONS OF SOCKET BINDER
730// These are behavioral differences form regular binder, where certain usecases
731// aren't supported.
732
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000733TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000734 auto proc1 = createRpcTestSocketServerProcess({});
735 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000736
737 sp<IBinder> outBinder;
738 EXPECT_EQ(INVALID_OPERATION,
739 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
740}
741
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000742TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000743 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000744
745 sp<IBinder> outBinder;
746 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000747 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000748 .transactionError());
749}
750
Steven Morelandc1635952021-04-01 16:20:47 +0000751TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000752 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000753
754 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
755 sp<IBinder> outBinder;
756 EXPECT_EQ(INVALID_OPERATION,
757 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
758}
759
Steven Morelandc1635952021-04-01 16:20:47 +0000760TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000761 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000762
763 // for historical reasons, IServiceManager interface only returns the
764 // exception code
765 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
766 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
767}
768
769// END TESTS FOR LIMITATIONS OF SOCKET BINDER
770
Steven Morelandc1635952021-04-01 16:20:47 +0000771TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000772 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000773
774 sp<IBinder> outBinder;
775 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
776 EXPECT_EQ(proc.rootBinder, outBinder);
777}
778
Steven Morelandc1635952021-04-01 16:20:47 +0000779TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000780 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000781
782 auto nastyNester = sp<MyBinderRpcTest>::make();
783 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
784
785 wp<IBinder> weak = nastyNester;
786 nastyNester = nullptr;
787 EXPECT_EQ(nullptr, weak.promote());
788}
789
Steven Morelandc1635952021-04-01 16:20:47 +0000790TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000791 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000792
793 sp<IBinder> a;
794 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
795
796 sp<IBinder> b;
797 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
798
799 EXPECT_EQ(a, b);
800}
801
Steven Morelandc1635952021-04-01 16:20:47 +0000802TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000803 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000804
805 sp<IBinder> a;
806 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
807 wp<IBinder> weak = a;
808 a = nullptr;
809
810 sp<IBinder> b;
811 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
812
813 // this is the wrong behavior, since BpBinder
814 // doesn't implement onIncStrongAttempted
815 // but make sure there is no crash
816 EXPECT_EQ(nullptr, weak.promote());
817
818 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
819
820 // In order to fix this:
821 // - need to have incStrongAttempted reflected across IPC boundary (wait for
822 // response to promote - round trip...)
823 // - sendOnLastWeakRef, to delete entries out of RpcState table
824 EXPECT_EQ(b, weak.promote());
825}
826
827#define expectSessions(expected, iface) \
828 do { \
829 int session; \
830 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
831 EXPECT_EQ(expected, session); \
832 } while (false)
833
Steven Morelandc1635952021-04-01 16:20:47 +0000834TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000835 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000836
837 sp<IBinderRpcSession> session;
838 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
839 std::string out;
840 EXPECT_OK(session->getName(&out));
841 EXPECT_EQ("aoeu", out);
842
843 expectSessions(1, proc.rootIface);
844 session = nullptr;
845 expectSessions(0, proc.rootIface);
846}
847
Steven Morelandc1635952021-04-01 16:20:47 +0000848TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000849 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000850
851 std::vector<sp<IBinderRpcSession>> sessions;
852
853 for (size_t i = 0; i < 15; i++) {
854 expectSessions(i, proc.rootIface);
855 sp<IBinderRpcSession> session;
856 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
857 sessions.push_back(session);
858 }
859 expectSessions(sessions.size(), proc.rootIface);
860 for (size_t i = 0; i < sessions.size(); i++) {
861 std::string out;
862 EXPECT_OK(sessions.at(i)->getName(&out));
863 EXPECT_EQ(std::to_string(i), out);
864 }
865 expectSessions(sessions.size(), proc.rootIface);
866
867 while (!sessions.empty()) {
868 sessions.pop_back();
869 expectSessions(sessions.size(), proc.rootIface);
870 }
871 expectSessions(0, proc.rootIface);
872}
873
874size_t epochMillis() {
875 using std::chrono::duration_cast;
876 using std::chrono::milliseconds;
877 using std::chrono::seconds;
878 using std::chrono::system_clock;
879 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
880}
881
Steven Morelandc1635952021-04-01 16:20:47 +0000882TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000883 constexpr size_t kNumThreads = 10;
884
Steven Moreland4313d7e2021-07-15 23:41:22 +0000885 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000886
887 EXPECT_OK(proc.rootIface->lock());
888
889 // block all but one thread taking locks
890 std::vector<std::thread> ts;
891 for (size_t i = 0; i < kNumThreads - 1; i++) {
892 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
893 }
894
895 usleep(100000); // give chance for calls on other threads
896
897 // other calls still work
898 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
899
900 constexpr size_t blockTimeMs = 500;
901 size_t epochMsBefore = epochMillis();
902 // after this, we should never see a response within this time
903 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
904
905 // this call should be blocked for blockTimeMs
906 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
907
908 size_t epochMsAfter = epochMillis();
909 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
910
911 for (auto& t : ts) t.join();
912}
913
Steven Morelandc1635952021-04-01 16:20:47 +0000914TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000915 constexpr size_t kNumThreads = 10;
916 constexpr size_t kNumCalls = kNumThreads + 3;
917 constexpr size_t kSleepMs = 500;
918
Steven Moreland4313d7e2021-07-15 23:41:22 +0000919 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000920
921 size_t epochMsBefore = epochMillis();
922
923 std::vector<std::thread> ts;
924 for (size_t i = 0; i < kNumCalls; i++) {
925 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
926 }
927
928 for (auto& t : ts) t.join();
929
930 size_t epochMsAfter = epochMillis();
931
932 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
933
934 // Potential flake, but make sure calls are handled in parallel.
935 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
936}
937
Steven Morelandc1635952021-04-01 16:20:47 +0000938TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000939 constexpr size_t kNumClientThreads = 10;
940 constexpr size_t kNumServerThreads = 10;
941 constexpr size_t kNumCalls = 100;
942
Steven Moreland4313d7e2021-07-15 23:41:22 +0000943 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000944
945 std::vector<std::thread> threads;
946 for (size_t i = 0; i < kNumClientThreads; i++) {
947 threads.push_back(std::thread([&] {
948 for (size_t j = 0; j < kNumCalls; j++) {
949 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000950 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000951 EXPECT_EQ(proc.rootBinder, out);
952 }
953 }));
954 }
955
956 for (auto& t : threads) t.join();
957}
958
Steven Morelandc6046982021-04-20 00:49:42 +0000959TEST_P(BinderRpc, OnewayStressTest) {
960 constexpr size_t kNumClientThreads = 10;
961 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000962 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000963
Steven Moreland4313d7e2021-07-15 23:41:22 +0000964 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000965
966 std::vector<std::thread> threads;
967 for (size_t i = 0; i < kNumClientThreads; i++) {
968 threads.push_back(std::thread([&] {
969 for (size_t j = 0; j < kNumCalls; j++) {
970 EXPECT_OK(proc.rootIface->sendString("a"));
971 }
972
973 // check threads are not stuck
974 EXPECT_OK(proc.rootIface->sleepMs(250));
975 }));
976 }
977
978 for (auto& t : threads) t.join();
979}
980
Steven Morelandc1635952021-04-01 16:20:47 +0000981TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000982 constexpr size_t kReallyLongTimeMs = 100;
983 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
984
Steven Moreland4313d7e2021-07-15 23:41:22 +0000985 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000986
987 size_t epochMsBefore = epochMillis();
988
989 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
990
991 size_t epochMsAfter = epochMillis();
992 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
993}
994
Steven Morelandc1635952021-04-01 16:20:47 +0000995TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000996 constexpr size_t kNumSleeps = 10;
997 constexpr size_t kNumExtraServerThreads = 4;
998 constexpr size_t kSleepMs = 50;
999
1000 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001001 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001002
1003 EXPECT_OK(proc.rootIface->lock());
1004
1005 for (size_t i = 0; i < kNumSleeps; i++) {
1006 // these should be processed serially
1007 proc.rootIface->sleepMsAsync(kSleepMs);
1008 }
1009 // should also be processesed serially
1010 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1011
1012 size_t epochMsBefore = epochMillis();
1013 EXPECT_OK(proc.rootIface->lockUnlock());
1014 size_t epochMsAfter = epochMillis();
1015
1016 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001017
1018 // pending oneway transactions hold ref, make sure we read data on all
1019 // sockets
1020 std::vector<std::thread> threads;
1021 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
1022 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
1023 }
1024 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +00001025}
1026
Steven Morelandd45be622021-06-04 02:19:37 +00001027TEST_P(BinderRpc, OnewayCallExhaustion) {
1028 constexpr size_t kNumClients = 2;
1029 constexpr size_t kTooLongMs = 1000;
1030
Steven Moreland4313d7e2021-07-15 23:41:22 +00001031 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001032
1033 // Build up oneway calls on the second session to make sure it terminates
1034 // and shuts down. The first session should be unaffected (proc destructor
1035 // checks the first session).
1036 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1037
1038 std::vector<std::thread> threads;
1039 for (size_t i = 0; i < kNumClients; i++) {
1040 // one of these threads will get stuck queueing a transaction once the
1041 // socket fills up, the other will be able to fill up transactions on
1042 // this object
1043 threads.push_back(std::thread([&] {
1044 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1045 }
1046 }));
1047 }
1048 for (auto& t : threads) t.join();
1049
1050 Status status = iface->sleepMsAsync(kTooLongMs);
1051 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1052
Steven Moreland798e0d12021-07-14 23:19:25 +00001053 // now that it has died, wait for the remote session to shutdown
1054 std::vector<int32_t> remoteCounts;
1055 do {
1056 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1057 } while (remoteCounts.size() == kNumClients);
1058
Steven Morelandd45be622021-06-04 02:19:37 +00001059 // the second session should be shutdown in the other process by the time we
1060 // are able to join above (it'll only be hung up once it finishes processing
1061 // any pending commands). We need to erase this session from the record
1062 // here, so that the destructor for our session won't check that this
1063 // session is valid, but we still want it to test the other session.
1064 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1065}
1066
Steven Moreland659416d2021-05-11 00:47:50 +00001067TEST_P(BinderRpc, Callbacks) {
1068 const static std::string kTestString = "good afternoon!";
1069
Steven Morelandc7d40132021-06-10 03:42:11 +00001070 for (bool callIsOneway : {true, false}) {
1071 for (bool callbackIsOneway : {true, false}) {
1072 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001073 auto proc = createRpcTestSocketServerProcess(
1074 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001075 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001076
Steven Morelandc7d40132021-06-10 03:42:11 +00001077 if (callIsOneway) {
1078 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1079 kTestString));
1080 } else {
1081 EXPECT_OK(
1082 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1083 }
Steven Moreland659416d2021-05-11 00:47:50 +00001084
Steven Morelandc7d40132021-06-10 03:42:11 +00001085 using std::literals::chrono_literals::operator""s;
1086 std::unique_lock<std::mutex> _l(cb->mMutex);
1087 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001088
Steven Morelandc7d40132021-06-10 03:42:11 +00001089 EXPECT_EQ(cb->mValues.size(), 1)
1090 << "callIsOneway: " << callIsOneway
1091 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1092 if (cb->mValues.empty()) continue;
1093 EXPECT_EQ(cb->mValues.at(0), kTestString)
1094 << "callIsOneway: " << callIsOneway
1095 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001096
Steven Morelandc7d40132021-06-10 03:42:11 +00001097 // since we are severing the connection, we need to go ahead and
1098 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001099 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1100 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1101 }
Steven Moreland659416d2021-05-11 00:47:50 +00001102
Steven Moreland1b304292021-07-15 22:59:34 +00001103 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001104 // need to manually shut it down
1105 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001106
Steven Morelandc7d40132021-06-10 03:42:11 +00001107 proc.expectAlreadyShutdown = true;
1108 }
Steven Moreland659416d2021-05-11 00:47:50 +00001109 }
1110 }
1111}
1112
Steven Moreland195edb82021-06-08 02:44:39 +00001113TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001114 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001115 auto cb = sp<MyBinderRpcCallback>::make();
1116
1117 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1118 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1119}
1120
Steven Morelandc1635952021-04-01 16:20:47 +00001121TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001122 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001123 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001124
1125 // make sure there is some state during crash
1126 // 1. we hold their binder
1127 sp<IBinderRpcSession> session;
1128 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1129 // 2. they hold our binder
1130 sp<IBinder> binder = new BBinder();
1131 EXPECT_OK(proc.rootIface->holdBinder(binder));
1132
1133 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1134 << "Do death cleanup: " << doDeathCleanup;
1135
Steven Morelandaf4ca712021-05-24 23:22:08 +00001136 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001137 }
1138}
1139
Steven Morelandd7302072021-05-15 01:32:04 +00001140TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001141 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001142
1143 // we can't allocate IPCThreadState so actually the first time should
1144 // succeed :(
1145 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1146
1147 // second time! we catch the error :)
1148 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1149
Steven Morelandaf4ca712021-05-24 23:22:08 +00001150 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001151}
1152
Steven Moreland37aff182021-03-26 02:04:16 +00001153TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
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 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1160}
1161
1162TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001163 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001164
1165 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1166 ASSERT_NE(binder, nullptr);
1167
1168 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1169 ASSERT_NE(ndkBinder, nullptr);
1170
1171 std::string out;
1172 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1173 ASSERT_TRUE(status.isOk()) << status.getDescription();
1174 ASSERT_EQ("aoeuaoeu", out);
1175}
1176
Steven Moreland5553ac42020-11-11 02:14:45 +00001177ssize_t countFds() {
1178 DIR* dir = opendir("/proc/self/fd/");
1179 if (dir == nullptr) return -1;
1180 ssize_t ret = 0;
1181 dirent* ent;
1182 while ((ent = readdir(dir)) != nullptr) ret++;
1183 closedir(dir);
1184 return ret;
1185}
1186
Steven Morelandc1635952021-04-01 16:20:47 +00001187TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001188 ssize_t beforeFds = countFds();
1189 ASSERT_GE(beforeFds, 0);
1190 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001191 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001192 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1193 }
1194 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1195}
1196
Steven Morelandda573042021-06-12 01:13:45 +00001197static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001198 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001199 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001200 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001201 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland1eab3452021-08-05 16:56:20 -07001202 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1203 if (status == -EAFNOSUPPORT) {
1204 return false;
1205 }
1206 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1207 }
Steven Morelandda573042021-06-12 01:13:45 +00001208 server->start();
1209
Yifan Hong702115c2021-06-24 15:39:18 -07001210 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001211 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001212 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001213 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1214 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001215}
1216
1217static std::vector<SocketType> testSocketTypes() {
Steven Moreland4198a122021-08-03 17:37:58 -07001218 std::vector<SocketType> ret = {SocketType::PRECONNECTED, SocketType::UNIX, SocketType::INET};
Steven Morelandda573042021-06-12 01:13:45 +00001219
1220 static bool hasVsockLoopback = testSupportVsockLoopback();
1221
1222 if (hasVsockLoopback) {
1223 ret.push_back(SocketType::VSOCK);
1224 }
1225
1226 return ret;
1227}
1228
Yifan Hong702115c2021-06-24 15:39:18 -07001229INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1230 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1231 ::testing::ValuesIn(RpcSecurityValues())),
1232 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001233
Yifan Hong702115c2021-06-24 15:39:18 -07001234class BinderRpcServerRootObject
1235 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001236
1237TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1238 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1239 auto setRootObject = [](bool isStrong) -> SetFn {
1240 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1241 };
1242
Yifan Hong702115c2021-06-24 15:39:18 -07001243 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1244 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001245 auto binder1 = sp<BBinder>::make();
1246 IBinder* binderRaw1 = binder1.get();
1247 setRootObject(isStrong1)(server.get(), binder1);
1248 EXPECT_EQ(binderRaw1, server->getRootObject());
1249 binder1.clear();
1250 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1251
1252 auto binder2 = sp<BBinder>::make();
1253 IBinder* binderRaw2 = binder2.get();
1254 setRootObject(isStrong2)(server.get(), binder2);
1255 EXPECT_EQ(binderRaw2, server->getRootObject());
1256 binder2.clear();
1257 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1258}
1259
1260INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001261 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1262 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001263
Yifan Hong1a235852021-05-13 16:07:47 -07001264class OneOffSignal {
1265public:
1266 // If notify() was previously called, or is called within |duration|, return true; else false.
1267 template <typename R, typename P>
1268 bool wait(std::chrono::duration<R, P> duration) {
1269 std::unique_lock<std::mutex> lock(mMutex);
1270 return mCv.wait_for(lock, duration, [this] { return mValue; });
1271 }
1272 void notify() {
1273 std::unique_lock<std::mutex> lock(mMutex);
1274 mValue = true;
1275 lock.unlock();
1276 mCv.notify_all();
1277 }
1278
1279private:
1280 std::mutex mMutex;
1281 std::condition_variable mCv;
1282 bool mValue = false;
1283};
1284
Yifan Hong702115c2021-06-24 15:39:18 -07001285TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001286 auto addr = allocateSocketAddress();
1287 unlink(addr.c_str());
Yifan Hong702115c2021-06-24 15:39:18 -07001288 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong1a235852021-05-13 16:07:47 -07001289 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001290 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001291 auto joinEnds = std::make_shared<OneOffSignal>();
1292
1293 // If things are broken and the thread never stops, don't block other tests. Because the thread
1294 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1295 // shared pointers are passed.
1296 std::thread([server, joinEnds] {
1297 server->join();
1298 joinEnds->notify();
1299 }).detach();
1300
1301 bool shutdown = false;
1302 for (int i = 0; i < 10 && !shutdown; i++) {
1303 usleep(300 * 1000); // 300ms; total 3s
1304 if (server->shutdown()) shutdown = true;
1305 }
1306 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1307
1308 ASSERT_TRUE(joinEnds->wait(2s))
1309 << "After server->shutdown() returns true, join() did not stop after 2s";
1310}
1311
Yifan Hong194acf22021-06-29 18:44:56 -07001312TEST(BinderRpc, Java) {
1313#if !defined(__ANDROID__)
1314 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1315 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1316 "to binderHostDeviceTest. Hence, just disable this test on host.";
1317#endif // !__ANDROID__
1318 sp<IServiceManager> sm = defaultServiceManager();
1319 ASSERT_NE(nullptr, sm);
1320 // Any Java service with non-empty getInterfaceDescriptor() would do.
1321 // Let's pick batteryproperties.
1322 auto binder = sm->checkService(String16("batteryproperties"));
1323 ASSERT_NE(nullptr, binder);
1324 auto descriptor = binder->getInterfaceDescriptor();
1325 ASSERT_GE(descriptor.size(), 0);
1326 ASSERT_EQ(OK, binder->pingBinder());
1327
1328 auto rpcServer = RpcServer::make();
1329 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1330 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001331 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001332 auto socket = rpcServer->releaseServer();
1333
1334 auto keepAlive = sp<BBinder>::make();
1335 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1336
1337 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001338 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001339 auto rpcBinder = rpcSession->getRootObject();
1340 ASSERT_NE(nullptr, rpcBinder);
1341
1342 ASSERT_EQ(OK, rpcBinder->pingBinder());
1343
1344 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1345 << "getInterfaceDescriptor should not crash system_server";
1346 ASSERT_EQ(OK, rpcBinder->pingBinder());
1347}
1348
Yifan Hong702115c2021-06-24 15:39:18 -07001349INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1350 BinderRpcSimple::PrintTestParam);
1351
Steven Morelandc1635952021-04-01 16:20:47 +00001352} // namespace android
1353
1354int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001355 ::testing::InitGoogleTest(&argc, argv);
1356 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1357 return RUN_ALL_TESTS();
1358}