blob: 7c405d354193c4741e1ad6be7838daa46f27f0f8 [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 Hongecf937d2021-08-11 17:29:28 -0700525 sp<RpcSession> session =
526 RpcSession::make(newFactory(rpcSecurity), std::nullopt, std::nullopt);
Steven Moreland4313d7e2021-07-15 23:41:22 +0000527 session->setMaxThreads(options.numIncomingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000528
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000529 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700530 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700531 status = session->setupPreconnectedClient({}, [=]() {
532 return connectToUds(addr.c_str());
533 });
534 if (status == OK) goto success;
Steven Moreland4198a122021-08-03 17:37:58 -0700535 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000536 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700537 status = session->setupUnixDomainClient(addr.c_str());
538 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000539 break;
540 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700541 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
542 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000543 break;
544 case SocketType::INET:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700545 status = session->setupInetClient("127.0.0.1", outPort);
546 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000547 break;
548 default:
549 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000550 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700551 LOG_ALWAYS_FATAL("Could not connect %s", statusToString(status).c_str());
Steven Moreland736664b2021-05-01 04:27:25 +0000552 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000553 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000554 }
Steven Morelandc1635952021-04-01 16:20:47 +0000555 return ret;
556 }
557
Steven Moreland4313d7e2021-07-15 23:41:22 +0000558 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000559 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000560 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000561 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000562 sp<MyBinderRpcTest> service =
563 new MyBinderRpcTest;
564 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000565 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000566 }),
567 };
568
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000569 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000570 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
571
572 return ret;
573 }
574};
575
Steven Morelandc1635952021-04-01 16:20:47 +0000576TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000577 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000578 ASSERT_NE(proc.rootBinder, nullptr);
579 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
580}
581
Steven Moreland4cf688f2021-03-31 01:48:58 +0000582TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000583 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000584 ASSERT_NE(proc.rootBinder, nullptr);
585 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
586}
587
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000588TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000589 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000590 for (auto session : proc.proc.sessions) {
591 ASSERT_NE(nullptr, session.root);
592 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000593 }
594}
595
Steven Morelandc1635952021-04-01 16:20:47 +0000596TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000597 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000598 Parcel data;
599 Parcel reply;
600 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
601}
602
Steven Moreland67753c32021-04-02 18:45:19 +0000603TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000604 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000605
606 Parcel p1;
607 p1.markForBinder(proc.rootBinder);
608 p1.writeInt32(3);
609
610 Parcel p2;
611
612 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
613 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
614}
615
Steven Morelandc1635952021-04-01 16:20:47 +0000616TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000617 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000618 Parcel data;
619 data.markForBinder(proc.rootBinder);
620 Parcel reply;
621 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
622}
623
Steven Morelandc1635952021-04-01 16:20:47 +0000624TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000625 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000626 EXPECT_OK(proc.rootIface->sendString("asdf"));
627}
628
Steven Morelandc1635952021-04-01 16:20:47 +0000629TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000630 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000631 std::string doubled;
632 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
633 EXPECT_EQ("cool cool ", doubled);
634}
635
Steven Morelandc1635952021-04-01 16:20:47 +0000636TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000637 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000638 std::string single = std::string(1024, 'a');
639 std::string doubled;
640 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
641 EXPECT_EQ(single + single, doubled);
642}
643
Steven Morelandc1635952021-04-01 16:20:47 +0000644TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000645 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000646
647 int32_t pingResult;
648 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
649 EXPECT_EQ(OK, pingResult);
650
651 EXPECT_EQ(0, MyBinderRpcSession::gNum);
652}
653
Steven Morelandc1635952021-04-01 16:20:47 +0000654TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000655 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000656
657 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
658 sp<IBinder> outBinder;
659 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
660 EXPECT_EQ(inBinder, outBinder);
661
662 wp<IBinder> weak = inBinder;
663 inBinder = nullptr;
664 outBinder = nullptr;
665
666 // Force reading a reply, to process any pending dec refs from the other
667 // process (the other process will process dec refs there before processing
668 // the ping here).
669 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
670
671 EXPECT_EQ(nullptr, weak.promote());
672
673 EXPECT_EQ(0, MyBinderRpcSession::gNum);
674}
675
Steven Morelandc1635952021-04-01 16:20:47 +0000676TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000677 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000678
679 sp<IBinderRpcSession> session;
680 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
681
682 sp<IBinder> inBinder = IInterface::asBinder(session);
683 sp<IBinder> outBinder;
684 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
685 EXPECT_EQ(inBinder, outBinder);
686
687 wp<IBinder> weak = inBinder;
688 session = nullptr;
689 inBinder = nullptr;
690 outBinder = nullptr;
691
692 // Force reading a reply, to process any pending dec refs from the other
693 // process (the other process will process dec refs there before processing
694 // the ping here).
695 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
696
697 EXPECT_EQ(nullptr, weak.promote());
698}
699
Steven Morelandc1635952021-04-01 16:20:47 +0000700TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000701 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000702
703 sp<IBinder> outBinder;
704 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
705 EXPECT_EQ(nullptr, outBinder);
706}
707
Steven Morelandc1635952021-04-01 16:20:47 +0000708TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000709 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000710
711 IBinder* ptr = nullptr;
712 {
713 sp<IBinder> binder = new BBinder();
714 ptr = binder.get();
715 EXPECT_OK(proc.rootIface->holdBinder(binder));
716 }
717
718 sp<IBinder> held;
719 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
720
721 EXPECT_EQ(held.get(), ptr);
722
723 // stop holding binder, because we test to make sure references are cleaned
724 // up
725 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
726 // and flush ref counts
727 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
728}
729
730// START TESTS FOR LIMITATIONS OF SOCKET BINDER
731// These are behavioral differences form regular binder, where certain usecases
732// aren't supported.
733
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000734TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000735 auto proc1 = createRpcTestSocketServerProcess({});
736 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000737
738 sp<IBinder> outBinder;
739 EXPECT_EQ(INVALID_OPERATION,
740 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
741}
742
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000743TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000744 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000745
746 sp<IBinder> outBinder;
747 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000748 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000749 .transactionError());
750}
751
Steven Morelandc1635952021-04-01 16:20:47 +0000752TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000753 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000754
755 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
756 sp<IBinder> outBinder;
757 EXPECT_EQ(INVALID_OPERATION,
758 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
759}
760
Steven Morelandc1635952021-04-01 16:20:47 +0000761TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000762 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000763
764 // for historical reasons, IServiceManager interface only returns the
765 // exception code
766 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
767 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
768}
769
770// END TESTS FOR LIMITATIONS OF SOCKET BINDER
771
Steven Morelandc1635952021-04-01 16:20:47 +0000772TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000773 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000774
775 sp<IBinder> outBinder;
776 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
777 EXPECT_EQ(proc.rootBinder, outBinder);
778}
779
Steven Morelandc1635952021-04-01 16:20:47 +0000780TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000781 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000782
783 auto nastyNester = sp<MyBinderRpcTest>::make();
784 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
785
786 wp<IBinder> weak = nastyNester;
787 nastyNester = nullptr;
788 EXPECT_EQ(nullptr, weak.promote());
789}
790
Steven Morelandc1635952021-04-01 16:20:47 +0000791TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000792 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000793
794 sp<IBinder> a;
795 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
796
797 sp<IBinder> b;
798 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
799
800 EXPECT_EQ(a, b);
801}
802
Steven Morelandc1635952021-04-01 16:20:47 +0000803TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000804 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000805
806 sp<IBinder> a;
807 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
808 wp<IBinder> weak = a;
809 a = nullptr;
810
811 sp<IBinder> b;
812 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
813
814 // this is the wrong behavior, since BpBinder
815 // doesn't implement onIncStrongAttempted
816 // but make sure there is no crash
817 EXPECT_EQ(nullptr, weak.promote());
818
819 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
820
821 // In order to fix this:
822 // - need to have incStrongAttempted reflected across IPC boundary (wait for
823 // response to promote - round trip...)
824 // - sendOnLastWeakRef, to delete entries out of RpcState table
825 EXPECT_EQ(b, weak.promote());
826}
827
828#define expectSessions(expected, iface) \
829 do { \
830 int session; \
831 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
832 EXPECT_EQ(expected, session); \
833 } while (false)
834
Steven Morelandc1635952021-04-01 16:20:47 +0000835TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000836 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000837
838 sp<IBinderRpcSession> session;
839 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
840 std::string out;
841 EXPECT_OK(session->getName(&out));
842 EXPECT_EQ("aoeu", out);
843
844 expectSessions(1, proc.rootIface);
845 session = nullptr;
846 expectSessions(0, proc.rootIface);
847}
848
Steven Morelandc1635952021-04-01 16:20:47 +0000849TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000850 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000851
852 std::vector<sp<IBinderRpcSession>> sessions;
853
854 for (size_t i = 0; i < 15; i++) {
855 expectSessions(i, proc.rootIface);
856 sp<IBinderRpcSession> session;
857 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
858 sessions.push_back(session);
859 }
860 expectSessions(sessions.size(), proc.rootIface);
861 for (size_t i = 0; i < sessions.size(); i++) {
862 std::string out;
863 EXPECT_OK(sessions.at(i)->getName(&out));
864 EXPECT_EQ(std::to_string(i), out);
865 }
866 expectSessions(sessions.size(), proc.rootIface);
867
868 while (!sessions.empty()) {
869 sessions.pop_back();
870 expectSessions(sessions.size(), proc.rootIface);
871 }
872 expectSessions(0, proc.rootIface);
873}
874
875size_t epochMillis() {
876 using std::chrono::duration_cast;
877 using std::chrono::milliseconds;
878 using std::chrono::seconds;
879 using std::chrono::system_clock;
880 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
881}
882
Steven Morelandc1635952021-04-01 16:20:47 +0000883TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000884 constexpr size_t kNumThreads = 10;
885
Steven Moreland4313d7e2021-07-15 23:41:22 +0000886 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000887
888 EXPECT_OK(proc.rootIface->lock());
889
890 // block all but one thread taking locks
891 std::vector<std::thread> ts;
892 for (size_t i = 0; i < kNumThreads - 1; i++) {
893 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
894 }
895
896 usleep(100000); // give chance for calls on other threads
897
898 // other calls still work
899 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
900
901 constexpr size_t blockTimeMs = 500;
902 size_t epochMsBefore = epochMillis();
903 // after this, we should never see a response within this time
904 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
905
906 // this call should be blocked for blockTimeMs
907 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
908
909 size_t epochMsAfter = epochMillis();
910 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
911
912 for (auto& t : ts) t.join();
913}
914
Steven Morelandc1635952021-04-01 16:20:47 +0000915TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000916 constexpr size_t kNumThreads = 10;
917 constexpr size_t kNumCalls = kNumThreads + 3;
918 constexpr size_t kSleepMs = 500;
919
Steven Moreland4313d7e2021-07-15 23:41:22 +0000920 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000921
922 size_t epochMsBefore = epochMillis();
923
924 std::vector<std::thread> ts;
925 for (size_t i = 0; i < kNumCalls; i++) {
926 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
927 }
928
929 for (auto& t : ts) t.join();
930
931 size_t epochMsAfter = epochMillis();
932
933 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
934
935 // Potential flake, but make sure calls are handled in parallel.
936 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
937}
938
Steven Morelandc1635952021-04-01 16:20:47 +0000939TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000940 constexpr size_t kNumClientThreads = 10;
941 constexpr size_t kNumServerThreads = 10;
942 constexpr size_t kNumCalls = 100;
943
Steven Moreland4313d7e2021-07-15 23:41:22 +0000944 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000945
946 std::vector<std::thread> threads;
947 for (size_t i = 0; i < kNumClientThreads; i++) {
948 threads.push_back(std::thread([&] {
949 for (size_t j = 0; j < kNumCalls; j++) {
950 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000951 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000952 EXPECT_EQ(proc.rootBinder, out);
953 }
954 }));
955 }
956
957 for (auto& t : threads) t.join();
958}
959
Steven Morelandc6046982021-04-20 00:49:42 +0000960TEST_P(BinderRpc, OnewayStressTest) {
961 constexpr size_t kNumClientThreads = 10;
962 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000963 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000964
Steven Moreland4313d7e2021-07-15 23:41:22 +0000965 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000966
967 std::vector<std::thread> threads;
968 for (size_t i = 0; i < kNumClientThreads; i++) {
969 threads.push_back(std::thread([&] {
970 for (size_t j = 0; j < kNumCalls; j++) {
971 EXPECT_OK(proc.rootIface->sendString("a"));
972 }
973
974 // check threads are not stuck
975 EXPECT_OK(proc.rootIface->sleepMs(250));
976 }));
977 }
978
979 for (auto& t : threads) t.join();
980}
981
Steven Morelandc1635952021-04-01 16:20:47 +0000982TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000983 constexpr size_t kReallyLongTimeMs = 100;
984 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
985
Steven Moreland4313d7e2021-07-15 23:41:22 +0000986 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000987
988 size_t epochMsBefore = epochMillis();
989
990 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
991
992 size_t epochMsAfter = epochMillis();
993 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
994}
995
Steven Morelandc1635952021-04-01 16:20:47 +0000996TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000997 constexpr size_t kNumSleeps = 10;
998 constexpr size_t kNumExtraServerThreads = 4;
999 constexpr size_t kSleepMs = 50;
1000
1001 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001002 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001003
1004 EXPECT_OK(proc.rootIface->lock());
1005
1006 for (size_t i = 0; i < kNumSleeps; i++) {
1007 // these should be processed serially
1008 proc.rootIface->sleepMsAsync(kSleepMs);
1009 }
1010 // should also be processesed serially
1011 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1012
1013 size_t epochMsBefore = epochMillis();
1014 EXPECT_OK(proc.rootIface->lockUnlock());
1015 size_t epochMsAfter = epochMillis();
1016
1017 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001018
1019 // pending oneway transactions hold ref, make sure we read data on all
1020 // sockets
1021 std::vector<std::thread> threads;
1022 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
1023 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
1024 }
1025 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +00001026}
1027
Steven Morelandd45be622021-06-04 02:19:37 +00001028TEST_P(BinderRpc, OnewayCallExhaustion) {
1029 constexpr size_t kNumClients = 2;
1030 constexpr size_t kTooLongMs = 1000;
1031
Steven Moreland4313d7e2021-07-15 23:41:22 +00001032 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001033
1034 // Build up oneway calls on the second session to make sure it terminates
1035 // and shuts down. The first session should be unaffected (proc destructor
1036 // checks the first session).
1037 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1038
1039 std::vector<std::thread> threads;
1040 for (size_t i = 0; i < kNumClients; i++) {
1041 // one of these threads will get stuck queueing a transaction once the
1042 // socket fills up, the other will be able to fill up transactions on
1043 // this object
1044 threads.push_back(std::thread([&] {
1045 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1046 }
1047 }));
1048 }
1049 for (auto& t : threads) t.join();
1050
1051 Status status = iface->sleepMsAsync(kTooLongMs);
1052 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1053
Steven Moreland798e0d12021-07-14 23:19:25 +00001054 // now that it has died, wait for the remote session to shutdown
1055 std::vector<int32_t> remoteCounts;
1056 do {
1057 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1058 } while (remoteCounts.size() == kNumClients);
1059
Steven Morelandd45be622021-06-04 02:19:37 +00001060 // the second session should be shutdown in the other process by the time we
1061 // are able to join above (it'll only be hung up once it finishes processing
1062 // any pending commands). We need to erase this session from the record
1063 // here, so that the destructor for our session won't check that this
1064 // session is valid, but we still want it to test the other session.
1065 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1066}
1067
Steven Moreland659416d2021-05-11 00:47:50 +00001068TEST_P(BinderRpc, Callbacks) {
1069 const static std::string kTestString = "good afternoon!";
1070
Steven Morelandc7d40132021-06-10 03:42:11 +00001071 for (bool callIsOneway : {true, false}) {
1072 for (bool callbackIsOneway : {true, false}) {
1073 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001074 auto proc = createRpcTestSocketServerProcess(
1075 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001076 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001077
Steven Morelandc7d40132021-06-10 03:42:11 +00001078 if (callIsOneway) {
1079 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1080 kTestString));
1081 } else {
1082 EXPECT_OK(
1083 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1084 }
Steven Moreland659416d2021-05-11 00:47:50 +00001085
Steven Morelandc7d40132021-06-10 03:42:11 +00001086 using std::literals::chrono_literals::operator""s;
1087 std::unique_lock<std::mutex> _l(cb->mMutex);
1088 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001089
Steven Morelandc7d40132021-06-10 03:42:11 +00001090 EXPECT_EQ(cb->mValues.size(), 1)
1091 << "callIsOneway: " << callIsOneway
1092 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1093 if (cb->mValues.empty()) continue;
1094 EXPECT_EQ(cb->mValues.at(0), kTestString)
1095 << "callIsOneway: " << callIsOneway
1096 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001097
Steven Morelandc7d40132021-06-10 03:42:11 +00001098 // since we are severing the connection, we need to go ahead and
1099 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001100 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1101 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1102 }
Steven Moreland659416d2021-05-11 00:47:50 +00001103
Steven Moreland1b304292021-07-15 22:59:34 +00001104 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001105 // need to manually shut it down
1106 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001107
Steven Morelandc7d40132021-06-10 03:42:11 +00001108 proc.expectAlreadyShutdown = true;
1109 }
Steven Moreland659416d2021-05-11 00:47:50 +00001110 }
1111 }
1112}
1113
Steven Moreland195edb82021-06-08 02:44:39 +00001114TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001115 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001116 auto cb = sp<MyBinderRpcCallback>::make();
1117
1118 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1119 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1120}
1121
Steven Morelandc1635952021-04-01 16:20:47 +00001122TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001123 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001124 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001125
1126 // make sure there is some state during crash
1127 // 1. we hold their binder
1128 sp<IBinderRpcSession> session;
1129 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1130 // 2. they hold our binder
1131 sp<IBinder> binder = new BBinder();
1132 EXPECT_OK(proc.rootIface->holdBinder(binder));
1133
1134 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1135 << "Do death cleanup: " << doDeathCleanup;
1136
Steven Morelandaf4ca712021-05-24 23:22:08 +00001137 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001138 }
1139}
1140
Steven Morelandd7302072021-05-15 01:32:04 +00001141TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001142 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001143
1144 // we can't allocate IPCThreadState so actually the first time should
1145 // succeed :(
1146 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1147
1148 // second time! we catch the error :)
1149 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1150
Steven Morelandaf4ca712021-05-24 23:22:08 +00001151 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001152}
1153
Steven Moreland37aff182021-03-26 02:04:16 +00001154TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001155 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001156
1157 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1158 ASSERT_NE(binder, nullptr);
1159
1160 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1161}
1162
1163TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001164 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001165
1166 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1167 ASSERT_NE(binder, nullptr);
1168
1169 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1170 ASSERT_NE(ndkBinder, nullptr);
1171
1172 std::string out;
1173 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1174 ASSERT_TRUE(status.isOk()) << status.getDescription();
1175 ASSERT_EQ("aoeuaoeu", out);
1176}
1177
Steven Moreland5553ac42020-11-11 02:14:45 +00001178ssize_t countFds() {
1179 DIR* dir = opendir("/proc/self/fd/");
1180 if (dir == nullptr) return -1;
1181 ssize_t ret = 0;
1182 dirent* ent;
1183 while ((ent = readdir(dir)) != nullptr) ret++;
1184 closedir(dir);
1185 return ret;
1186}
1187
Steven Morelandc1635952021-04-01 16:20:47 +00001188TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001189 ssize_t beforeFds = countFds();
1190 ASSERT_GE(beforeFds, 0);
1191 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001192 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001193 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1194 }
1195 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1196}
1197
Steven Morelandda573042021-06-12 01:13:45 +00001198static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001199 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001200 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001201 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001202 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland1eab3452021-08-05 16:56:20 -07001203 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1204 if (status == -EAFNOSUPPORT) {
1205 return false;
1206 }
1207 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1208 }
Steven Morelandda573042021-06-12 01:13:45 +00001209 server->start();
1210
Yifan Hongecf937d2021-08-11 17:29:28 -07001211 sp<RpcSession> session =
1212 RpcSession::make(RpcTransportCtxFactoryRaw::make(), std::nullopt, std::nullopt);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001213 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001214 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001215 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1216 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001217}
1218
1219static std::vector<SocketType> testSocketTypes() {
Steven Moreland4198a122021-08-03 17:37:58 -07001220 std::vector<SocketType> ret = {SocketType::PRECONNECTED, SocketType::UNIX, SocketType::INET};
Steven Morelandda573042021-06-12 01:13:45 +00001221
1222 static bool hasVsockLoopback = testSupportVsockLoopback();
1223
1224 if (hasVsockLoopback) {
1225 ret.push_back(SocketType::VSOCK);
1226 }
1227
1228 return ret;
1229}
1230
Yifan Hong702115c2021-06-24 15:39:18 -07001231INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1232 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1233 ::testing::ValuesIn(RpcSecurityValues())),
1234 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001235
Yifan Hong702115c2021-06-24 15:39:18 -07001236class BinderRpcServerRootObject
1237 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001238
1239TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1240 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1241 auto setRootObject = [](bool isStrong) -> SetFn {
1242 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1243 };
1244
Yifan Hong702115c2021-06-24 15:39:18 -07001245 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1246 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001247 auto binder1 = sp<BBinder>::make();
1248 IBinder* binderRaw1 = binder1.get();
1249 setRootObject(isStrong1)(server.get(), binder1);
1250 EXPECT_EQ(binderRaw1, server->getRootObject());
1251 binder1.clear();
1252 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1253
1254 auto binder2 = sp<BBinder>::make();
1255 IBinder* binderRaw2 = binder2.get();
1256 setRootObject(isStrong2)(server.get(), binder2);
1257 EXPECT_EQ(binderRaw2, server->getRootObject());
1258 binder2.clear();
1259 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1260}
1261
1262INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001263 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1264 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001265
Yifan Hong1a235852021-05-13 16:07:47 -07001266class OneOffSignal {
1267public:
1268 // If notify() was previously called, or is called within |duration|, return true; else false.
1269 template <typename R, typename P>
1270 bool wait(std::chrono::duration<R, P> duration) {
1271 std::unique_lock<std::mutex> lock(mMutex);
1272 return mCv.wait_for(lock, duration, [this] { return mValue; });
1273 }
1274 void notify() {
1275 std::unique_lock<std::mutex> lock(mMutex);
1276 mValue = true;
1277 lock.unlock();
1278 mCv.notify_all();
1279 }
1280
1281private:
1282 std::mutex mMutex;
1283 std::condition_variable mCv;
1284 bool mValue = false;
1285};
1286
Yifan Hong702115c2021-06-24 15:39:18 -07001287TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001288 auto addr = allocateSocketAddress();
1289 unlink(addr.c_str());
Yifan Hong702115c2021-06-24 15:39:18 -07001290 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong1a235852021-05-13 16:07:47 -07001291 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001292 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001293 auto joinEnds = std::make_shared<OneOffSignal>();
1294
1295 // If things are broken and the thread never stops, don't block other tests. Because the thread
1296 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1297 // shared pointers are passed.
1298 std::thread([server, joinEnds] {
1299 server->join();
1300 joinEnds->notify();
1301 }).detach();
1302
1303 bool shutdown = false;
1304 for (int i = 0; i < 10 && !shutdown; i++) {
1305 usleep(300 * 1000); // 300ms; total 3s
1306 if (server->shutdown()) shutdown = true;
1307 }
1308 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1309
1310 ASSERT_TRUE(joinEnds->wait(2s))
1311 << "After server->shutdown() returns true, join() did not stop after 2s";
1312}
1313
Yifan Hong194acf22021-06-29 18:44:56 -07001314TEST(BinderRpc, Java) {
1315#if !defined(__ANDROID__)
1316 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1317 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1318 "to binderHostDeviceTest. Hence, just disable this test on host.";
1319#endif // !__ANDROID__
1320 sp<IServiceManager> sm = defaultServiceManager();
1321 ASSERT_NE(nullptr, sm);
1322 // Any Java service with non-empty getInterfaceDescriptor() would do.
1323 // Let's pick batteryproperties.
1324 auto binder = sm->checkService(String16("batteryproperties"));
1325 ASSERT_NE(nullptr, binder);
1326 auto descriptor = binder->getInterfaceDescriptor();
1327 ASSERT_GE(descriptor.size(), 0);
1328 ASSERT_EQ(OK, binder->pingBinder());
1329
1330 auto rpcServer = RpcServer::make();
1331 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1332 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001333 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001334 auto socket = rpcServer->releaseServer();
1335
1336 auto keepAlive = sp<BBinder>::make();
1337 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1338
1339 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001340 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001341 auto rpcBinder = rpcSession->getRootObject();
1342 ASSERT_NE(nullptr, rpcBinder);
1343
1344 ASSERT_EQ(OK, rpcBinder->pingBinder());
1345
1346 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1347 << "getInterfaceDescriptor should not crash system_server";
1348 ASSERT_EQ(OK, rpcBinder->pingBinder());
1349}
1350
Yifan Hong702115c2021-06-24 15:39:18 -07001351INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1352 BinderRpcSimple::PrintTestParam);
1353
Steven Morelandc1635952021-04-01 16:20:47 +00001354} // namespace android
1355
1356int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001357 ::testing::InitGoogleTest(&argc, argv);
1358 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1359 return RUN_ALL_TESTS();
1360}