blob: c2639e7c67819189815a5d2721ec2639fcadbcfb [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) {
653 server->setPerSessionRootObject([&](const sockaddr* addr,
654 socklen_t len) {
655 sp<MyBinderRpcTest> service = sp<MyBinderRpcTest>::make();
656 switch (addr->sa_family) {
657 case AF_UNIX:
658 // nothing to save
659 break;
660 case AF_VSOCK:
661 CHECK_EQ(len, sizeof(sockaddr_vm));
662 service->port = reinterpret_cast<const sockaddr_vm*>(addr)
663 ->svm_port;
664 break;
665 case AF_INET:
666 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700667 service->port =
668 ntohs(reinterpret_cast<const sockaddr_in*>(addr)
669 ->sin_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700670 break;
671 case AF_INET6:
672 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700673 service->port =
674 ntohs(reinterpret_cast<const sockaddr_in6*>(addr)
675 ->sin6_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700676 break;
677 default:
678 LOG_ALWAYS_FATAL("Unrecognized address family %d",
679 addr->sa_family);
680 }
681 service->server = server;
682 return service;
683 });
684 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000685 };
686
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000687 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000688 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
689
690 return ret;
691 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700692
693 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
694 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000695};
696
Steven Morelandc1635952021-04-01 16:20:47 +0000697TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000698 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000699 ASSERT_NE(proc.rootBinder, nullptr);
700 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
701}
702
Steven Moreland4cf688f2021-03-31 01:48:58 +0000703TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000704 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000705 ASSERT_NE(proc.rootBinder, nullptr);
706 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
707}
708
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000709TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000710 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000711 for (auto session : proc.proc.sessions) {
712 ASSERT_NE(nullptr, session.root);
713 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000714 }
715}
716
Steven Moreland51c44a92021-10-14 16:50:35 -0700717TEST_P(BinderRpc, SeparateRootObject) {
718 SocketType type = std::get<0>(GetParam());
719 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
720 // we can't get port numbers for unix sockets
721 return;
722 }
723
724 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
725
726 int port1 = 0;
727 EXPECT_OK(proc.rootIface->getClientPort(&port1));
728
729 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
730 int port2;
731 EXPECT_OK(rootIface2->getClientPort(&port2));
732
733 // we should have a different IBinderRpcTest object created for each
734 // session, because we use setPerSessionRootObject
735 EXPECT_NE(port1, port2);
736}
737
Steven Morelandc1635952021-04-01 16:20:47 +0000738TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000739 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000740 Parcel data;
741 Parcel reply;
742 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
743}
744
Steven Moreland67753c32021-04-02 18:45:19 +0000745TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700746 auto proc1 = createRpcTestSocketServerProcess({});
747 auto proc2 = createRpcTestSocketServerProcess({});
748
749 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000750
751 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700752 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000753 p1.writeInt32(3);
754
Steven Moreland2034eff2021-10-13 11:24:35 -0700755 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, p1.dataSize()));
756 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
757
Steven Moreland67753c32021-04-02 18:45:19 +0000758 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700759 p2.markForBinder(proc2.rootBinder);
760 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000761
762 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
763 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
764}
765
Steven Morelandc1635952021-04-01 16:20:47 +0000766TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000767 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000768 Parcel data;
769 data.markForBinder(proc.rootBinder);
770 Parcel reply;
771 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
772}
773
Steven Morelandc1635952021-04-01 16:20:47 +0000774TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000775 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000776 EXPECT_OK(proc.rootIface->sendString("asdf"));
777}
778
Steven Morelandc1635952021-04-01 16:20:47 +0000779TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000780 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000781 std::string doubled;
782 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
783 EXPECT_EQ("cool cool ", doubled);
784}
785
Steven Morelandc1635952021-04-01 16:20:47 +0000786TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000787 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000788 std::string single = std::string(1024, 'a');
789 std::string doubled;
790 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
791 EXPECT_EQ(single + single, doubled);
792}
793
Steven Morelandc1635952021-04-01 16:20:47 +0000794TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000795 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000796
797 int32_t pingResult;
798 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
799 EXPECT_EQ(OK, pingResult);
800
801 EXPECT_EQ(0, MyBinderRpcSession::gNum);
802}
803
Steven Morelandc1635952021-04-01 16:20:47 +0000804TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000805 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000806
807 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
808 sp<IBinder> outBinder;
809 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
810 EXPECT_EQ(inBinder, outBinder);
811
812 wp<IBinder> weak = inBinder;
813 inBinder = nullptr;
814 outBinder = nullptr;
815
816 // Force reading a reply, to process any pending dec refs from the other
817 // process (the other process will process dec refs there before processing
818 // the ping here).
819 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
820
821 EXPECT_EQ(nullptr, weak.promote());
822
823 EXPECT_EQ(0, MyBinderRpcSession::gNum);
824}
825
Steven Morelandc1635952021-04-01 16:20:47 +0000826TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000827 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000828
829 sp<IBinderRpcSession> session;
830 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
831
832 sp<IBinder> inBinder = IInterface::asBinder(session);
833 sp<IBinder> outBinder;
834 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
835 EXPECT_EQ(inBinder, outBinder);
836
837 wp<IBinder> weak = inBinder;
838 session = nullptr;
839 inBinder = nullptr;
840 outBinder = nullptr;
841
842 // Force reading a reply, to process any pending dec refs from the other
843 // process (the other process will process dec refs there before processing
844 // the ping here).
845 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
846
847 EXPECT_EQ(nullptr, weak.promote());
848}
849
Steven Morelandc1635952021-04-01 16:20:47 +0000850TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000851 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000852
853 sp<IBinder> outBinder;
854 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
855 EXPECT_EQ(nullptr, outBinder);
856}
857
Steven Morelandc1635952021-04-01 16:20:47 +0000858TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000859 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000860
861 IBinder* ptr = nullptr;
862 {
863 sp<IBinder> binder = new BBinder();
864 ptr = binder.get();
865 EXPECT_OK(proc.rootIface->holdBinder(binder));
866 }
867
868 sp<IBinder> held;
869 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
870
871 EXPECT_EQ(held.get(), ptr);
872
873 // stop holding binder, because we test to make sure references are cleaned
874 // up
875 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
876 // and flush ref counts
877 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
878}
879
880// START TESTS FOR LIMITATIONS OF SOCKET BINDER
881// These are behavioral differences form regular binder, where certain usecases
882// aren't supported.
883
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000884TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000885 auto proc1 = createRpcTestSocketServerProcess({});
886 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000887
888 sp<IBinder> outBinder;
889 EXPECT_EQ(INVALID_OPERATION,
890 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
891}
892
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000893TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000894 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000895
896 sp<IBinder> outBinder;
897 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000898 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000899 .transactionError());
900}
901
Steven Morelandc1635952021-04-01 16:20:47 +0000902TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000903 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000904
905 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
906 sp<IBinder> outBinder;
907 EXPECT_EQ(INVALID_OPERATION,
908 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
909}
910
Steven Morelandc1635952021-04-01 16:20:47 +0000911TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000912 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000913
914 // for historical reasons, IServiceManager interface only returns the
915 // exception code
916 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
917 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
918}
919
920// END TESTS FOR LIMITATIONS OF SOCKET BINDER
921
Steven Morelandc1635952021-04-01 16:20:47 +0000922TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000923 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000924
925 sp<IBinder> outBinder;
926 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
927 EXPECT_EQ(proc.rootBinder, outBinder);
928}
929
Steven Morelandc1635952021-04-01 16:20:47 +0000930TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000931 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000932
933 auto nastyNester = sp<MyBinderRpcTest>::make();
934 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
935
936 wp<IBinder> weak = nastyNester;
937 nastyNester = nullptr;
938 EXPECT_EQ(nullptr, weak.promote());
939}
940
Steven Morelandc1635952021-04-01 16:20:47 +0000941TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000942 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000943
944 sp<IBinder> a;
945 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
946
947 sp<IBinder> b;
948 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
949
950 EXPECT_EQ(a, b);
951}
952
Steven Morelandc1635952021-04-01 16:20:47 +0000953TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000954 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000955
956 sp<IBinder> a;
957 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
958 wp<IBinder> weak = a;
959 a = nullptr;
960
961 sp<IBinder> b;
962 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
963
964 // this is the wrong behavior, since BpBinder
965 // doesn't implement onIncStrongAttempted
966 // but make sure there is no crash
967 EXPECT_EQ(nullptr, weak.promote());
968
969 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
970
971 // In order to fix this:
972 // - need to have incStrongAttempted reflected across IPC boundary (wait for
973 // response to promote - round trip...)
974 // - sendOnLastWeakRef, to delete entries out of RpcState table
975 EXPECT_EQ(b, weak.promote());
976}
977
978#define expectSessions(expected, iface) \
979 do { \
980 int session; \
981 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
982 EXPECT_EQ(expected, session); \
983 } while (false)
984
Steven Morelandc1635952021-04-01 16:20:47 +0000985TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000986 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000987
988 sp<IBinderRpcSession> session;
989 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
990 std::string out;
991 EXPECT_OK(session->getName(&out));
992 EXPECT_EQ("aoeu", out);
993
994 expectSessions(1, proc.rootIface);
995 session = nullptr;
996 expectSessions(0, proc.rootIface);
997}
998
Steven Morelandc1635952021-04-01 16:20:47 +0000999TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001000 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001001
1002 std::vector<sp<IBinderRpcSession>> sessions;
1003
1004 for (size_t i = 0; i < 15; i++) {
1005 expectSessions(i, proc.rootIface);
1006 sp<IBinderRpcSession> session;
1007 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
1008 sessions.push_back(session);
1009 }
1010 expectSessions(sessions.size(), proc.rootIface);
1011 for (size_t i = 0; i < sessions.size(); i++) {
1012 std::string out;
1013 EXPECT_OK(sessions.at(i)->getName(&out));
1014 EXPECT_EQ(std::to_string(i), out);
1015 }
1016 expectSessions(sessions.size(), proc.rootIface);
1017
1018 while (!sessions.empty()) {
1019 sessions.pop_back();
1020 expectSessions(sessions.size(), proc.rootIface);
1021 }
1022 expectSessions(0, proc.rootIface);
1023}
1024
1025size_t epochMillis() {
1026 using std::chrono::duration_cast;
1027 using std::chrono::milliseconds;
1028 using std::chrono::seconds;
1029 using std::chrono::system_clock;
1030 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1031}
1032
Steven Morelandc1635952021-04-01 16:20:47 +00001033TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001034 constexpr size_t kNumThreads = 10;
1035
Steven Moreland4313d7e2021-07-15 23:41:22 +00001036 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001037
1038 EXPECT_OK(proc.rootIface->lock());
1039
1040 // block all but one thread taking locks
1041 std::vector<std::thread> ts;
1042 for (size_t i = 0; i < kNumThreads - 1; i++) {
1043 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
1044 }
1045
1046 usleep(100000); // give chance for calls on other threads
1047
1048 // other calls still work
1049 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1050
1051 constexpr size_t blockTimeMs = 500;
1052 size_t epochMsBefore = epochMillis();
1053 // after this, we should never see a response within this time
1054 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
1055
1056 // this call should be blocked for blockTimeMs
1057 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1058
1059 size_t epochMsAfter = epochMillis();
1060 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
1061
1062 for (auto& t : ts) t.join();
1063}
1064
Yifan Hong1f44f982021-10-08 17:16:47 -07001065void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
1066 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001067 size_t epochMsBefore = epochMillis();
1068
1069 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -07001070 for (size_t i = 0; i < numCalls; i++) {
1071 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +00001072 }
1073
1074 for (auto& t : ts) t.join();
1075
1076 size_t epochMsAfter = epochMillis();
1077
Yifan Hong1f44f982021-10-08 17:16:47 -07001078 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +00001079
1080 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -07001081 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
1082}
1083
1084TEST_P(BinderRpc, ThreadPoolOverSaturated) {
1085 constexpr size_t kNumThreads = 10;
1086 constexpr size_t kNumCalls = kNumThreads + 3;
1087 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1088 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
1089}
1090
1091TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
1092 constexpr size_t kNumThreads = 20;
1093 constexpr size_t kNumOutgoingConnections = 10;
1094 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
1095 auto proc = createRpcTestSocketServerProcess(
1096 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
1097 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +00001098}
1099
Steven Morelandc1635952021-04-01 16:20:47 +00001100TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001101 constexpr size_t kNumClientThreads = 10;
1102 constexpr size_t kNumServerThreads = 10;
1103 constexpr size_t kNumCalls = 100;
1104
Steven Moreland4313d7e2021-07-15 23:41:22 +00001105 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001106
1107 std::vector<std::thread> threads;
1108 for (size_t i = 0; i < kNumClientThreads; i++) {
1109 threads.push_back(std::thread([&] {
1110 for (size_t j = 0; j < kNumCalls; j++) {
1111 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001112 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001113 EXPECT_EQ(proc.rootBinder, out);
1114 }
1115 }));
1116 }
1117
1118 for (auto& t : threads) t.join();
1119}
1120
Steven Moreland925ba0a2021-09-17 18:06:32 -07001121static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
1122 std::vector<std::thread> threads;
1123 for (size_t i = 0; i < threadCount; i++) {
1124 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
1125 }
1126 for (auto& t : threads) t.join();
1127}
1128
Steven Morelandc6046982021-04-20 00:49:42 +00001129TEST_P(BinderRpc, OnewayStressTest) {
1130 constexpr size_t kNumClientThreads = 10;
1131 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -07001132 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +00001133
Steven Moreland4313d7e2021-07-15 23:41:22 +00001134 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001135
1136 std::vector<std::thread> threads;
1137 for (size_t i = 0; i < kNumClientThreads; i++) {
1138 threads.push_back(std::thread([&] {
1139 for (size_t j = 0; j < kNumCalls; j++) {
1140 EXPECT_OK(proc.rootIface->sendString("a"));
1141 }
Steven Morelandc6046982021-04-20 00:49:42 +00001142 }));
1143 }
1144
1145 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -07001146
1147 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +00001148}
1149
Steven Morelandc1635952021-04-01 16:20:47 +00001150TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001151 constexpr size_t kReallyLongTimeMs = 100;
1152 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1153
Steven Moreland4313d7e2021-07-15 23:41:22 +00001154 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001155
1156 size_t epochMsBefore = epochMillis();
1157
1158 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1159
1160 size_t epochMsAfter = epochMillis();
1161 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1162}
1163
Steven Morelandc1635952021-04-01 16:20:47 +00001164TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001165 constexpr size_t kNumSleeps = 10;
1166 constexpr size_t kNumExtraServerThreads = 4;
1167 constexpr size_t kSleepMs = 50;
1168
1169 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001170 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001171
1172 EXPECT_OK(proc.rootIface->lock());
1173
Steven Moreland1c678802021-09-17 16:48:47 -07001174 size_t epochMsBefore = epochMillis();
1175
1176 // all these *Async commands should be queued on the server sequentially,
1177 // even though there are multiple threads.
1178 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001179 proc.rootIface->sleepMsAsync(kSleepMs);
1180 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001181 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1182
Steven Moreland1c678802021-09-17 16:48:47 -07001183 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +00001184 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -07001185
Steven Moreland5553ac42020-11-11 02:14:45 +00001186 size_t epochMsAfter = epochMillis();
1187
1188 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001189
Steven Moreland925ba0a2021-09-17 18:06:32 -07001190 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001191}
1192
Steven Morelandd45be622021-06-04 02:19:37 +00001193TEST_P(BinderRpc, OnewayCallExhaustion) {
1194 constexpr size_t kNumClients = 2;
1195 constexpr size_t kTooLongMs = 1000;
1196
Steven Moreland4313d7e2021-07-15 23:41:22 +00001197 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001198
1199 // Build up oneway calls on the second session to make sure it terminates
1200 // and shuts down. The first session should be unaffected (proc destructor
1201 // checks the first session).
1202 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1203
1204 std::vector<std::thread> threads;
1205 for (size_t i = 0; i < kNumClients; i++) {
1206 // one of these threads will get stuck queueing a transaction once the
1207 // socket fills up, the other will be able to fill up transactions on
1208 // this object
1209 threads.push_back(std::thread([&] {
1210 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1211 }
1212 }));
1213 }
1214 for (auto& t : threads) t.join();
1215
1216 Status status = iface->sleepMsAsync(kTooLongMs);
1217 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1218
Steven Moreland798e0d12021-07-14 23:19:25 +00001219 // now that it has died, wait for the remote session to shutdown
1220 std::vector<int32_t> remoteCounts;
1221 do {
1222 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1223 } while (remoteCounts.size() == kNumClients);
1224
Steven Morelandd45be622021-06-04 02:19:37 +00001225 // the second session should be shutdown in the other process by the time we
1226 // are able to join above (it'll only be hung up once it finishes processing
1227 // any pending commands). We need to erase this session from the record
1228 // here, so that the destructor for our session won't check that this
1229 // session is valid, but we still want it to test the other session.
1230 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1231}
1232
Steven Moreland659416d2021-05-11 00:47:50 +00001233TEST_P(BinderRpc, Callbacks) {
1234 const static std::string kTestString = "good afternoon!";
1235
Steven Morelandc7d40132021-06-10 03:42:11 +00001236 for (bool callIsOneway : {true, false}) {
1237 for (bool callbackIsOneway : {true, false}) {
1238 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001239 auto proc = createRpcTestSocketServerProcess(
1240 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001241 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001242
Steven Morelandc7d40132021-06-10 03:42:11 +00001243 if (callIsOneway) {
1244 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1245 kTestString));
1246 } else {
1247 EXPECT_OK(
1248 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1249 }
Steven Moreland659416d2021-05-11 00:47:50 +00001250
Steven Morelandc7d40132021-06-10 03:42:11 +00001251 using std::literals::chrono_literals::operator""s;
1252 std::unique_lock<std::mutex> _l(cb->mMutex);
1253 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001254
Steven Morelandc7d40132021-06-10 03:42:11 +00001255 EXPECT_EQ(cb->mValues.size(), 1)
1256 << "callIsOneway: " << callIsOneway
1257 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1258 if (cb->mValues.empty()) continue;
1259 EXPECT_EQ(cb->mValues.at(0), kTestString)
1260 << "callIsOneway: " << callIsOneway
1261 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001262
Steven Morelandc7d40132021-06-10 03:42:11 +00001263 // since we are severing the connection, we need to go ahead and
1264 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001265 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1266 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1267 }
Steven Moreland659416d2021-05-11 00:47:50 +00001268
Steven Moreland1b304292021-07-15 22:59:34 +00001269 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001270 // need to manually shut it down
1271 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001272
Steven Morelandc7d40132021-06-10 03:42:11 +00001273 proc.expectAlreadyShutdown = true;
1274 }
Steven Moreland659416d2021-05-11 00:47:50 +00001275 }
1276 }
1277}
1278
Steven Moreland195edb82021-06-08 02:44:39 +00001279TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001280 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001281 auto cb = sp<MyBinderRpcCallback>::make();
1282
1283 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1284 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1285}
1286
Steven Morelandc1635952021-04-01 16:20:47 +00001287TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001288 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001289 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001290
1291 // make sure there is some state during crash
1292 // 1. we hold their binder
1293 sp<IBinderRpcSession> session;
1294 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1295 // 2. they hold our binder
1296 sp<IBinder> binder = new BBinder();
1297 EXPECT_OK(proc.rootIface->holdBinder(binder));
1298
1299 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1300 << "Do death cleanup: " << doDeathCleanup;
1301
Steven Morelandaf4ca712021-05-24 23:22:08 +00001302 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001303 }
1304}
1305
Steven Morelandd7302072021-05-15 01:32:04 +00001306TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Morelanda83191d2021-10-27 10:14:53 -07001307 bool okToFork = ProcessState::selfOrNull() == nullptr;
1308
Steven Moreland4313d7e2021-07-15 23:41:22 +00001309 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001310
Steven Morelanda83191d2021-10-27 10:14:53 -07001311 // If this process has used ProcessState already, then the forked process
1312 // cannot use it at all. If this process hasn't used it (depending on the
1313 // order tests are run), then the forked process can use it, and we'll only
1314 // catch the invalid usage the second time. Such is the burden of global
1315 // state!
1316 if (okToFork) {
1317 // we can't allocate IPCThreadState so actually the first time should
1318 // succeed :(
1319 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1320 }
Steven Morelandd7302072021-05-15 01:32:04 +00001321
1322 // second time! we catch the error :)
1323 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1324
Steven Morelandaf4ca712021-05-24 23:22:08 +00001325 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001326}
1327
Steven Moreland37aff182021-03-26 02:04:16 +00001328TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001329 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001330
1331 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1332 ASSERT_NE(binder, nullptr);
1333
1334 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1335}
1336
1337TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001338 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001339
1340 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1341 ASSERT_NE(binder, nullptr);
1342
1343 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1344 ASSERT_NE(ndkBinder, nullptr);
1345
1346 std::string out;
1347 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1348 ASSERT_TRUE(status.isOk()) << status.getDescription();
1349 ASSERT_EQ("aoeuaoeu", out);
1350}
1351
Steven Moreland5553ac42020-11-11 02:14:45 +00001352ssize_t countFds() {
1353 DIR* dir = opendir("/proc/self/fd/");
1354 if (dir == nullptr) return -1;
1355 ssize_t ret = 0;
1356 dirent* ent;
1357 while ((ent = readdir(dir)) != nullptr) ret++;
1358 closedir(dir);
1359 return ret;
1360}
1361
Steven Morelandc1635952021-04-01 16:20:47 +00001362TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001363 ssize_t beforeFds = countFds();
1364 ASSERT_GE(beforeFds, 0);
1365 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001366 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001367 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1368 }
1369 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1370}
1371
Devin Moore800b2252021-10-15 16:22:57 +00001372TEST_P(BinderRpc, AidlDelegatorTest) {
1373 auto proc = createRpcTestSocketServerProcess({});
1374 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1375 ASSERT_NE(nullptr, myDelegator);
1376
1377 std::string doubled;
1378 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1379 EXPECT_EQ("cool cool ", doubled);
1380}
1381
Steven Morelandda573042021-06-12 01:13:45 +00001382static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001383 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001384 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001385 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland1eab3452021-08-05 16:56:20 -07001386 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1387 if (status == -EAFNOSUPPORT) {
1388 return false;
1389 }
1390 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1391 }
Steven Morelandda573042021-06-12 01:13:45 +00001392 server->start();
1393
Yifan Hongfdd9f692021-09-09 15:12:52 -07001394 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001395 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001396 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001397 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1398 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001399}
1400
Yifan Hong1deca4b2021-09-10 16:16:44 -07001401static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1402 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1403
1404 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001405
1406 static bool hasVsockLoopback = testSupportVsockLoopback();
1407
1408 if (hasVsockLoopback) {
1409 ret.push_back(SocketType::VSOCK);
1410 }
1411
1412 return ret;
1413}
1414
Yifan Hong702115c2021-06-24 15:39:18 -07001415INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1416 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1417 ::testing::ValuesIn(RpcSecurityValues())),
1418 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001419
Yifan Hong702115c2021-06-24 15:39:18 -07001420class BinderRpcServerRootObject
1421 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001422
1423TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1424 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1425 auto setRootObject = [](bool isStrong) -> SetFn {
1426 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1427 };
1428
Yifan Hong702115c2021-06-24 15:39:18 -07001429 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1430 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001431 auto binder1 = sp<BBinder>::make();
1432 IBinder* binderRaw1 = binder1.get();
1433 setRootObject(isStrong1)(server.get(), binder1);
1434 EXPECT_EQ(binderRaw1, server->getRootObject());
1435 binder1.clear();
1436 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1437
1438 auto binder2 = sp<BBinder>::make();
1439 IBinder* binderRaw2 = binder2.get();
1440 setRootObject(isStrong2)(server.get(), binder2);
1441 EXPECT_EQ(binderRaw2, server->getRootObject());
1442 binder2.clear();
1443 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1444}
1445
1446INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001447 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1448 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001449
Yifan Hong1a235852021-05-13 16:07:47 -07001450class OneOffSignal {
1451public:
1452 // If notify() was previously called, or is called within |duration|, return true; else false.
1453 template <typename R, typename P>
1454 bool wait(std::chrono::duration<R, P> duration) {
1455 std::unique_lock<std::mutex> lock(mMutex);
1456 return mCv.wait_for(lock, duration, [this] { return mValue; });
1457 }
1458 void notify() {
1459 std::unique_lock<std::mutex> lock(mMutex);
1460 mValue = true;
1461 lock.unlock();
1462 mCv.notify_all();
1463 }
1464
1465private:
1466 std::mutex mMutex;
1467 std::condition_variable mCv;
1468 bool mValue = false;
1469};
1470
Yifan Hong702115c2021-06-24 15:39:18 -07001471TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001472 auto addr = allocateSocketAddress();
Yifan Hong702115c2021-06-24 15:39:18 -07001473 auto server = RpcServer::make(newFactory(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001474 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001475 auto joinEnds = std::make_shared<OneOffSignal>();
1476
1477 // If things are broken and the thread never stops, don't block other tests. Because the thread
1478 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1479 // shared pointers are passed.
1480 std::thread([server, joinEnds] {
1481 server->join();
1482 joinEnds->notify();
1483 }).detach();
1484
1485 bool shutdown = false;
1486 for (int i = 0; i < 10 && !shutdown; i++) {
1487 usleep(300 * 1000); // 300ms; total 3s
1488 if (server->shutdown()) shutdown = true;
1489 }
1490 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1491
1492 ASSERT_TRUE(joinEnds->wait(2s))
1493 << "After server->shutdown() returns true, join() did not stop after 2s";
1494}
1495
Yifan Hong194acf22021-06-29 18:44:56 -07001496TEST(BinderRpc, Java) {
1497#if !defined(__ANDROID__)
1498 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1499 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1500 "to binderHostDeviceTest. Hence, just disable this test on host.";
1501#endif // !__ANDROID__
1502 sp<IServiceManager> sm = defaultServiceManager();
1503 ASSERT_NE(nullptr, sm);
1504 // Any Java service with non-empty getInterfaceDescriptor() would do.
1505 // Let's pick batteryproperties.
1506 auto binder = sm->checkService(String16("batteryproperties"));
1507 ASSERT_NE(nullptr, binder);
1508 auto descriptor = binder->getInterfaceDescriptor();
1509 ASSERT_GE(descriptor.size(), 0);
1510 ASSERT_EQ(OK, binder->pingBinder());
1511
1512 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001513 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001514 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001515 auto socket = rpcServer->releaseServer();
1516
1517 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001518 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1519
Yifan Honge3caaf22022-01-12 14:46:56 -08001520 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1521 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001522 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001523 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1524 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001525 << statusToString(setRpcClientDebugStatus);
1526 GTEST_SKIP();
1527 }
1528
1529 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001530
1531 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001532 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001533 auto rpcBinder = rpcSession->getRootObject();
1534 ASSERT_NE(nullptr, rpcBinder);
1535
1536 ASSERT_EQ(OK, rpcBinder->pingBinder());
1537
1538 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1539 << "getInterfaceDescriptor should not crash system_server";
1540 ASSERT_EQ(OK, rpcBinder->pingBinder());
1541}
1542
Yifan Hong702115c2021-06-24 15:39:18 -07001543INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1544 BinderRpcSimple::PrintTestParam);
1545
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001546class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001547public:
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001548 using Param = std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001549 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001550
1551 // A server that handles client socket connections.
1552 class Server {
1553 public:
1554 explicit Server() {}
1555 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001556 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001557 [[nodiscard]] AssertionResult setUp(
1558 const Param& param,
1559 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
1560 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001561 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001562 switch (socketType) {
1563 case SocketType::PRECONNECTED: {
1564 return AssertionFailure() << "Not supported by this test";
1565 } break;
1566 case SocketType::UNIX: {
1567 auto addr = allocateSocketAddress();
1568 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1569 if (status != OK) {
1570 return AssertionFailure()
1571 << "setupUnixDomainServer: " << statusToString(status);
1572 }
1573 mConnectToServer = [addr] {
1574 return connectTo(UnixSocketAddress(addr.c_str()));
1575 };
1576 } break;
1577 case SocketType::VSOCK: {
1578 auto port = allocateVsockPort();
1579 auto status = rpcServer->setupVsockServer(port);
1580 if (status != OK) {
1581 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1582 }
1583 mConnectToServer = [port] {
1584 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1585 };
1586 } break;
1587 case SocketType::INET: {
1588 unsigned int port;
1589 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1590 if (status != OK) {
1591 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1592 }
1593 mConnectToServer = [port] {
1594 const char* addr = kLocalInetAddress;
1595 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1596 if (aiStart == nullptr) return base::unique_fd{};
1597 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1598 auto fd = connectTo(
1599 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1600 if (fd.ok()) return fd;
1601 }
1602 ALOGE("None of the socket address resolved for %s:%u can be connected",
1603 addr, port);
1604 return base::unique_fd{};
1605 };
1606 }
1607 }
1608 mFd = rpcServer->releaseServer();
1609 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001610 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001611 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1612 mSetup = true;
1613 return AssertionSuccess();
1614 }
1615 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1616 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1617 return mCertVerifier;
1618 }
1619 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1620 void start() {
1621 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1622 mThread = std::make_unique<std::thread>(&Server::run, this);
1623 }
1624 void run() {
1625 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1626
1627 std::vector<std::thread> threads;
1628 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1629 base::unique_fd acceptedFd(
1630 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1631 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1632 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1633 }
1634
1635 for (auto& thread : threads) thread.join();
1636 }
1637 void handleOne(android::base::unique_fd acceptedFd) {
1638 ASSERT_TRUE(acceptedFd.ok());
1639 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1640 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001641 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001642 }
Yifan Honge07d2732021-09-13 21:59:14 -07001643 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001644 shutdown();
1645 join();
1646 }
1647 void shutdown() { mFdTrigger->trigger(); }
1648
1649 void setPostConnect(
1650 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1651 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001652 }
1653
1654 private:
1655 std::unique_ptr<std::thread> mThread;
1656 ConnectToServer mConnectToServer;
1657 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1658 base::unique_fd mFd;
1659 std::unique_ptr<RpcTransportCtx> mCtx;
1660 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1661 std::make_shared<RpcCertificateVerifierSimple>();
1662 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001663 // The function invoked after connection and handshake. By default, it is
1664 // |defaultPostConnect| that sends |kMessage| to the client.
1665 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1666 Server::defaultPostConnect;
1667
1668 void join() {
1669 if (mThread != nullptr) {
1670 mThread->join();
1671 mThread = nullptr;
1672 }
1673 }
1674
1675 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1676 FdTrigger* fdTrigger) {
1677 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001678 iovec messageIov{message.data(), message.size()};
1679 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1, {});
Yifan Hong67519322021-09-13 18:51:16 -07001680 if (status != OK) return AssertionFailure() << statusToString(status);
1681 return AssertionSuccess();
1682 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001683 };
1684
1685 class Client {
1686 public:
1687 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1688 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001689 [[nodiscard]] AssertionResult setUp(const Param& param) {
1690 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001691 mFdTrigger = FdTrigger::make();
1692 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1693 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1694 return AssertionSuccess();
1695 }
1696 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1697 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1698 return mCertVerifier;
1699 }
Yifan Hong67519322021-09-13 18:51:16 -07001700 // connect() and do handshake
1701 bool setUpTransport() {
1702 mFd = mConnectToServer();
1703 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1704 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1705 return mClientTransport != nullptr;
1706 }
1707 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1708 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1709 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001710 iovec readMessageIov{readMessage.data(), readMessage.size()};
1711 status_t readStatus = mClientTransport->interruptableReadFully(mFdTrigger.get(),
1712 &readMessageIov, 1, {});
Yifan Hong67519322021-09-13 18:51:16 -07001713 if (readStatus != OK) {
1714 return AssertionFailure() << statusToString(readStatus);
1715 }
1716 if (readMessage != expectedMessage) {
1717 return AssertionFailure()
1718 << "Expected " << expectedMessage << ", actual " << readMessage;
1719 }
1720 return AssertionSuccess();
1721 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001722 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001723 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001724 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1725 return;
1726 }
1727 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001728 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001729 }
1730
1731 private:
1732 ConnectToServer mConnectToServer;
1733 base::unique_fd mFd;
1734 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1735 std::unique_ptr<RpcTransportCtx> mCtx;
1736 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1737 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001738 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001739 };
1740
1741 // Make A trust B.
1742 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001743 static status_t trust(RpcSecurity rpcSecurity,
1744 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1745 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001746 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001747 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1748 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1749 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001750 }
1751
1752 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001753};
1754
1755class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1756public:
1757 using Server = RpcTransportTestUtils::Server;
1758 using Client = RpcTransportTestUtils::Client;
1759 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1760 auto [socketType, rpcSecurity, certificateFormat] = info.param;
1761 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1762 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
1763 return ret;
1764 }
1765 static std::vector<ParamType> getRpcTranportTestParams() {
1766 std::vector<ParamType> ret;
1767 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1768 for (auto rpcSecurity : RpcSecurityValues()) {
1769 switch (rpcSecurity) {
1770 case RpcSecurity::RAW: {
1771 ret.emplace_back(socketType, rpcSecurity, std::nullopt);
1772 } break;
1773 case RpcSecurity::TLS: {
1774 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM);
1775 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER);
1776 } break;
1777 }
1778 }
1779 }
1780 return ret;
1781 }
1782 template <typename A, typename B>
1783 status_t trust(const A& a, const B& b) {
1784 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1785 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1786 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001787};
1788
1789TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001790 auto server = std::make_unique<Server>();
1791 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001792
1793 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001794 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001795
1796 ASSERT_EQ(OK, trust(&client, server));
1797 ASSERT_EQ(OK, trust(server, &client));
1798
1799 server->start();
1800 client.run();
1801}
1802
1803TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001804 auto server = std::make_unique<Server>();
1805 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001806
1807 std::vector<Client> clients;
1808 for (int i = 0; i < 2; i++) {
1809 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001810 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001811 ASSERT_EQ(OK, trust(&client, server));
1812 ASSERT_EQ(OK, trust(server, &client));
1813 }
1814
1815 server->start();
1816 for (auto& client : clients) client.run();
1817}
1818
1819TEST_P(RpcTransportTest, UntrustedServer) {
1820 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1821
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001822 auto untrustedServer = std::make_unique<Server>();
1823 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001824
1825 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001826 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001827
1828 ASSERT_EQ(OK, trust(untrustedServer, &client));
1829
1830 untrustedServer->start();
1831
1832 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1833 // the client can't verify the server's identity.
1834 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1835 client.run(handshakeOk);
1836}
1837TEST_P(RpcTransportTest, MaliciousServer) {
1838 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001839 auto validServer = std::make_unique<Server>();
1840 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001841
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001842 auto maliciousServer = std::make_unique<Server>();
1843 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001844
1845 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001846 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001847
1848 ASSERT_EQ(OK, trust(&client, validServer));
1849 ASSERT_EQ(OK, trust(validServer, &client));
1850 ASSERT_EQ(OK, trust(maliciousServer, &client));
1851
1852 maliciousServer->start();
1853
1854 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1855 // the client can't verify the server's identity.
1856 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1857 client.run(handshakeOk);
1858}
1859
1860TEST_P(RpcTransportTest, UntrustedClient) {
1861 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001862 auto server = std::make_unique<Server>();
1863 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001864
1865 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001866 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001867
1868 ASSERT_EQ(OK, trust(&client, server));
1869
1870 server->start();
1871
1872 // For TLS, Client should be able to verify server's identity, so client should see
1873 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1874 // identity and should drop the connection, so client shouldn't be able to read anything.
1875 bool readOk = rpcSecurity != RpcSecurity::TLS;
1876 client.run(true, readOk);
1877}
1878
1879TEST_P(RpcTransportTest, MaliciousClient) {
1880 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001881 auto server = std::make_unique<Server>();
1882 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001883
1884 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001885 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001886 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001887 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001888
1889 ASSERT_EQ(OK, trust(&validClient, server));
1890 ASSERT_EQ(OK, trust(&maliciousClient, server));
1891
1892 server->start();
1893
1894 // See UntrustedClient.
1895 bool readOk = rpcSecurity != RpcSecurity::TLS;
1896 maliciousClient.run(true, readOk);
1897}
1898
Yifan Hong67519322021-09-13 18:51:16 -07001899TEST_P(RpcTransportTest, Trigger) {
1900 std::string msg2 = ", world!";
1901 std::mutex writeMutex;
1902 std::condition_variable writeCv;
1903 bool shouldContinueWriting = false;
1904 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001905 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001906 iovec messageIov{message.data(), message.size()};
1907 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1, {});
Yifan Hong67519322021-09-13 18:51:16 -07001908 if (status != OK) return AssertionFailure() << statusToString(status);
1909
1910 {
1911 std::unique_lock<std::mutex> lock(writeMutex);
1912 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1913 return AssertionFailure() << "write barrier not cleared in time!";
1914 }
1915 }
1916
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001917 iovec msg2Iov{msg2.data(), msg2.size()};
1918 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, {});
Steven Morelandc591b472021-09-16 13:56:11 -07001919 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001920 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001921 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001922 << statusToString(status);
1923 return AssertionSuccess();
1924 };
1925
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001926 auto server = std::make_unique<Server>();
1927 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001928
1929 // Set up client
1930 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001931 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001932
1933 // Exchange keys
1934 ASSERT_EQ(OK, trust(&client, server));
1935 ASSERT_EQ(OK, trust(server, &client));
1936
1937 server->setPostConnect(serverPostConnect);
1938
Yifan Hong67519322021-09-13 18:51:16 -07001939 server->start();
1940 // connect() to server and do handshake
1941 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001942 // read the first message. This ensures that server has finished handshake and start handling
1943 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001944 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001945 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1946 // write is on an FdTrigger that has been shut down.
1947 server->shutdown();
1948 // Continues server thread to write the second message.
1949 {
Yifan Hong22211f82021-09-14 12:32:25 -07001950 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001951 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001952 }
Yifan Hong22211f82021-09-14 12:32:25 -07001953 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001954 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001955 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001956 // On the client side, second read fails with DEAD_OBJECT
1957 ASSERT_FALSE(client.readMessage(msg2));
1958}
1959
Yifan Hong1deca4b2021-09-10 16:16:44 -07001960INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001961 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001962 RpcTransportTest::PrintParamInfo);
1963
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001964class RpcTransportTlsKeyTest
1965 : public testing::TestWithParam<std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat>> {
1966public:
1967 template <typename A, typename B>
1968 status_t trust(const A& a, const B& b) {
1969 auto [socketType, certificateFormat, keyFormat] = GetParam();
1970 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1971 }
1972 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1973 auto [socketType, certificateFormat, keyFormat] = info.param;
1974 auto ret = PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1975 "_key_" + PrintToString(keyFormat);
1976 return ret;
1977 };
1978};
1979
1980TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
1981 auto [socketType, certificateFormat, keyFormat] = GetParam();
1982
1983 std::vector<uint8_t> pkeyData, certData;
1984 {
1985 auto pkey = makeKeyPairForSelfSignedCert();
1986 ASSERT_NE(nullptr, pkey);
1987 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1988 ASSERT_NE(nullptr, cert);
1989 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1990 certData = serializeCertificate(cert.get(), certificateFormat);
1991 }
1992
1993 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1994 auto desCert = deserializeCertificate(certData, certificateFormat);
1995 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
1996 auto utilsParam =
1997 std::make_tuple(socketType, RpcSecurity::TLS, std::make_optional(certificateFormat));
1998
1999 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2000 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2001
2002 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2003 ASSERT_TRUE(client.setUp(utilsParam));
2004
2005 ASSERT_EQ(OK, trust(&client, server));
2006 ASSERT_EQ(OK, trust(server, &client));
2007
2008 server->start();
2009 client.run();
2010}
2011
2012INSTANTIATE_TEST_CASE_P(
2013 BinderRpc, RpcTransportTlsKeyTest,
2014 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2015 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
2016 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER)),
2017 RpcTransportTlsKeyTest::PrintParamInfo);
2018
Steven Morelandc1635952021-04-01 16:20:47 +00002019} // namespace android
2020
2021int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002022 ::testing::InitGoogleTest(&argc, argv);
2023 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002024
Steven Moreland5553ac42020-11-11 02:14:45 +00002025 return RUN_ALL_TESTS();
2026}