blob: 4977c63083b8b70fa6b584616ee333bd8c78462c [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
Yifan Hong1deca4b2021-09-10 16:16:44 -070017#include <BinderRpcTestClientInfo.h>
18#include <BinderRpcTestServerInfo.h>
Steven Moreland659416d2021-05-11 00:47:50 +000019#include <BnBinderRpcCallback.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000020#include <BnBinderRpcSession.h>
21#include <BnBinderRpcTest.h>
Steven Moreland37aff182021-03-26 02:04:16 +000022#include <aidl/IBinderRpcTest.h>
Yifan Hong6d82c8a2021-04-26 20:26:45 -070023#include <android-base/file.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000024#include <android-base/logging.h>
Yifan Hongfe4b83f2021-11-08 16:29:53 -080025#include <android-base/properties.h>
Steven Moreland37aff182021-03-26 02:04:16 +000026#include <android/binder_auto_utils.h>
27#include <android/binder_libbinder.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000028#include <binder/Binder.h>
29#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000030#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000031#include <binder/IServiceManager.h>
32#include <binder/ProcessState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000033#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000034#include <binder/RpcSession.h>
Yifan Honge0e53282021-09-23 18:37:21 -070035#include <binder/RpcTlsTestUtils.h>
Yifan Hongb1ce80c2021-09-17 22:10:58 -070036#include <binder/RpcTlsUtils.h>
Yifan Hong702115c2021-06-24 15:39:18 -070037#include <binder/RpcTransport.h>
38#include <binder/RpcTransportRaw.h>
Yifan Hong92409752021-07-30 21:25:32 -070039#include <binder/RpcTransportTls.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000040#include <gtest/gtest.h>
41
Steven Morelandc1635952021-04-01 16:20:47 +000042#include <chrono>
43#include <cstdlib>
44#include <iostream>
45#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000046#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000047
Yifan Hong1deca4b2021-09-10 16:16:44 -070048#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000049#include <sys/prctl.h>
50#include <unistd.h>
51
Yifan Hong1deca4b2021-09-10 16:16:44 -070052#include "../FdTrigger.h"
Steven Moreland4198a122021-08-03 17:37:58 -070053#include "../RpcSocketAddress.h" // for testing preconnected clients
Yifan Hongffdaf952021-09-17 18:08:38 -070054#include "../RpcState.h" // for debugging
55#include "../vm_sockets.h" // for VMADDR_*
Steven Moreland5553ac42020-11-11 02:14:45 +000056
Yifan Hong1a235852021-05-13 16:07:47 -070057using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070058using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070059using testing::AssertionFailure;
60using testing::AssertionResult;
61using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070062
Steven Moreland5553ac42020-11-11 02:14:45 +000063namespace android {
64
Steven Morelandbf57bce2021-07-26 15:26:12 -070065static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
66 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Devin Mooref3b9c4f2021-08-03 15:50:13 +000067const char* kLocalInetAddress = "127.0.0.1";
Steven Morelandbf57bce2021-07-26 15:26:12 -070068
Yifan Hong92409752021-07-30 21:25:32 -070069enum class RpcSecurity { RAW, TLS };
Yifan Hong702115c2021-06-24 15:39:18 -070070
71static inline std::vector<RpcSecurity> RpcSecurityValues() {
Yifan Hong92409752021-07-30 21:25:32 -070072 return {RpcSecurity::RAW, RpcSecurity::TLS};
Yifan Hong702115c2021-06-24 15:39:18 -070073}
74
Yifan Hong13c90062021-09-09 14:59:53 -070075static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(
Yifan Hongffdaf952021-09-17 18:08:38 -070076 RpcSecurity rpcSecurity, std::shared_ptr<RpcCertificateVerifier> verifier = nullptr,
77 std::unique_ptr<RpcAuth> auth = nullptr) {
Yifan Hong702115c2021-06-24 15:39:18 -070078 switch (rpcSecurity) {
79 case RpcSecurity::RAW:
80 return RpcTransportCtxFactoryRaw::make();
Yifan Hong13c90062021-09-09 14:59:53 -070081 case RpcSecurity::TLS: {
Yifan Hong13c90062021-09-09 14:59:53 -070082 if (verifier == nullptr) {
83 verifier = std::make_shared<RpcCertificateVerifierSimple>();
84 }
Yifan Hongffdaf952021-09-17 18:08:38 -070085 if (auth == nullptr) {
86 auth = std::make_unique<RpcAuthSelfSigned>();
87 }
88 return RpcTransportCtxFactoryTls::make(std::move(verifier), std::move(auth));
Yifan Hong13c90062021-09-09 14:59:53 -070089 }
Yifan Hong702115c2021-06-24 15:39:18 -070090 default:
91 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
92 }
93}
94
Steven Moreland1fda67b2021-04-02 18:35:50 +000095TEST(BinderRpcParcel, EntireParcelFormatted) {
96 Parcel p;
97 p.writeInt32(3);
98
99 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
100}
101
Yifan Hong702115c2021-06-24 15:39:18 -0700102class BinderRpcSimple : public ::testing::TestWithParam<RpcSecurity> {
103public:
104 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
105 return newFactory(info.param)->toCString();
106 }
107};
108
109TEST_P(BinderRpcSimple, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700110 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
111 int sinkFd = sink.get();
Yifan Hong702115c2021-06-24 15:39:18 -0700112 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -0700113 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700114 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -0700115 ASSERT_TRUE(server->hasServer());
116 base::unique_fd retrieved = server->releaseServer();
117 ASSERT_FALSE(server->hasServer());
118 ASSERT_EQ(sinkFd, retrieved.get());
119}
120
Steven Morelandbf57bce2021-07-26 15:26:12 -0700121TEST(BinderRpc, CannotUseNextWireVersion) {
122 auto session = RpcSession::make();
123 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
124 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
125 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
126 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
127}
128
129TEST(BinderRpc, CanUseExperimentalWireVersion) {
130 auto session = RpcSession::make();
131 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
132}
133
Steven Moreland5553ac42020-11-11 02:14:45 +0000134using android::binder::Status;
135
136#define EXPECT_OK(status) \
137 do { \
138 Status stat = (status); \
139 EXPECT_TRUE(stat.isOk()) << stat; \
140 } while (false)
141
142class MyBinderRpcSession : public BnBinderRpcSession {
143public:
144 static std::atomic<int32_t> gNum;
145
146 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
147 Status getName(std::string* name) override {
148 *name = mName;
149 return Status::ok();
150 }
151 ~MyBinderRpcSession() { gNum--; }
152
153private:
154 std::string mName;
155};
156std::atomic<int32_t> MyBinderRpcSession::gNum;
157
Steven Moreland659416d2021-05-11 00:47:50 +0000158class MyBinderRpcCallback : public BnBinderRpcCallback {
159 Status sendCallback(const std::string& value) {
160 std::unique_lock _l(mMutex);
161 mValues.push_back(value);
162 _l.unlock();
163 mCv.notify_one();
164 return Status::ok();
165 }
166 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
167
168public:
169 std::mutex mMutex;
170 std::condition_variable mCv;
171 std::vector<std::string> mValues;
172};
173
Steven Moreland5553ac42020-11-11 02:14:45 +0000174class MyBinderRpcTest : public BnBinderRpcTest {
175public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000176 wp<RpcServer> server;
Steven Moreland51c44a92021-10-14 16:50:35 -0700177 int port = 0;
Steven Moreland5553ac42020-11-11 02:14:45 +0000178
179 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000180 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000181 return Status::ok();
182 }
183 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000184 *strstr = str + str;
185 return Status::ok();
186 }
Steven Moreland51c44a92021-10-14 16:50:35 -0700187 Status getClientPort(int* out) override {
188 *out = port;
189 return Status::ok();
190 }
Steven Moreland736664b2021-05-01 04:27:25 +0000191 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000192 sp<RpcServer> spServer = server.promote();
193 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000194 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
195 }
Steven Moreland736664b2021-05-01 04:27:25 +0000196 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000197 for (auto session : spServer->listSessions()) {
198 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000199 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000200 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000201 return Status::ok();
202 }
203 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
204 if (binder == nullptr) {
205 std::cout << "Received null binder!" << std::endl;
206 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
207 }
208 *out = binder->pingBinder();
209 return Status::ok();
210 }
211 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
212 *out = binder;
213 return Status::ok();
214 }
215 static sp<IBinder> mHeldBinder;
216 Status holdBinder(const sp<IBinder>& binder) override {
217 mHeldBinder = binder;
218 return Status::ok();
219 }
220 Status getHeldBinder(sp<IBinder>* held) override {
221 *held = mHeldBinder;
222 return Status::ok();
223 }
224 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
225 if (count <= 0) return Status::ok();
226 return binder->nestMe(this, count - 1);
227 }
228 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
229 static sp<IBinder> binder = new BBinder;
230 *out = binder;
231 return Status::ok();
232 }
233 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
234 *out = new MyBinderRpcSession(name);
235 return Status::ok();
236 }
237 Status getNumOpenSessions(int32_t* out) override {
238 *out = MyBinderRpcSession::gNum;
239 return Status::ok();
240 }
241
242 std::mutex blockMutex;
243 Status lock() override {
244 blockMutex.lock();
245 return Status::ok();
246 }
247 Status unlockInMsAsync(int32_t ms) override {
248 usleep(ms * 1000);
249 blockMutex.unlock();
250 return Status::ok();
251 }
252 Status lockUnlock() override {
253 std::lock_guard<std::mutex> _l(blockMutex);
254 return Status::ok();
255 }
256
257 Status sleepMs(int32_t ms) override {
258 usleep(ms * 1000);
259 return Status::ok();
260 }
261
262 Status sleepMsAsync(int32_t ms) override {
263 // In-process binder calls are asynchronous, but the call to this method
264 // is synchronous wrt its client. This in/out-process threading model
265 // diffentiation is a classic binder leaky abstraction (for better or
266 // worse) and is preserved here the way binder sockets plugs itself
267 // into BpBinder, as nothing is changed at the higher levels
268 // (IInterface) which result in this behavior.
269 return sleepMs(ms);
270 }
271
Steven Moreland659416d2021-05-11 00:47:50 +0000272 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
273 const std::string& value) override {
274 if (callback == nullptr) {
275 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
276 }
277
278 if (delayed) {
279 std::thread([=]() {
280 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000281 Status status = doCallback(callback, oneway, false, value);
282 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000283 }).detach();
284 return Status::ok();
285 }
286
287 if (oneway) {
288 return callback->sendOnewayCallback(value);
289 }
290
291 return callback->sendCallback(value);
292 }
293
Steven Morelandc7d40132021-06-10 03:42:11 +0000294 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
295 const std::string& value) override {
296 return doCallback(callback, oneway, delayed, value);
297 }
298
Steven Moreland5553ac42020-11-11 02:14:45 +0000299 Status die(bool cleanup) override {
300 if (cleanup) {
301 exit(1);
302 } else {
303 _exit(1);
304 }
305 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000306
307 Status scheduleShutdown() override {
308 sp<RpcServer> strongServer = server.promote();
309 if (strongServer == nullptr) {
310 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
311 }
312 std::thread([=] {
313 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
314 }).detach();
315 return Status::ok();
316 }
317
Steven Morelandd7302072021-05-15 01:32:04 +0000318 Status useKernelBinderCallingId() override {
319 // this is WRONG! It does not make sense when using RPC binder, and
320 // because it is SO wrong, and so much code calls this, it should abort!
321
322 (void)IPCThreadState::self()->getCallingPid();
323 return Status::ok();
324 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000325};
326sp<IBinder> MyBinderRpcTest::mHeldBinder;
327
328class Process {
329public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700330 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700331 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
332 android::base::borrowed_fd /* readEnd */)>& f) {
333 android::base::unique_fd childWriteEnd;
334 android::base::unique_fd childReadEnd;
335 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
336 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000337 if (0 == (mPid = fork())) {
338 // racey: assume parent doesn't crash before this is set
339 prctl(PR_SET_PDEATHSIG, SIGHUP);
340
Yifan Hong1deca4b2021-09-10 16:16:44 -0700341 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000342
343 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000344 }
345 }
346 ~Process() {
347 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000348 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000349 }
350 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700351 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700352 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000353
354private:
355 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700356 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700357 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000358};
359
360static std::string allocateSocketAddress() {
361 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000362 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700363 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
364 unlink(ret.c_str());
365 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000366};
367
Steven Morelandda573042021-06-12 01:13:45 +0000368static unsigned int allocateVsockPort() {
369 static unsigned int vsockPort = 3456;
370 return vsockPort++;
371}
372
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000373struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000374 // reference to process hosting a socket server
375 Process host;
376
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000377 struct SessionInfo {
378 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000379 sp<IBinder> root;
380 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000381
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000382 // client session objects associated with other process
383 // each one represents a separate session
384 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000385
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000386 ProcessSession(ProcessSession&&) = default;
387 ~ProcessSession() {
388 for (auto& session : sessions) {
389 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000390 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000391
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000392 for (auto& info : sessions) {
393 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000394
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395 EXPECT_NE(nullptr, session);
396 EXPECT_NE(nullptr, session->state());
397 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000398
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000399 wp<RpcSession> weakSession = session;
400 session = nullptr;
401 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000402 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000403 }
404};
405
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000406// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000407// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000408struct BinderRpcTestProcessSession {
409 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000410
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000411 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000412 sp<IBinder> rootBinder;
413
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000414 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000415 sp<IBinderRpcTest> rootIface;
416
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000417 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000418 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000419
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
421 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000422 EXPECT_NE(nullptr, rootIface);
423 if (rootIface == nullptr) return;
424
Steven Morelandaf4ca712021-05-24 23:22:08 +0000425 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000426 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000427 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000428 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000429 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000430 for (auto remoteCount : remoteCounts) {
431 EXPECT_EQ(remoteCount, 1);
432 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000433
Steven Moreland798e0d12021-07-14 23:19:25 +0000434 // even though it is on another thread, shutdown races with
435 // the transaction reply being written
436 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
437 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
438 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000439 }
440
441 rootIface = nullptr;
442 rootBinder = nullptr;
443 }
444};
445
Steven Morelandc1635952021-04-01 16:20:47 +0000446enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700447 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000448 UNIX,
449 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700450 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000451};
Yifan Hong702115c2021-06-24 15:39:18 -0700452static inline std::string PrintToString(SocketType socketType) {
453 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700454 case SocketType::PRECONNECTED:
455 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000456 case SocketType::UNIX:
457 return "unix_domain_socket";
458 case SocketType::VSOCK:
459 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700460 case SocketType::INET:
461 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000462 default:
463 LOG_ALWAYS_FATAL("Unknown socket type");
464 return "";
465 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000466}
Steven Morelandda573042021-06-12 01:13:45 +0000467
Yifan Hong1deca4b2021-09-10 16:16:44 -0700468static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700469 base::unique_fd serverFd(
470 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
471 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700472 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
473 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700474
475 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
476 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700477 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
478 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700479 }
480 return serverFd;
481}
482
Yifan Hong702115c2021-06-24 15:39:18 -0700483class BinderRpc : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000484public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000485 struct Options {
486 size_t numThreads = 1;
487 size_t numSessions = 1;
488 size_t numIncomingConnections = 0;
Yifan Hong1f44f982021-10-08 17:16:47 -0700489 size_t numOutgoingConnections = SIZE_MAX;
Steven Moreland4313d7e2021-07-15 23:41:22 +0000490 };
491
Yifan Hong702115c2021-06-24 15:39:18 -0700492 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
493 auto [type, security] = info.param;
494 return PrintToString(type) + "_" + newFactory(security)->toCString();
495 }
496
Yifan Hong1deca4b2021-09-10 16:16:44 -0700497 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
498 uint64_t length = str.length();
499 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
500 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
501 }
502
503 static inline std::string readString(android::base::borrowed_fd fd) {
504 uint64_t length;
505 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
506 std::string ret(length, '\0');
507 CHECK(android::base::ReadFully(fd, ret.data(), length));
508 return ret;
509 }
510
511 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
512 Parcel parcel;
513 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
514 writeString(fd,
515 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
516 }
517
518 template <typename T>
519 static inline T readFromFd(android::base::borrowed_fd fd) {
520 std::string data = readString(fd);
521 Parcel parcel;
522 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
523 T object;
524 CHECK_EQ(OK, object.readFromParcel(&parcel));
525 return object;
526 }
527
Steven Morelandc1635952021-04-01 16:20:47 +0000528 // This creates a new process serving an interface on a certain number of
529 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000530 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000531 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
532 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000533
Yifan Hong702115c2021-06-24 15:39:18 -0700534 SocketType socketType = std::get<0>(GetParam());
535 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000536
Steven Morelandda573042021-06-12 01:13:45 +0000537 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000538 std::string addr = allocateSocketAddress();
Steven Morelandc1635952021-04-01 16:20:47 +0000539
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000540 auto ret = ProcessSession{
Yifan Hong1deca4b2021-09-10 16:16:44 -0700541 .host = Process([&](android::base::borrowed_fd writeEnd,
542 android::base::borrowed_fd readEnd) {
543 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
544 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
Steven Morelandc1635952021-04-01 16:20:47 +0000545
Steven Moreland4313d7e2021-07-15 23:41:22 +0000546 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000547
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000548 unsigned int outPort = 0;
549
Steven Morelandc1635952021-04-01 16:20:47 +0000550 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700551 case SocketType::PRECONNECTED:
552 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000553 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700554 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000555 break;
556 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700557 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000558 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700559 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700560 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700561 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700562 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700563 }
Steven Morelandc1635952021-04-01 16:20:47 +0000564 default:
565 LOG_ALWAYS_FATAL("Unknown socket type");
566 }
567
Yifan Hong1deca4b2021-09-10 16:16:44 -0700568 BinderRpcTestServerInfo serverInfo;
569 serverInfo.port = static_cast<int64_t>(outPort);
Yifan Hong9734cfc2021-09-13 16:14:09 -0700570 serverInfo.cert.data = server->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700571 writeToFd(writeEnd, serverInfo);
572 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
573
574 if (rpcSecurity == RpcSecurity::TLS) {
575 for (const auto& clientCert : clientInfo.certs) {
576 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700577 certVerifier
578 ->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
579 clientCert.data));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700580 }
581 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000582
Steven Moreland611d15f2021-05-01 01:28:27 +0000583 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000584
Steven Morelandf137de92021-04-24 01:54:26 +0000585 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000586
587 // Another thread calls shutdown. Wait for it to complete.
588 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000589 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000590 };
591
Yifan Hong1deca4b2021-09-10 16:16:44 -0700592 std::vector<sp<RpcSession>> sessions;
593 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
594 for (size_t i = 0; i < options.numSessions; i++) {
595 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
596 }
597
598 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
599 BinderRpcTestClientInfo clientInfo;
600 for (const auto& session : sessions) {
601 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700602 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700603 }
604 writeToFd(ret.host.writeEnd(), clientInfo);
605
606 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700607 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700608 CHECK_NE(0, serverInfo.port);
609 }
610
611 if (rpcSecurity == RpcSecurity::TLS) {
612 const auto& serverCert = serverInfo.cert.data;
613 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700614 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
615 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700616 }
617
Steven Moreland2372f9d2021-08-05 15:42:01 -0700618 status_t status;
619
Yifan Hong1deca4b2021-09-10 16:16:44 -0700620 for (const auto& session : sessions) {
Yifan Hong10423062021-10-08 16:26:32 -0700621 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700622 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000623
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000624 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700625 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700626 status = session->setupPreconnectedClient({}, [=]() {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700627 return connectTo(UnixSocketAddress(addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700628 });
Steven Moreland4198a122021-08-03 17:37:58 -0700629 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000630 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700631 status = session->setupUnixDomainClient(addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000632 break;
633 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700634 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000635 break;
636 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700637 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000638 break;
639 default:
640 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000641 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700642 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000643 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000644 }
Steven Morelandc1635952021-04-01 16:20:47 +0000645 return ret;
646 }
647
Steven Moreland4313d7e2021-07-15 23:41:22 +0000648 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000649 BinderRpcTestProcessSession ret{
Steven Moreland51c44a92021-10-14 16:50:35 -0700650 .proc = createRpcTestSocketServerProcess(
651 options,
652 [&](const sp<RpcServer>& server) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000653 server->setPerSessionRootObject([&](const void* addrPtr, size_t len) {
654 // UNIX sockets with abstract addresses return
655 // sizeof(sa_family_t)==2 in addrlen
656 CHECK_GE(len, sizeof(sa_family_t));
657 const sockaddr* addr = reinterpret_cast<const sockaddr*>(addrPtr);
Steven Moreland51c44a92021-10-14 16:50:35 -0700658 sp<MyBinderRpcTest> service = sp<MyBinderRpcTest>::make();
659 switch (addr->sa_family) {
660 case AF_UNIX:
661 // nothing to save
662 break;
663 case AF_VSOCK:
664 CHECK_EQ(len, sizeof(sockaddr_vm));
665 service->port = reinterpret_cast<const sockaddr_vm*>(addr)
666 ->svm_port;
667 break;
668 case AF_INET:
669 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700670 service->port =
671 ntohs(reinterpret_cast<const sockaddr_in*>(addr)
672 ->sin_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700673 break;
674 case AF_INET6:
675 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700676 service->port =
677 ntohs(reinterpret_cast<const sockaddr_in6*>(addr)
678 ->sin6_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700679 break;
680 default:
681 LOG_ALWAYS_FATAL("Unrecognized address family %d",
682 addr->sa_family);
683 }
684 service->server = server;
685 return service;
686 });
687 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000688 };
689
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000690 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000691 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
692
693 return ret;
694 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700695
696 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
697 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000698};
699
Steven Morelandc1635952021-04-01 16:20:47 +0000700TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000701 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000702 ASSERT_NE(proc.rootBinder, nullptr);
703 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
704}
705
Steven Moreland4cf688f2021-03-31 01:48:58 +0000706TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000707 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000708 ASSERT_NE(proc.rootBinder, nullptr);
709 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
710}
711
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000712TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000713 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000714 for (auto session : proc.proc.sessions) {
715 ASSERT_NE(nullptr, session.root);
716 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000717 }
718}
719
Steven Moreland51c44a92021-10-14 16:50:35 -0700720TEST_P(BinderRpc, SeparateRootObject) {
721 SocketType type = std::get<0>(GetParam());
722 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
723 // we can't get port numbers for unix sockets
724 return;
725 }
726
727 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
728
729 int port1 = 0;
730 EXPECT_OK(proc.rootIface->getClientPort(&port1));
731
732 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
733 int port2;
734 EXPECT_OK(rootIface2->getClientPort(&port2));
735
736 // we should have a different IBinderRpcTest object created for each
737 // session, because we use setPerSessionRootObject
738 EXPECT_NE(port1, port2);
739}
740
Steven Morelandc1635952021-04-01 16:20:47 +0000741TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000742 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000743 Parcel data;
744 Parcel reply;
745 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
746}
747
Steven Moreland67753c32021-04-02 18:45:19 +0000748TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700749 auto proc1 = createRpcTestSocketServerProcess({});
750 auto proc2 = createRpcTestSocketServerProcess({});
751
752 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000753
754 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700755 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000756 p1.writeInt32(3);
757
Frederick Maylea4ed5672022-06-17 22:03:38 +0000758 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700759 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
760
Steven Moreland67753c32021-04-02 18:45:19 +0000761 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700762 p2.markForBinder(proc2.rootBinder);
763 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000764
765 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
766 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
767}
768
Steven Morelandc1635952021-04-01 16:20:47 +0000769TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000770 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000771 Parcel data;
772 data.markForBinder(proc.rootBinder);
773 Parcel reply;
774 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
775}
776
Steven Morelandc1635952021-04-01 16:20:47 +0000777TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000778 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000779 EXPECT_OK(proc.rootIface->sendString("asdf"));
780}
781
Steven Morelandc1635952021-04-01 16:20:47 +0000782TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000783 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000784 std::string doubled;
785 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
786 EXPECT_EQ("cool cool ", doubled);
787}
788
Steven Morelandc1635952021-04-01 16:20:47 +0000789TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000790 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000791 std::string single = std::string(1024, 'a');
792 std::string doubled;
793 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
794 EXPECT_EQ(single + single, doubled);
795}
796
Steven Morelandc1635952021-04-01 16:20:47 +0000797TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000798 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000799
800 int32_t pingResult;
801 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
802 EXPECT_EQ(OK, pingResult);
803
804 EXPECT_EQ(0, MyBinderRpcSession::gNum);
805}
806
Steven Morelandc1635952021-04-01 16:20:47 +0000807TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000808 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000809
810 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
811 sp<IBinder> outBinder;
812 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
813 EXPECT_EQ(inBinder, outBinder);
814
815 wp<IBinder> weak = inBinder;
816 inBinder = nullptr;
817 outBinder = nullptr;
818
819 // Force reading a reply, to process any pending dec refs from the other
820 // process (the other process will process dec refs there before processing
821 // the ping here).
822 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
823
824 EXPECT_EQ(nullptr, weak.promote());
825
826 EXPECT_EQ(0, MyBinderRpcSession::gNum);
827}
828
Steven Morelandc1635952021-04-01 16:20:47 +0000829TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000830 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000831
832 sp<IBinderRpcSession> session;
833 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
834
835 sp<IBinder> inBinder = IInterface::asBinder(session);
836 sp<IBinder> outBinder;
837 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
838 EXPECT_EQ(inBinder, outBinder);
839
840 wp<IBinder> weak = inBinder;
841 session = nullptr;
842 inBinder = nullptr;
843 outBinder = nullptr;
844
845 // Force reading a reply, to process any pending dec refs from the other
846 // process (the other process will process dec refs there before processing
847 // the ping here).
848 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
849
850 EXPECT_EQ(nullptr, weak.promote());
851}
852
Steven Morelandc1635952021-04-01 16:20:47 +0000853TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000854 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000855
856 sp<IBinder> outBinder;
857 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
858 EXPECT_EQ(nullptr, outBinder);
859}
860
Steven Morelandc1635952021-04-01 16:20:47 +0000861TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000862 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000863
864 IBinder* ptr = nullptr;
865 {
866 sp<IBinder> binder = new BBinder();
867 ptr = binder.get();
868 EXPECT_OK(proc.rootIface->holdBinder(binder));
869 }
870
871 sp<IBinder> held;
872 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
873
874 EXPECT_EQ(held.get(), ptr);
875
876 // stop holding binder, because we test to make sure references are cleaned
877 // up
878 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
879 // and flush ref counts
880 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
881}
882
883// START TESTS FOR LIMITATIONS OF SOCKET BINDER
884// These are behavioral differences form regular binder, where certain usecases
885// aren't supported.
886
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000887TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000888 auto proc1 = createRpcTestSocketServerProcess({});
889 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000890
891 sp<IBinder> outBinder;
892 EXPECT_EQ(INVALID_OPERATION,
893 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
894}
895
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000896TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000897 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000898
899 sp<IBinder> outBinder;
900 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000901 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000902 .transactionError());
903}
904
Steven Morelandc1635952021-04-01 16:20:47 +0000905TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000906 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000907
908 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
909 sp<IBinder> outBinder;
910 EXPECT_EQ(INVALID_OPERATION,
911 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
912}
913
Steven Morelandc1635952021-04-01 16:20:47 +0000914TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000915 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000916
917 // for historical reasons, IServiceManager interface only returns the
918 // exception code
919 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
920 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
921}
922
923// END TESTS FOR LIMITATIONS OF SOCKET BINDER
924
Steven Morelandc1635952021-04-01 16:20:47 +0000925TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000926 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000927
928 sp<IBinder> outBinder;
929 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
930 EXPECT_EQ(proc.rootBinder, outBinder);
931}
932
Steven Morelandc1635952021-04-01 16:20:47 +0000933TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000934 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000935
936 auto nastyNester = sp<MyBinderRpcTest>::make();
937 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
938
939 wp<IBinder> weak = nastyNester;
940 nastyNester = nullptr;
941 EXPECT_EQ(nullptr, weak.promote());
942}
943
Steven Morelandc1635952021-04-01 16:20:47 +0000944TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000945 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000946
947 sp<IBinder> a;
948 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
949
950 sp<IBinder> b;
951 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
952
953 EXPECT_EQ(a, b);
954}
955
Steven Morelandc1635952021-04-01 16:20:47 +0000956TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000957 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000958
959 sp<IBinder> a;
960 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
961 wp<IBinder> weak = a;
962 a = nullptr;
963
964 sp<IBinder> b;
965 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
966
967 // this is the wrong behavior, since BpBinder
968 // doesn't implement onIncStrongAttempted
969 // but make sure there is no crash
970 EXPECT_EQ(nullptr, weak.promote());
971
972 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
973
974 // In order to fix this:
975 // - need to have incStrongAttempted reflected across IPC boundary (wait for
976 // response to promote - round trip...)
977 // - sendOnLastWeakRef, to delete entries out of RpcState table
978 EXPECT_EQ(b, weak.promote());
979}
980
981#define expectSessions(expected, iface) \
982 do { \
983 int session; \
984 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
985 EXPECT_EQ(expected, session); \
986 } while (false)
987
Steven Morelandc1635952021-04-01 16:20:47 +0000988TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000989 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000990
991 sp<IBinderRpcSession> session;
992 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
993 std::string out;
994 EXPECT_OK(session->getName(&out));
995 EXPECT_EQ("aoeu", out);
996
997 expectSessions(1, proc.rootIface);
998 session = nullptr;
999 expectSessions(0, proc.rootIface);
1000}
1001
Steven Morelandc1635952021-04-01 16:20:47 +00001002TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001003 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001004
1005 std::vector<sp<IBinderRpcSession>> sessions;
1006
1007 for (size_t i = 0; i < 15; i++) {
1008 expectSessions(i, proc.rootIface);
1009 sp<IBinderRpcSession> session;
1010 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
1011 sessions.push_back(session);
1012 }
1013 expectSessions(sessions.size(), proc.rootIface);
1014 for (size_t i = 0; i < sessions.size(); i++) {
1015 std::string out;
1016 EXPECT_OK(sessions.at(i)->getName(&out));
1017 EXPECT_EQ(std::to_string(i), out);
1018 }
1019 expectSessions(sessions.size(), proc.rootIface);
1020
1021 while (!sessions.empty()) {
1022 sessions.pop_back();
1023 expectSessions(sessions.size(), proc.rootIface);
1024 }
1025 expectSessions(0, proc.rootIface);
1026}
1027
1028size_t epochMillis() {
1029 using std::chrono::duration_cast;
1030 using std::chrono::milliseconds;
1031 using std::chrono::seconds;
1032 using std::chrono::system_clock;
1033 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1034}
1035
Steven Morelandc1635952021-04-01 16:20:47 +00001036TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001037 constexpr size_t kNumThreads = 10;
1038
Steven Moreland4313d7e2021-07-15 23:41:22 +00001039 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001040
1041 EXPECT_OK(proc.rootIface->lock());
1042
1043 // block all but one thread taking locks
1044 std::vector<std::thread> ts;
1045 for (size_t i = 0; i < kNumThreads - 1; i++) {
1046 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
1047 }
1048
1049 usleep(100000); // give chance for calls on other threads
1050
1051 // other calls still work
1052 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1053
1054 constexpr size_t blockTimeMs = 500;
1055 size_t epochMsBefore = epochMillis();
1056 // after this, we should never see a response within this time
1057 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
1058
1059 // this call should be blocked for blockTimeMs
1060 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1061
1062 size_t epochMsAfter = epochMillis();
1063 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
1064
1065 for (auto& t : ts) t.join();
1066}
1067
Yifan Hong1f44f982021-10-08 17:16:47 -07001068void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
1069 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001070 size_t epochMsBefore = epochMillis();
1071
1072 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -07001073 for (size_t i = 0; i < numCalls; i++) {
1074 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +00001075 }
1076
1077 for (auto& t : ts) t.join();
1078
1079 size_t epochMsAfter = epochMillis();
1080
Yifan Hong1f44f982021-10-08 17:16:47 -07001081 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +00001082
1083 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -07001084 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
1085}
1086
1087TEST_P(BinderRpc, ThreadPoolOverSaturated) {
1088 constexpr size_t kNumThreads = 10;
1089 constexpr size_t kNumCalls = kNumThreads + 3;
1090 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1091 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
1092}
1093
1094TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
1095 constexpr size_t kNumThreads = 20;
1096 constexpr size_t kNumOutgoingConnections = 10;
1097 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
1098 auto proc = createRpcTestSocketServerProcess(
1099 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
1100 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +00001101}
1102
Steven Morelandc1635952021-04-01 16:20:47 +00001103TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001104 constexpr size_t kNumClientThreads = 10;
1105 constexpr size_t kNumServerThreads = 10;
1106 constexpr size_t kNumCalls = 100;
1107
Steven Moreland4313d7e2021-07-15 23:41:22 +00001108 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001109
1110 std::vector<std::thread> threads;
1111 for (size_t i = 0; i < kNumClientThreads; i++) {
1112 threads.push_back(std::thread([&] {
1113 for (size_t j = 0; j < kNumCalls; j++) {
1114 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001115 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001116 EXPECT_EQ(proc.rootBinder, out);
1117 }
1118 }));
1119 }
1120
1121 for (auto& t : threads) t.join();
1122}
1123
Steven Moreland925ba0a2021-09-17 18:06:32 -07001124static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
1125 std::vector<std::thread> threads;
1126 for (size_t i = 0; i < threadCount; i++) {
1127 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
1128 }
1129 for (auto& t : threads) t.join();
1130}
1131
Steven Morelandc6046982021-04-20 00:49:42 +00001132TEST_P(BinderRpc, OnewayStressTest) {
1133 constexpr size_t kNumClientThreads = 10;
1134 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -07001135 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +00001136
Steven Moreland4313d7e2021-07-15 23:41:22 +00001137 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001138
1139 std::vector<std::thread> threads;
1140 for (size_t i = 0; i < kNumClientThreads; i++) {
1141 threads.push_back(std::thread([&] {
1142 for (size_t j = 0; j < kNumCalls; j++) {
1143 EXPECT_OK(proc.rootIface->sendString("a"));
1144 }
Steven Morelandc6046982021-04-20 00:49:42 +00001145 }));
1146 }
1147
1148 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -07001149
1150 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +00001151}
1152
Steven Morelandc1635952021-04-01 16:20:47 +00001153TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001154 constexpr size_t kReallyLongTimeMs = 100;
1155 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1156
Steven Moreland4313d7e2021-07-15 23:41:22 +00001157 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001158
1159 size_t epochMsBefore = epochMillis();
1160
1161 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1162
1163 size_t epochMsAfter = epochMillis();
1164 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1165}
1166
Steven Morelandc1635952021-04-01 16:20:47 +00001167TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001168 constexpr size_t kNumSleeps = 10;
1169 constexpr size_t kNumExtraServerThreads = 4;
1170 constexpr size_t kSleepMs = 50;
1171
1172 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001173 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001174
1175 EXPECT_OK(proc.rootIface->lock());
1176
Steven Moreland1c678802021-09-17 16:48:47 -07001177 size_t epochMsBefore = epochMillis();
1178
1179 // all these *Async commands should be queued on the server sequentially,
1180 // even though there are multiple threads.
1181 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001182 proc.rootIface->sleepMsAsync(kSleepMs);
1183 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001184 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1185
Steven Moreland1c678802021-09-17 16:48:47 -07001186 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +00001187 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -07001188
Steven Moreland5553ac42020-11-11 02:14:45 +00001189 size_t epochMsAfter = epochMillis();
1190
1191 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001192
Steven Moreland925ba0a2021-09-17 18:06:32 -07001193 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001194}
1195
Steven Morelandd45be622021-06-04 02:19:37 +00001196TEST_P(BinderRpc, OnewayCallExhaustion) {
1197 constexpr size_t kNumClients = 2;
1198 constexpr size_t kTooLongMs = 1000;
1199
Steven Moreland4313d7e2021-07-15 23:41:22 +00001200 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001201
1202 // Build up oneway calls on the second session to make sure it terminates
1203 // and shuts down. The first session should be unaffected (proc destructor
1204 // checks the first session).
1205 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1206
1207 std::vector<std::thread> threads;
1208 for (size_t i = 0; i < kNumClients; i++) {
1209 // one of these threads will get stuck queueing a transaction once the
1210 // socket fills up, the other will be able to fill up transactions on
1211 // this object
1212 threads.push_back(std::thread([&] {
1213 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1214 }
1215 }));
1216 }
1217 for (auto& t : threads) t.join();
1218
1219 Status status = iface->sleepMsAsync(kTooLongMs);
1220 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1221
Steven Moreland798e0d12021-07-14 23:19:25 +00001222 // now that it has died, wait for the remote session to shutdown
1223 std::vector<int32_t> remoteCounts;
1224 do {
1225 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1226 } while (remoteCounts.size() == kNumClients);
1227
Steven Morelandd45be622021-06-04 02:19:37 +00001228 // the second session should be shutdown in the other process by the time we
1229 // are able to join above (it'll only be hung up once it finishes processing
1230 // any pending commands). We need to erase this session from the record
1231 // here, so that the destructor for our session won't check that this
1232 // session is valid, but we still want it to test the other session.
1233 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1234}
1235
Steven Moreland659416d2021-05-11 00:47:50 +00001236TEST_P(BinderRpc, Callbacks) {
1237 const static std::string kTestString = "good afternoon!";
1238
Steven Morelandc7d40132021-06-10 03:42:11 +00001239 for (bool callIsOneway : {true, false}) {
1240 for (bool callbackIsOneway : {true, false}) {
1241 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001242 auto proc = createRpcTestSocketServerProcess(
1243 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001244 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001245
Steven Morelandc7d40132021-06-10 03:42:11 +00001246 if (callIsOneway) {
1247 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1248 kTestString));
1249 } else {
1250 EXPECT_OK(
1251 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1252 }
Steven Moreland659416d2021-05-11 00:47:50 +00001253
Steven Moreland03ecce62022-05-13 23:22:05 +00001254 // if both transactions are synchronous and the response is sent back on the
1255 // same thread, everything should have happened in a nested call. Otherwise,
1256 // the callback will be processed on another thread.
1257 if (callIsOneway || callbackIsOneway || delayed) {
1258 using std::literals::chrono_literals::operator""s;
1259 std::unique_lock<std::mutex> _l(cb->mMutex);
1260 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1261 }
Steven Moreland659416d2021-05-11 00:47:50 +00001262
Steven Morelandc7d40132021-06-10 03:42:11 +00001263 EXPECT_EQ(cb->mValues.size(), 1)
1264 << "callIsOneway: " << callIsOneway
1265 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1266 if (cb->mValues.empty()) continue;
1267 EXPECT_EQ(cb->mValues.at(0), kTestString)
1268 << "callIsOneway: " << callIsOneway
1269 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001270
Steven Morelandc7d40132021-06-10 03:42:11 +00001271 // since we are severing the connection, we need to go ahead and
1272 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001273 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1274 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1275 }
Steven Moreland659416d2021-05-11 00:47:50 +00001276
Steven Moreland1b304292021-07-15 22:59:34 +00001277 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001278 // need to manually shut it down
1279 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001280
Steven Morelandc7d40132021-06-10 03:42:11 +00001281 proc.expectAlreadyShutdown = true;
1282 }
Steven Moreland659416d2021-05-11 00:47:50 +00001283 }
1284 }
1285}
1286
Steven Moreland195edb82021-06-08 02:44:39 +00001287TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001288 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001289 auto cb = sp<MyBinderRpcCallback>::make();
1290
1291 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1292 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1293}
1294
Steven Morelandc1635952021-04-01 16:20:47 +00001295TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001296 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001297 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001298
1299 // make sure there is some state during crash
1300 // 1. we hold their binder
1301 sp<IBinderRpcSession> session;
1302 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1303 // 2. they hold our binder
1304 sp<IBinder> binder = new BBinder();
1305 EXPECT_OK(proc.rootIface->holdBinder(binder));
1306
1307 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1308 << "Do death cleanup: " << doDeathCleanup;
1309
Steven Morelandaf4ca712021-05-24 23:22:08 +00001310 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001311 }
1312}
1313
Steven Morelandd7302072021-05-15 01:32:04 +00001314TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Morelanda83191d2021-10-27 10:14:53 -07001315 bool okToFork = ProcessState::selfOrNull() == nullptr;
1316
Steven Moreland4313d7e2021-07-15 23:41:22 +00001317 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001318
Steven Morelanda83191d2021-10-27 10:14:53 -07001319 // If this process has used ProcessState already, then the forked process
1320 // cannot use it at all. If this process hasn't used it (depending on the
1321 // order tests are run), then the forked process can use it, and we'll only
1322 // catch the invalid usage the second time. Such is the burden of global
1323 // state!
1324 if (okToFork) {
1325 // we can't allocate IPCThreadState so actually the first time should
1326 // succeed :(
1327 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1328 }
Steven Morelandd7302072021-05-15 01:32:04 +00001329
1330 // second time! we catch the error :)
1331 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1332
Steven Morelandaf4ca712021-05-24 23:22:08 +00001333 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001334}
1335
Steven Moreland37aff182021-03-26 02:04:16 +00001336TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001337 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001338
1339 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1340 ASSERT_NE(binder, nullptr);
1341
1342 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1343}
1344
1345TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001346 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001347
1348 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1349 ASSERT_NE(binder, nullptr);
1350
1351 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1352 ASSERT_NE(ndkBinder, nullptr);
1353
1354 std::string out;
1355 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1356 ASSERT_TRUE(status.isOk()) << status.getDescription();
1357 ASSERT_EQ("aoeuaoeu", out);
1358}
1359
Steven Moreland5553ac42020-11-11 02:14:45 +00001360ssize_t countFds() {
1361 DIR* dir = opendir("/proc/self/fd/");
1362 if (dir == nullptr) return -1;
1363 ssize_t ret = 0;
1364 dirent* ent;
1365 while ((ent = readdir(dir)) != nullptr) ret++;
1366 closedir(dir);
1367 return ret;
1368}
1369
Steven Morelandc1635952021-04-01 16:20:47 +00001370TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001371 ssize_t beforeFds = countFds();
1372 ASSERT_GE(beforeFds, 0);
1373 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001374 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001375 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1376 }
1377 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1378}
1379
Devin Moore800b2252021-10-15 16:22:57 +00001380TEST_P(BinderRpc, AidlDelegatorTest) {
1381 auto proc = createRpcTestSocketServerProcess({});
1382 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1383 ASSERT_NE(nullptr, myDelegator);
1384
1385 std::string doubled;
1386 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1387 EXPECT_EQ("cool cool ", doubled);
1388}
1389
Steven Morelandda573042021-06-12 01:13:45 +00001390static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001391 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001392 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001393 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland1eab3452021-08-05 16:56:20 -07001394 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1395 if (status == -EAFNOSUPPORT) {
1396 return false;
1397 }
1398 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1399 }
Steven Morelandda573042021-06-12 01:13:45 +00001400 server->start();
1401
Yifan Hongfdd9f692021-09-09 15:12:52 -07001402 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001403 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001404 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001405 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1406 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001407}
1408
Yifan Hong1deca4b2021-09-10 16:16:44 -07001409static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1410 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1411
1412 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001413
1414 static bool hasVsockLoopback = testSupportVsockLoopback();
1415
1416 if (hasVsockLoopback) {
1417 ret.push_back(SocketType::VSOCK);
1418 }
1419
1420 return ret;
1421}
1422
Yifan Hong702115c2021-06-24 15:39:18 -07001423INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1424 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1425 ::testing::ValuesIn(RpcSecurityValues())),
1426 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001427
Yifan Hong702115c2021-06-24 15:39:18 -07001428class BinderRpcServerRootObject
1429 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001430
1431TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1432 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1433 auto setRootObject = [](bool isStrong) -> SetFn {
1434 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1435 };
1436
Yifan Hong702115c2021-06-24 15:39:18 -07001437 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1438 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001439 auto binder1 = sp<BBinder>::make();
1440 IBinder* binderRaw1 = binder1.get();
1441 setRootObject(isStrong1)(server.get(), binder1);
1442 EXPECT_EQ(binderRaw1, server->getRootObject());
1443 binder1.clear();
1444 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1445
1446 auto binder2 = sp<BBinder>::make();
1447 IBinder* binderRaw2 = binder2.get();
1448 setRootObject(isStrong2)(server.get(), binder2);
1449 EXPECT_EQ(binderRaw2, server->getRootObject());
1450 binder2.clear();
1451 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1452}
1453
1454INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001455 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1456 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001457
Yifan Hong1a235852021-05-13 16:07:47 -07001458class OneOffSignal {
1459public:
1460 // If notify() was previously called, or is called within |duration|, return true; else false.
1461 template <typename R, typename P>
1462 bool wait(std::chrono::duration<R, P> duration) {
1463 std::unique_lock<std::mutex> lock(mMutex);
1464 return mCv.wait_for(lock, duration, [this] { return mValue; });
1465 }
1466 void notify() {
1467 std::unique_lock<std::mutex> lock(mMutex);
1468 mValue = true;
1469 lock.unlock();
1470 mCv.notify_all();
1471 }
1472
1473private:
1474 std::mutex mMutex;
1475 std::condition_variable mCv;
1476 bool mValue = false;
1477};
1478
Yifan Hong702115c2021-06-24 15:39:18 -07001479TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001480 auto addr = allocateSocketAddress();
Yifan Hong702115c2021-06-24 15:39:18 -07001481 auto server = RpcServer::make(newFactory(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001482 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001483 auto joinEnds = std::make_shared<OneOffSignal>();
1484
1485 // If things are broken and the thread never stops, don't block other tests. Because the thread
1486 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1487 // shared pointers are passed.
1488 std::thread([server, joinEnds] {
1489 server->join();
1490 joinEnds->notify();
1491 }).detach();
1492
1493 bool shutdown = false;
1494 for (int i = 0; i < 10 && !shutdown; i++) {
1495 usleep(300 * 1000); // 300ms; total 3s
1496 if (server->shutdown()) shutdown = true;
1497 }
1498 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1499
1500 ASSERT_TRUE(joinEnds->wait(2s))
1501 << "After server->shutdown() returns true, join() did not stop after 2s";
1502}
1503
Yifan Hong194acf22021-06-29 18:44:56 -07001504TEST(BinderRpc, Java) {
1505#if !defined(__ANDROID__)
1506 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1507 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1508 "to binderHostDeviceTest. Hence, just disable this test on host.";
1509#endif // !__ANDROID__
1510 sp<IServiceManager> sm = defaultServiceManager();
1511 ASSERT_NE(nullptr, sm);
1512 // Any Java service with non-empty getInterfaceDescriptor() would do.
1513 // Let's pick batteryproperties.
1514 auto binder = sm->checkService(String16("batteryproperties"));
1515 ASSERT_NE(nullptr, binder);
1516 auto descriptor = binder->getInterfaceDescriptor();
1517 ASSERT_GE(descriptor.size(), 0);
1518 ASSERT_EQ(OK, binder->pingBinder());
1519
1520 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001521 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001522 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001523 auto socket = rpcServer->releaseServer();
1524
1525 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001526 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1527
Yifan Honge3caaf22022-01-12 14:46:56 -08001528 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1529 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001530 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001531 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1532 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001533 << statusToString(setRpcClientDebugStatus);
1534 GTEST_SKIP();
1535 }
1536
1537 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001538
1539 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001540 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001541 auto rpcBinder = rpcSession->getRootObject();
1542 ASSERT_NE(nullptr, rpcBinder);
1543
1544 ASSERT_EQ(OK, rpcBinder->pingBinder());
1545
1546 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1547 << "getInterfaceDescriptor should not crash system_server";
1548 ASSERT_EQ(OK, rpcBinder->pingBinder());
1549}
1550
Yifan Hong702115c2021-06-24 15:39:18 -07001551INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1552 BinderRpcSimple::PrintTestParam);
1553
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001554class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001555public:
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001556 using Param = std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001557 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001558
1559 // A server that handles client socket connections.
1560 class Server {
1561 public:
1562 explicit Server() {}
1563 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001564 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001565 [[nodiscard]] AssertionResult setUp(
1566 const Param& param,
1567 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
1568 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001569 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001570 switch (socketType) {
1571 case SocketType::PRECONNECTED: {
1572 return AssertionFailure() << "Not supported by this test";
1573 } break;
1574 case SocketType::UNIX: {
1575 auto addr = allocateSocketAddress();
1576 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1577 if (status != OK) {
1578 return AssertionFailure()
1579 << "setupUnixDomainServer: " << statusToString(status);
1580 }
1581 mConnectToServer = [addr] {
1582 return connectTo(UnixSocketAddress(addr.c_str()));
1583 };
1584 } break;
1585 case SocketType::VSOCK: {
1586 auto port = allocateVsockPort();
1587 auto status = rpcServer->setupVsockServer(port);
1588 if (status != OK) {
1589 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1590 }
1591 mConnectToServer = [port] {
1592 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1593 };
1594 } break;
1595 case SocketType::INET: {
1596 unsigned int port;
1597 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1598 if (status != OK) {
1599 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1600 }
1601 mConnectToServer = [port] {
1602 const char* addr = kLocalInetAddress;
1603 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1604 if (aiStart == nullptr) return base::unique_fd{};
1605 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1606 auto fd = connectTo(
1607 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1608 if (fd.ok()) return fd;
1609 }
1610 ALOGE("None of the socket address resolved for %s:%u can be connected",
1611 addr, port);
1612 return base::unique_fd{};
1613 };
1614 }
1615 }
1616 mFd = rpcServer->releaseServer();
1617 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001618 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001619 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1620 mSetup = true;
1621 return AssertionSuccess();
1622 }
1623 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1624 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1625 return mCertVerifier;
1626 }
1627 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1628 void start() {
1629 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1630 mThread = std::make_unique<std::thread>(&Server::run, this);
1631 }
1632 void run() {
1633 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1634
1635 std::vector<std::thread> threads;
1636 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1637 base::unique_fd acceptedFd(
1638 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1639 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1640 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1641 }
1642
1643 for (auto& thread : threads) thread.join();
1644 }
1645 void handleOne(android::base::unique_fd acceptedFd) {
1646 ASSERT_TRUE(acceptedFd.ok());
1647 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1648 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001649 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001650 }
Yifan Honge07d2732021-09-13 21:59:14 -07001651 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001652 shutdown();
1653 join();
1654 }
1655 void shutdown() { mFdTrigger->trigger(); }
1656
1657 void setPostConnect(
1658 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1659 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001660 }
1661
1662 private:
1663 std::unique_ptr<std::thread> mThread;
1664 ConnectToServer mConnectToServer;
1665 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1666 base::unique_fd mFd;
1667 std::unique_ptr<RpcTransportCtx> mCtx;
1668 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1669 std::make_shared<RpcCertificateVerifierSimple>();
1670 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001671 // The function invoked after connection and handshake. By default, it is
1672 // |defaultPostConnect| that sends |kMessage| to the client.
1673 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1674 Server::defaultPostConnect;
1675
1676 void join() {
1677 if (mThread != nullptr) {
1678 mThread->join();
1679 mThread = nullptr;
1680 }
1681 }
1682
1683 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1684 FdTrigger* fdTrigger) {
1685 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001686 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001687 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
1688 std::nullopt);
Yifan Hong67519322021-09-13 18:51:16 -07001689 if (status != OK) return AssertionFailure() << statusToString(status);
1690 return AssertionSuccess();
1691 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001692 };
1693
1694 class Client {
1695 public:
1696 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1697 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001698 [[nodiscard]] AssertionResult setUp(const Param& param) {
1699 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001700 mFdTrigger = FdTrigger::make();
1701 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1702 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1703 return AssertionSuccess();
1704 }
1705 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1706 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1707 return mCertVerifier;
1708 }
Yifan Hong67519322021-09-13 18:51:16 -07001709 // connect() and do handshake
1710 bool setUpTransport() {
1711 mFd = mConnectToServer();
1712 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1713 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1714 return mClientTransport != nullptr;
1715 }
1716 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1717 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1718 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001719 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001720 status_t readStatus =
1721 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
1722 std::nullopt);
Yifan Hong67519322021-09-13 18:51:16 -07001723 if (readStatus != OK) {
1724 return AssertionFailure() << statusToString(readStatus);
1725 }
1726 if (readMessage != expectedMessage) {
1727 return AssertionFailure()
1728 << "Expected " << expectedMessage << ", actual " << readMessage;
1729 }
1730 return AssertionSuccess();
1731 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001732 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001733 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001734 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1735 return;
1736 }
1737 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001738 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001739 }
1740
1741 private:
1742 ConnectToServer mConnectToServer;
1743 base::unique_fd mFd;
1744 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1745 std::unique_ptr<RpcTransportCtx> mCtx;
1746 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1747 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001748 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001749 };
1750
1751 // Make A trust B.
1752 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001753 static status_t trust(RpcSecurity rpcSecurity,
1754 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1755 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001756 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001757 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1758 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1759 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001760 }
1761
1762 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001763};
1764
1765class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1766public:
1767 using Server = RpcTransportTestUtils::Server;
1768 using Client = RpcTransportTestUtils::Client;
1769 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1770 auto [socketType, rpcSecurity, certificateFormat] = info.param;
1771 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1772 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
1773 return ret;
1774 }
1775 static std::vector<ParamType> getRpcTranportTestParams() {
1776 std::vector<ParamType> ret;
1777 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1778 for (auto rpcSecurity : RpcSecurityValues()) {
1779 switch (rpcSecurity) {
1780 case RpcSecurity::RAW: {
1781 ret.emplace_back(socketType, rpcSecurity, std::nullopt);
1782 } break;
1783 case RpcSecurity::TLS: {
1784 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM);
1785 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER);
1786 } break;
1787 }
1788 }
1789 }
1790 return ret;
1791 }
1792 template <typename A, typename B>
1793 status_t trust(const A& a, const B& b) {
1794 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1795 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1796 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001797};
1798
1799TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001800 auto server = std::make_unique<Server>();
1801 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001802
1803 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001804 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001805
1806 ASSERT_EQ(OK, trust(&client, server));
1807 ASSERT_EQ(OK, trust(server, &client));
1808
1809 server->start();
1810 client.run();
1811}
1812
1813TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001814 auto server = std::make_unique<Server>();
1815 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001816
1817 std::vector<Client> clients;
1818 for (int i = 0; i < 2; i++) {
1819 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001820 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001821 ASSERT_EQ(OK, trust(&client, server));
1822 ASSERT_EQ(OK, trust(server, &client));
1823 }
1824
1825 server->start();
1826 for (auto& client : clients) client.run();
1827}
1828
1829TEST_P(RpcTransportTest, UntrustedServer) {
1830 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1831
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001832 auto untrustedServer = std::make_unique<Server>();
1833 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001834
1835 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001836 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001837
1838 ASSERT_EQ(OK, trust(untrustedServer, &client));
1839
1840 untrustedServer->start();
1841
1842 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1843 // the client can't verify the server's identity.
1844 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1845 client.run(handshakeOk);
1846}
1847TEST_P(RpcTransportTest, MaliciousServer) {
1848 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001849 auto validServer = std::make_unique<Server>();
1850 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001851
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001852 auto maliciousServer = std::make_unique<Server>();
1853 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001854
1855 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001856 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001857
1858 ASSERT_EQ(OK, trust(&client, validServer));
1859 ASSERT_EQ(OK, trust(validServer, &client));
1860 ASSERT_EQ(OK, trust(maliciousServer, &client));
1861
1862 maliciousServer->start();
1863
1864 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1865 // the client can't verify the server's identity.
1866 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1867 client.run(handshakeOk);
1868}
1869
1870TEST_P(RpcTransportTest, UntrustedClient) {
1871 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001872 auto server = std::make_unique<Server>();
1873 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001874
1875 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001876 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001877
1878 ASSERT_EQ(OK, trust(&client, server));
1879
1880 server->start();
1881
1882 // For TLS, Client should be able to verify server's identity, so client should see
1883 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1884 // identity and should drop the connection, so client shouldn't be able to read anything.
1885 bool readOk = rpcSecurity != RpcSecurity::TLS;
1886 client.run(true, readOk);
1887}
1888
1889TEST_P(RpcTransportTest, MaliciousClient) {
1890 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001891 auto server = std::make_unique<Server>();
1892 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001893
1894 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001895 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001896 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001897 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001898
1899 ASSERT_EQ(OK, trust(&validClient, server));
1900 ASSERT_EQ(OK, trust(&maliciousClient, server));
1901
1902 server->start();
1903
1904 // See UntrustedClient.
1905 bool readOk = rpcSecurity != RpcSecurity::TLS;
1906 maliciousClient.run(true, readOk);
1907}
1908
Yifan Hong67519322021-09-13 18:51:16 -07001909TEST_P(RpcTransportTest, Trigger) {
1910 std::string msg2 = ", world!";
1911 std::mutex writeMutex;
1912 std::condition_variable writeCv;
1913 bool shouldContinueWriting = false;
1914 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001915 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001916 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001917 auto status =
1918 serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1, std::nullopt);
Yifan Hong67519322021-09-13 18:51:16 -07001919 if (status != OK) return AssertionFailure() << statusToString(status);
1920
1921 {
1922 std::unique_lock<std::mutex> lock(writeMutex);
1923 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1924 return AssertionFailure() << "write barrier not cleared in time!";
1925 }
1926 }
1927
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001928 iovec msg2Iov{msg2.data(), msg2.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001929 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt);
Steven Morelandc591b472021-09-16 13:56:11 -07001930 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001931 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001932 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001933 << statusToString(status);
1934 return AssertionSuccess();
1935 };
1936
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001937 auto server = std::make_unique<Server>();
1938 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001939
1940 // Set up client
1941 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001942 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001943
1944 // Exchange keys
1945 ASSERT_EQ(OK, trust(&client, server));
1946 ASSERT_EQ(OK, trust(server, &client));
1947
1948 server->setPostConnect(serverPostConnect);
1949
Yifan Hong67519322021-09-13 18:51:16 -07001950 server->start();
1951 // connect() to server and do handshake
1952 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001953 // read the first message. This ensures that server has finished handshake and start handling
1954 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001955 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001956 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1957 // write is on an FdTrigger that has been shut down.
1958 server->shutdown();
1959 // Continues server thread to write the second message.
1960 {
Yifan Hong22211f82021-09-14 12:32:25 -07001961 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001962 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001963 }
Yifan Hong22211f82021-09-14 12:32:25 -07001964 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001965 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001966 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001967 // On the client side, second read fails with DEAD_OBJECT
1968 ASSERT_FALSE(client.readMessage(msg2));
1969}
1970
Yifan Hong1deca4b2021-09-10 16:16:44 -07001971INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001972 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001973 RpcTransportTest::PrintParamInfo);
1974
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001975class RpcTransportTlsKeyTest
1976 : public testing::TestWithParam<std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat>> {
1977public:
1978 template <typename A, typename B>
1979 status_t trust(const A& a, const B& b) {
1980 auto [socketType, certificateFormat, keyFormat] = GetParam();
1981 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1982 }
1983 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1984 auto [socketType, certificateFormat, keyFormat] = info.param;
1985 auto ret = PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1986 "_key_" + PrintToString(keyFormat);
1987 return ret;
1988 };
1989};
1990
1991TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
1992 auto [socketType, certificateFormat, keyFormat] = GetParam();
1993
1994 std::vector<uint8_t> pkeyData, certData;
1995 {
1996 auto pkey = makeKeyPairForSelfSignedCert();
1997 ASSERT_NE(nullptr, pkey);
1998 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1999 ASSERT_NE(nullptr, cert);
2000 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2001 certData = serializeCertificate(cert.get(), certificateFormat);
2002 }
2003
2004 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2005 auto desCert = deserializeCertificate(certData, certificateFormat);
2006 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
2007 auto utilsParam =
2008 std::make_tuple(socketType, RpcSecurity::TLS, std::make_optional(certificateFormat));
2009
2010 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2011 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2012
2013 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2014 ASSERT_TRUE(client.setUp(utilsParam));
2015
2016 ASSERT_EQ(OK, trust(&client, server));
2017 ASSERT_EQ(OK, trust(server, &client));
2018
2019 server->start();
2020 client.run();
2021}
2022
2023INSTANTIATE_TEST_CASE_P(
2024 BinderRpc, RpcTransportTlsKeyTest,
2025 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2026 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
2027 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER)),
2028 RpcTransportTlsKeyTest::PrintParamInfo);
2029
Steven Morelandc1635952021-04-01 16:20:47 +00002030} // namespace android
2031
2032int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002033 ::testing::InitGoogleTest(&argc, argv);
2034 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002035
Steven Moreland5553ac42020-11-11 02:14:45 +00002036 return RUN_ALL_TESTS();
2037}