blob: d68c6fffd1bdd0693516428b1c79fa61ac2b2b69 [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>
Steven Moreland37aff182021-03-26 02:04:16 +000025#include <android/binder_auto_utils.h>
26#include <android/binder_libbinder.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000027#include <binder/Binder.h>
28#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000029#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000030#include <binder/IServiceManager.h>
31#include <binder/ProcessState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000032#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000033#include <binder/RpcSession.h>
Yifan Honge0e53282021-09-23 18:37:21 -070034#include <binder/RpcTlsTestUtils.h>
Yifan Hongb1ce80c2021-09-17 22:10:58 -070035#include <binder/RpcTlsUtils.h>
Yifan Hong702115c2021-06-24 15:39:18 -070036#include <binder/RpcTransport.h>
37#include <binder/RpcTransportRaw.h>
Yifan Hong92409752021-07-30 21:25:32 -070038#include <binder/RpcTransportTls.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000039#include <gtest/gtest.h>
40
Steven Morelandc1635952021-04-01 16:20:47 +000041#include <chrono>
42#include <cstdlib>
43#include <iostream>
44#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000045#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000046
Yifan Hong1deca4b2021-09-10 16:16:44 -070047#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000048#include <sys/prctl.h>
49#include <unistd.h>
50
Yifan Hong1deca4b2021-09-10 16:16:44 -070051#include "../FdTrigger.h"
Steven Moreland4198a122021-08-03 17:37:58 -070052#include "../RpcSocketAddress.h" // for testing preconnected clients
Yifan Hongffdaf952021-09-17 18:08:38 -070053#include "../RpcState.h" // for debugging
54#include "../vm_sockets.h" // for VMADDR_*
Steven Moreland5553ac42020-11-11 02:14:45 +000055
Yifan Hong1a235852021-05-13 16:07:47 -070056using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070057using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070058using testing::AssertionFailure;
59using testing::AssertionResult;
60using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070061
Steven Moreland5553ac42020-11-11 02:14:45 +000062namespace android {
63
Steven Morelandbf57bce2021-07-26 15:26:12 -070064static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
65 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Devin Mooref3b9c4f2021-08-03 15:50:13 +000066const char* kLocalInetAddress = "127.0.0.1";
Steven Morelandbf57bce2021-07-26 15:26:12 -070067
Yifan Hong92409752021-07-30 21:25:32 -070068enum class RpcSecurity { RAW, TLS };
Yifan Hong702115c2021-06-24 15:39:18 -070069
70static inline std::vector<RpcSecurity> RpcSecurityValues() {
Yifan Hong92409752021-07-30 21:25:32 -070071 return {RpcSecurity::RAW, RpcSecurity::TLS};
Yifan Hong702115c2021-06-24 15:39:18 -070072}
73
Yifan Hong13c90062021-09-09 14:59:53 -070074static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(
Yifan Hongffdaf952021-09-17 18:08:38 -070075 RpcSecurity rpcSecurity, std::shared_ptr<RpcCertificateVerifier> verifier = nullptr,
76 std::unique_ptr<RpcAuth> auth = nullptr) {
Yifan Hong702115c2021-06-24 15:39:18 -070077 switch (rpcSecurity) {
78 case RpcSecurity::RAW:
79 return RpcTransportCtxFactoryRaw::make();
Yifan Hong13c90062021-09-09 14:59:53 -070080 case RpcSecurity::TLS: {
Yifan Hong13c90062021-09-09 14:59:53 -070081 if (verifier == nullptr) {
82 verifier = std::make_shared<RpcCertificateVerifierSimple>();
83 }
Yifan Hongffdaf952021-09-17 18:08:38 -070084 if (auth == nullptr) {
85 auth = std::make_unique<RpcAuthSelfSigned>();
86 }
87 return RpcTransportCtxFactoryTls::make(std::move(verifier), std::move(auth));
Yifan Hong13c90062021-09-09 14:59:53 -070088 }
Yifan Hong702115c2021-06-24 15:39:18 -070089 default:
90 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
91 }
92}
93
Steven Moreland1fda67b2021-04-02 18:35:50 +000094TEST(BinderRpcParcel, EntireParcelFormatted) {
95 Parcel p;
96 p.writeInt32(3);
97
98 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
99}
100
Yifan Hong702115c2021-06-24 15:39:18 -0700101class BinderRpcSimple : public ::testing::TestWithParam<RpcSecurity> {
102public:
103 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
104 return newFactory(info.param)->toCString();
105 }
106};
107
108TEST_P(BinderRpcSimple, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700109 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
110 int sinkFd = sink.get();
Yifan Hong702115c2021-06-24 15:39:18 -0700111 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -0700112 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
113 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 Moreland5553ac42020-11-11 02:14:45 +0000177
178 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000179 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000180 return Status::ok();
181 }
182 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000183 *strstr = str + str;
184 return Status::ok();
185 }
Steven Moreland736664b2021-05-01 04:27:25 +0000186 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000187 sp<RpcServer> spServer = server.promote();
188 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000189 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
190 }
Steven Moreland736664b2021-05-01 04:27:25 +0000191 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000192 for (auto session : spServer->listSessions()) {
193 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000194 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000195 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000196 return Status::ok();
197 }
198 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
199 if (binder == nullptr) {
200 std::cout << "Received null binder!" << std::endl;
201 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
202 }
203 *out = binder->pingBinder();
204 return Status::ok();
205 }
206 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
207 *out = binder;
208 return Status::ok();
209 }
210 static sp<IBinder> mHeldBinder;
211 Status holdBinder(const sp<IBinder>& binder) override {
212 mHeldBinder = binder;
213 return Status::ok();
214 }
215 Status getHeldBinder(sp<IBinder>* held) override {
216 *held = mHeldBinder;
217 return Status::ok();
218 }
219 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
220 if (count <= 0) return Status::ok();
221 return binder->nestMe(this, count - 1);
222 }
223 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
224 static sp<IBinder> binder = new BBinder;
225 *out = binder;
226 return Status::ok();
227 }
228 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
229 *out = new MyBinderRpcSession(name);
230 return Status::ok();
231 }
232 Status getNumOpenSessions(int32_t* out) override {
233 *out = MyBinderRpcSession::gNum;
234 return Status::ok();
235 }
236
237 std::mutex blockMutex;
238 Status lock() override {
239 blockMutex.lock();
240 return Status::ok();
241 }
242 Status unlockInMsAsync(int32_t ms) override {
243 usleep(ms * 1000);
244 blockMutex.unlock();
245 return Status::ok();
246 }
247 Status lockUnlock() override {
248 std::lock_guard<std::mutex> _l(blockMutex);
249 return Status::ok();
250 }
251
252 Status sleepMs(int32_t ms) override {
253 usleep(ms * 1000);
254 return Status::ok();
255 }
256
257 Status sleepMsAsync(int32_t ms) override {
258 // In-process binder calls are asynchronous, but the call to this method
259 // is synchronous wrt its client. This in/out-process threading model
260 // diffentiation is a classic binder leaky abstraction (for better or
261 // worse) and is preserved here the way binder sockets plugs itself
262 // into BpBinder, as nothing is changed at the higher levels
263 // (IInterface) which result in this behavior.
264 return sleepMs(ms);
265 }
266
Steven Moreland659416d2021-05-11 00:47:50 +0000267 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
268 const std::string& value) override {
269 if (callback == nullptr) {
270 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
271 }
272
273 if (delayed) {
274 std::thread([=]() {
275 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000276 Status status = doCallback(callback, oneway, false, value);
277 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000278 }).detach();
279 return Status::ok();
280 }
281
282 if (oneway) {
283 return callback->sendOnewayCallback(value);
284 }
285
286 return callback->sendCallback(value);
287 }
288
Steven Morelandc7d40132021-06-10 03:42:11 +0000289 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
290 const std::string& value) override {
291 return doCallback(callback, oneway, delayed, value);
292 }
293
Steven Moreland5553ac42020-11-11 02:14:45 +0000294 Status die(bool cleanup) override {
295 if (cleanup) {
296 exit(1);
297 } else {
298 _exit(1);
299 }
300 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000301
302 Status scheduleShutdown() override {
303 sp<RpcServer> strongServer = server.promote();
304 if (strongServer == nullptr) {
305 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
306 }
307 std::thread([=] {
308 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
309 }).detach();
310 return Status::ok();
311 }
312
Steven Morelandd7302072021-05-15 01:32:04 +0000313 Status useKernelBinderCallingId() override {
314 // this is WRONG! It does not make sense when using RPC binder, and
315 // because it is SO wrong, and so much code calls this, it should abort!
316
317 (void)IPCThreadState::self()->getCallingPid();
318 return Status::ok();
319 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000320};
321sp<IBinder> MyBinderRpcTest::mHeldBinder;
322
323class Process {
324public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700325 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700326 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
327 android::base::borrowed_fd /* readEnd */)>& f) {
328 android::base::unique_fd childWriteEnd;
329 android::base::unique_fd childReadEnd;
330 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
331 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000332 if (0 == (mPid = fork())) {
333 // racey: assume parent doesn't crash before this is set
334 prctl(PR_SET_PDEATHSIG, SIGHUP);
335
Yifan Hong1deca4b2021-09-10 16:16:44 -0700336 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000337
338 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000339 }
340 }
341 ~Process() {
342 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000343 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000344 }
345 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700346 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700347 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000348
349private:
350 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700351 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700352 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000353};
354
355static std::string allocateSocketAddress() {
356 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000357 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700358 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
359 unlink(ret.c_str());
360 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000361};
362
Steven Morelandda573042021-06-12 01:13:45 +0000363static unsigned int allocateVsockPort() {
364 static unsigned int vsockPort = 3456;
365 return vsockPort++;
366}
367
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000368struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000369 // reference to process hosting a socket server
370 Process host;
371
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000372 struct SessionInfo {
373 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000374 sp<IBinder> root;
375 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000376
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000377 // client session objects associated with other process
378 // each one represents a separate session
379 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000380
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000381 ProcessSession(ProcessSession&&) = default;
382 ~ProcessSession() {
383 for (auto& session : sessions) {
384 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000385 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000386
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000387 for (auto& info : sessions) {
388 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000389
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000390 EXPECT_NE(nullptr, session);
391 EXPECT_NE(nullptr, session->state());
392 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000393
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000394 wp<RpcSession> weakSession = session;
395 session = nullptr;
396 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000397 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000398 }
399};
400
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000401// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000402// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000403struct BinderRpcTestProcessSession {
404 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000405
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000406 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000407 sp<IBinder> rootBinder;
408
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000410 sp<IBinderRpcTest> rootIface;
411
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000412 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000413 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000414
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000415 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
416 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000417 EXPECT_NE(nullptr, rootIface);
418 if (rootIface == nullptr) return;
419
Steven Morelandaf4ca712021-05-24 23:22:08 +0000420 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000421 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000422 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000423 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000424 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000425 for (auto remoteCount : remoteCounts) {
426 EXPECT_EQ(remoteCount, 1);
427 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000428
Steven Moreland798e0d12021-07-14 23:19:25 +0000429 // even though it is on another thread, shutdown races with
430 // the transaction reply being written
431 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
432 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
433 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000434 }
435
436 rootIface = nullptr;
437 rootBinder = nullptr;
438 }
439};
440
Steven Morelandc1635952021-04-01 16:20:47 +0000441enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700442 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000443 UNIX,
444 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700445 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000446};
Yifan Hong702115c2021-06-24 15:39:18 -0700447static inline std::string PrintToString(SocketType socketType) {
448 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700449 case SocketType::PRECONNECTED:
450 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000451 case SocketType::UNIX:
452 return "unix_domain_socket";
453 case SocketType::VSOCK:
454 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700455 case SocketType::INET:
456 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000457 default:
458 LOG_ALWAYS_FATAL("Unknown socket type");
459 return "";
460 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000461}
Steven Morelandda573042021-06-12 01:13:45 +0000462
Yifan Hong1deca4b2021-09-10 16:16:44 -0700463static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700464 base::unique_fd serverFd(
465 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
466 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700467 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
468 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700469
470 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
471 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700472 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
473 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700474 }
475 return serverFd;
476}
477
Yifan Hong702115c2021-06-24 15:39:18 -0700478class BinderRpc : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000479public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000480 struct Options {
481 size_t numThreads = 1;
482 size_t numSessions = 1;
483 size_t numIncomingConnections = 0;
Yifan Hong1f44f982021-10-08 17:16:47 -0700484 size_t numOutgoingConnections = SIZE_MAX;
Steven Moreland4313d7e2021-07-15 23:41:22 +0000485 };
486
Yifan Hong702115c2021-06-24 15:39:18 -0700487 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
488 auto [type, security] = info.param;
489 return PrintToString(type) + "_" + newFactory(security)->toCString();
490 }
491
Yifan Hong1deca4b2021-09-10 16:16:44 -0700492 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
493 uint64_t length = str.length();
494 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
495 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
496 }
497
498 static inline std::string readString(android::base::borrowed_fd fd) {
499 uint64_t length;
500 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
501 std::string ret(length, '\0');
502 CHECK(android::base::ReadFully(fd, ret.data(), length));
503 return ret;
504 }
505
506 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
507 Parcel parcel;
508 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
509 writeString(fd,
510 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
511 }
512
513 template <typename T>
514 static inline T readFromFd(android::base::borrowed_fd fd) {
515 std::string data = readString(fd);
516 Parcel parcel;
517 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
518 T object;
519 CHECK_EQ(OK, object.readFromParcel(&parcel));
520 return object;
521 }
522
Steven Morelandc1635952021-04-01 16:20:47 +0000523 // This creates a new process serving an interface on a certain number of
524 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000525 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000526 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
527 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000528
Yifan Hong702115c2021-06-24 15:39:18 -0700529 SocketType socketType = std::get<0>(GetParam());
530 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000531
Steven Morelandda573042021-06-12 01:13:45 +0000532 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000533 std::string addr = allocateSocketAddress();
Steven Morelandc1635952021-04-01 16:20:47 +0000534
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000535 auto ret = ProcessSession{
Yifan Hong1deca4b2021-09-10 16:16:44 -0700536 .host = Process([&](android::base::borrowed_fd writeEnd,
537 android::base::borrowed_fd readEnd) {
538 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
539 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
Steven Morelandc1635952021-04-01 16:20:47 +0000540
541 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000542 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000543
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000544 unsigned int outPort = 0;
545
Steven Morelandc1635952021-04-01 16:20:47 +0000546 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700547 case SocketType::PRECONNECTED:
548 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000549 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700550 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000551 break;
552 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700553 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000554 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700555 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700556 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700557 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700558 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700559 }
Steven Morelandc1635952021-04-01 16:20:47 +0000560 default:
561 LOG_ALWAYS_FATAL("Unknown socket type");
562 }
563
Yifan Hong1deca4b2021-09-10 16:16:44 -0700564 BinderRpcTestServerInfo serverInfo;
565 serverInfo.port = static_cast<int64_t>(outPort);
Yifan Hong9734cfc2021-09-13 16:14:09 -0700566 serverInfo.cert.data = server->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700567 writeToFd(writeEnd, serverInfo);
568 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
569
570 if (rpcSecurity == RpcSecurity::TLS) {
571 for (const auto& clientCert : clientInfo.certs) {
572 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700573 certVerifier
574 ->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
575 clientCert.data));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700576 }
577 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000578
Steven Moreland611d15f2021-05-01 01:28:27 +0000579 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000580
Steven Morelandf137de92021-04-24 01:54:26 +0000581 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000582
583 // Another thread calls shutdown. Wait for it to complete.
584 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000585 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000586 };
587
Yifan Hong1deca4b2021-09-10 16:16:44 -0700588 std::vector<sp<RpcSession>> sessions;
589 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
590 for (size_t i = 0; i < options.numSessions; i++) {
591 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
592 }
593
594 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
595 BinderRpcTestClientInfo clientInfo;
596 for (const auto& session : sessions) {
597 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700598 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700599 }
600 writeToFd(ret.host.writeEnd(), clientInfo);
601
602 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700603 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700604 CHECK_NE(0, serverInfo.port);
605 }
606
607 if (rpcSecurity == RpcSecurity::TLS) {
608 const auto& serverCert = serverInfo.cert.data;
609 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700610 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
611 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700612 }
613
Steven Moreland2372f9d2021-08-05 15:42:01 -0700614 status_t status;
615
Yifan Hong1deca4b2021-09-10 16:16:44 -0700616 for (const auto& session : sessions) {
Yifan Hong10423062021-10-08 16:26:32 -0700617 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700618 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000619
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000620 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700621 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700622 status = session->setupPreconnectedClient({}, [=]() {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700623 return connectTo(UnixSocketAddress(addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700624 });
Steven Moreland4198a122021-08-03 17:37:58 -0700625 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000626 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700627 status = session->setupUnixDomainClient(addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000628 break;
629 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700630 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000631 break;
632 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700633 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000634 break;
635 default:
636 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000637 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700638 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000639 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000640 }
Steven Morelandc1635952021-04-01 16:20:47 +0000641 return ret;
642 }
643
Steven Moreland4313d7e2021-07-15 23:41:22 +0000644 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000645 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000646 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000647 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000648 sp<MyBinderRpcTest> service =
649 new MyBinderRpcTest;
650 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000651 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000652 }),
653 };
654
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000655 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000656 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
657
658 return ret;
659 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700660
661 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
662 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000663};
664
Steven Morelandc1635952021-04-01 16:20:47 +0000665TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000666 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000667 ASSERT_NE(proc.rootBinder, nullptr);
668 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
669}
670
Steven Moreland4cf688f2021-03-31 01:48:58 +0000671TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000672 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000673 ASSERT_NE(proc.rootBinder, nullptr);
674 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
675}
676
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000677TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000678 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000679 for (auto session : proc.proc.sessions) {
680 ASSERT_NE(nullptr, session.root);
681 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000682 }
683}
684
Steven Morelandc1635952021-04-01 16:20:47 +0000685TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000686 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000687 Parcel data;
688 Parcel reply;
689 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
690}
691
Steven Moreland67753c32021-04-02 18:45:19 +0000692TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000693 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000694
695 Parcel p1;
696 p1.markForBinder(proc.rootBinder);
697 p1.writeInt32(3);
698
699 Parcel p2;
700
701 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
702 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
703}
704
Steven Morelandc1635952021-04-01 16:20:47 +0000705TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000706 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000707 Parcel data;
708 data.markForBinder(proc.rootBinder);
709 Parcel reply;
710 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
711}
712
Steven Morelandc1635952021-04-01 16:20:47 +0000713TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000714 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000715 EXPECT_OK(proc.rootIface->sendString("asdf"));
716}
717
Steven Morelandc1635952021-04-01 16:20:47 +0000718TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000719 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000720 std::string doubled;
721 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
722 EXPECT_EQ("cool cool ", doubled);
723}
724
Steven Morelandc1635952021-04-01 16:20:47 +0000725TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000726 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000727 std::string single = std::string(1024, 'a');
728 std::string doubled;
729 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
730 EXPECT_EQ(single + single, doubled);
731}
732
Steven Morelandc1635952021-04-01 16:20:47 +0000733TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000734 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000735
736 int32_t pingResult;
737 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
738 EXPECT_EQ(OK, pingResult);
739
740 EXPECT_EQ(0, MyBinderRpcSession::gNum);
741}
742
Steven Morelandc1635952021-04-01 16:20:47 +0000743TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000744 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000745
746 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
747 sp<IBinder> outBinder;
748 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
749 EXPECT_EQ(inBinder, outBinder);
750
751 wp<IBinder> weak = inBinder;
752 inBinder = nullptr;
753 outBinder = nullptr;
754
755 // Force reading a reply, to process any pending dec refs from the other
756 // process (the other process will process dec refs there before processing
757 // the ping here).
758 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
759
760 EXPECT_EQ(nullptr, weak.promote());
761
762 EXPECT_EQ(0, MyBinderRpcSession::gNum);
763}
764
Steven Morelandc1635952021-04-01 16:20:47 +0000765TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000766 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000767
768 sp<IBinderRpcSession> session;
769 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
770
771 sp<IBinder> inBinder = IInterface::asBinder(session);
772 sp<IBinder> outBinder;
773 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
774 EXPECT_EQ(inBinder, outBinder);
775
776 wp<IBinder> weak = inBinder;
777 session = nullptr;
778 inBinder = nullptr;
779 outBinder = nullptr;
780
781 // Force reading a reply, to process any pending dec refs from the other
782 // process (the other process will process dec refs there before processing
783 // the ping here).
784 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
785
786 EXPECT_EQ(nullptr, weak.promote());
787}
788
Steven Morelandc1635952021-04-01 16:20:47 +0000789TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000790 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000791
792 sp<IBinder> outBinder;
793 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
794 EXPECT_EQ(nullptr, outBinder);
795}
796
Steven Morelandc1635952021-04-01 16:20:47 +0000797TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000798 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000799
800 IBinder* ptr = nullptr;
801 {
802 sp<IBinder> binder = new BBinder();
803 ptr = binder.get();
804 EXPECT_OK(proc.rootIface->holdBinder(binder));
805 }
806
807 sp<IBinder> held;
808 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
809
810 EXPECT_EQ(held.get(), ptr);
811
812 // stop holding binder, because we test to make sure references are cleaned
813 // up
814 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
815 // and flush ref counts
816 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
817}
818
819// START TESTS FOR LIMITATIONS OF SOCKET BINDER
820// These are behavioral differences form regular binder, where certain usecases
821// aren't supported.
822
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000823TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000824 auto proc1 = createRpcTestSocketServerProcess({});
825 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000826
827 sp<IBinder> outBinder;
828 EXPECT_EQ(INVALID_OPERATION,
829 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
830}
831
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000832TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000833 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000834
835 sp<IBinder> outBinder;
836 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000837 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000838 .transactionError());
839}
840
Steven Morelandc1635952021-04-01 16:20:47 +0000841TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000842 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000843
844 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
845 sp<IBinder> outBinder;
846 EXPECT_EQ(INVALID_OPERATION,
847 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
848}
849
Steven Morelandc1635952021-04-01 16:20:47 +0000850TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000851 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000852
853 // for historical reasons, IServiceManager interface only returns the
854 // exception code
855 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
856 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
857}
858
859// END TESTS FOR LIMITATIONS OF SOCKET BINDER
860
Steven Morelandc1635952021-04-01 16:20:47 +0000861TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000862 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000863
864 sp<IBinder> outBinder;
865 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
866 EXPECT_EQ(proc.rootBinder, outBinder);
867}
868
Steven Morelandc1635952021-04-01 16:20:47 +0000869TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000870 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000871
872 auto nastyNester = sp<MyBinderRpcTest>::make();
873 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
874
875 wp<IBinder> weak = nastyNester;
876 nastyNester = nullptr;
877 EXPECT_EQ(nullptr, weak.promote());
878}
879
Steven Morelandc1635952021-04-01 16:20:47 +0000880TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000881 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000882
883 sp<IBinder> a;
884 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
885
886 sp<IBinder> b;
887 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
888
889 EXPECT_EQ(a, b);
890}
891
Steven Morelandc1635952021-04-01 16:20:47 +0000892TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000893 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000894
895 sp<IBinder> a;
896 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
897 wp<IBinder> weak = a;
898 a = nullptr;
899
900 sp<IBinder> b;
901 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
902
903 // this is the wrong behavior, since BpBinder
904 // doesn't implement onIncStrongAttempted
905 // but make sure there is no crash
906 EXPECT_EQ(nullptr, weak.promote());
907
908 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
909
910 // In order to fix this:
911 // - need to have incStrongAttempted reflected across IPC boundary (wait for
912 // response to promote - round trip...)
913 // - sendOnLastWeakRef, to delete entries out of RpcState table
914 EXPECT_EQ(b, weak.promote());
915}
916
917#define expectSessions(expected, iface) \
918 do { \
919 int session; \
920 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
921 EXPECT_EQ(expected, session); \
922 } while (false)
923
Steven Morelandc1635952021-04-01 16:20:47 +0000924TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000925 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000926
927 sp<IBinderRpcSession> session;
928 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
929 std::string out;
930 EXPECT_OK(session->getName(&out));
931 EXPECT_EQ("aoeu", out);
932
933 expectSessions(1, proc.rootIface);
934 session = nullptr;
935 expectSessions(0, proc.rootIface);
936}
937
Steven Morelandc1635952021-04-01 16:20:47 +0000938TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000939 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000940
941 std::vector<sp<IBinderRpcSession>> sessions;
942
943 for (size_t i = 0; i < 15; i++) {
944 expectSessions(i, proc.rootIface);
945 sp<IBinderRpcSession> session;
946 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
947 sessions.push_back(session);
948 }
949 expectSessions(sessions.size(), proc.rootIface);
950 for (size_t i = 0; i < sessions.size(); i++) {
951 std::string out;
952 EXPECT_OK(sessions.at(i)->getName(&out));
953 EXPECT_EQ(std::to_string(i), out);
954 }
955 expectSessions(sessions.size(), proc.rootIface);
956
957 while (!sessions.empty()) {
958 sessions.pop_back();
959 expectSessions(sessions.size(), proc.rootIface);
960 }
961 expectSessions(0, proc.rootIface);
962}
963
964size_t epochMillis() {
965 using std::chrono::duration_cast;
966 using std::chrono::milliseconds;
967 using std::chrono::seconds;
968 using std::chrono::system_clock;
969 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
970}
971
Steven Morelandc1635952021-04-01 16:20:47 +0000972TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000973 constexpr size_t kNumThreads = 10;
974
Steven Moreland4313d7e2021-07-15 23:41:22 +0000975 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000976
977 EXPECT_OK(proc.rootIface->lock());
978
979 // block all but one thread taking locks
980 std::vector<std::thread> ts;
981 for (size_t i = 0; i < kNumThreads - 1; i++) {
982 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
983 }
984
985 usleep(100000); // give chance for calls on other threads
986
987 // other calls still work
988 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
989
990 constexpr size_t blockTimeMs = 500;
991 size_t epochMsBefore = epochMillis();
992 // after this, we should never see a response within this time
993 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
994
995 // this call should be blocked for blockTimeMs
996 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
997
998 size_t epochMsAfter = epochMillis();
999 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
1000
1001 for (auto& t : ts) t.join();
1002}
1003
Yifan Hong1f44f982021-10-08 17:16:47 -07001004void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
1005 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001006 size_t epochMsBefore = epochMillis();
1007
1008 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -07001009 for (size_t i = 0; i < numCalls; i++) {
1010 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +00001011 }
1012
1013 for (auto& t : ts) t.join();
1014
1015 size_t epochMsAfter = epochMillis();
1016
Yifan Hong1f44f982021-10-08 17:16:47 -07001017 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +00001018
1019 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -07001020 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
1021}
1022
1023TEST_P(BinderRpc, ThreadPoolOverSaturated) {
1024 constexpr size_t kNumThreads = 10;
1025 constexpr size_t kNumCalls = kNumThreads + 3;
1026 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1027 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
1028}
1029
1030TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
1031 constexpr size_t kNumThreads = 20;
1032 constexpr size_t kNumOutgoingConnections = 10;
1033 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
1034 auto proc = createRpcTestSocketServerProcess(
1035 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
1036 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +00001037}
1038
Steven Morelandc1635952021-04-01 16:20:47 +00001039TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001040 constexpr size_t kNumClientThreads = 10;
1041 constexpr size_t kNumServerThreads = 10;
1042 constexpr size_t kNumCalls = 100;
1043
Steven Moreland4313d7e2021-07-15 23:41:22 +00001044 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001045
1046 std::vector<std::thread> threads;
1047 for (size_t i = 0; i < kNumClientThreads; i++) {
1048 threads.push_back(std::thread([&] {
1049 for (size_t j = 0; j < kNumCalls; j++) {
1050 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001051 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001052 EXPECT_EQ(proc.rootBinder, out);
1053 }
1054 }));
1055 }
1056
1057 for (auto& t : threads) t.join();
1058}
1059
Steven Moreland925ba0a2021-09-17 18:06:32 -07001060static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
1061 std::vector<std::thread> threads;
1062 for (size_t i = 0; i < threadCount; i++) {
1063 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
1064 }
1065 for (auto& t : threads) t.join();
1066}
1067
Steven Morelandc6046982021-04-20 00:49:42 +00001068TEST_P(BinderRpc, OnewayStressTest) {
1069 constexpr size_t kNumClientThreads = 10;
1070 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -07001071 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +00001072
Steven Moreland4313d7e2021-07-15 23:41:22 +00001073 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001074
1075 std::vector<std::thread> threads;
1076 for (size_t i = 0; i < kNumClientThreads; i++) {
1077 threads.push_back(std::thread([&] {
1078 for (size_t j = 0; j < kNumCalls; j++) {
1079 EXPECT_OK(proc.rootIface->sendString("a"));
1080 }
Steven Morelandc6046982021-04-20 00:49:42 +00001081 }));
1082 }
1083
1084 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -07001085
1086 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +00001087}
1088
Steven Morelandc1635952021-04-01 16:20:47 +00001089TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001090 constexpr size_t kReallyLongTimeMs = 100;
1091 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1092
Steven Moreland4313d7e2021-07-15 23:41:22 +00001093 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001094
1095 size_t epochMsBefore = epochMillis();
1096
1097 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1098
1099 size_t epochMsAfter = epochMillis();
1100 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1101}
1102
Steven Morelandc1635952021-04-01 16:20:47 +00001103TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001104 constexpr size_t kNumSleeps = 10;
1105 constexpr size_t kNumExtraServerThreads = 4;
1106 constexpr size_t kSleepMs = 50;
1107
1108 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001109 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001110
1111 EXPECT_OK(proc.rootIface->lock());
1112
Steven Moreland1c678802021-09-17 16:48:47 -07001113 size_t epochMsBefore = epochMillis();
1114
1115 // all these *Async commands should be queued on the server sequentially,
1116 // even though there are multiple threads.
1117 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001118 proc.rootIface->sleepMsAsync(kSleepMs);
1119 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001120 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1121
Steven Moreland1c678802021-09-17 16:48:47 -07001122 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +00001123 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -07001124
Steven Moreland5553ac42020-11-11 02:14:45 +00001125 size_t epochMsAfter = epochMillis();
1126
1127 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001128
Steven Moreland925ba0a2021-09-17 18:06:32 -07001129 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001130}
1131
Steven Morelandd45be622021-06-04 02:19:37 +00001132TEST_P(BinderRpc, OnewayCallExhaustion) {
1133 constexpr size_t kNumClients = 2;
1134 constexpr size_t kTooLongMs = 1000;
1135
Steven Moreland4313d7e2021-07-15 23:41:22 +00001136 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001137
1138 // Build up oneway calls on the second session to make sure it terminates
1139 // and shuts down. The first session should be unaffected (proc destructor
1140 // checks the first session).
1141 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1142
1143 std::vector<std::thread> threads;
1144 for (size_t i = 0; i < kNumClients; i++) {
1145 // one of these threads will get stuck queueing a transaction once the
1146 // socket fills up, the other will be able to fill up transactions on
1147 // this object
1148 threads.push_back(std::thread([&] {
1149 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1150 }
1151 }));
1152 }
1153 for (auto& t : threads) t.join();
1154
1155 Status status = iface->sleepMsAsync(kTooLongMs);
1156 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1157
Steven Moreland798e0d12021-07-14 23:19:25 +00001158 // now that it has died, wait for the remote session to shutdown
1159 std::vector<int32_t> remoteCounts;
1160 do {
1161 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1162 } while (remoteCounts.size() == kNumClients);
1163
Steven Morelandd45be622021-06-04 02:19:37 +00001164 // the second session should be shutdown in the other process by the time we
1165 // are able to join above (it'll only be hung up once it finishes processing
1166 // any pending commands). We need to erase this session from the record
1167 // here, so that the destructor for our session won't check that this
1168 // session is valid, but we still want it to test the other session.
1169 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1170}
1171
Steven Moreland659416d2021-05-11 00:47:50 +00001172TEST_P(BinderRpc, Callbacks) {
1173 const static std::string kTestString = "good afternoon!";
1174
Steven Morelandc7d40132021-06-10 03:42:11 +00001175 for (bool callIsOneway : {true, false}) {
1176 for (bool callbackIsOneway : {true, false}) {
1177 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001178 auto proc = createRpcTestSocketServerProcess(
1179 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001180 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001181
Steven Morelandc7d40132021-06-10 03:42:11 +00001182 if (callIsOneway) {
1183 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1184 kTestString));
1185 } else {
1186 EXPECT_OK(
1187 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1188 }
Steven Moreland659416d2021-05-11 00:47:50 +00001189
Steven Morelandc7d40132021-06-10 03:42:11 +00001190 using std::literals::chrono_literals::operator""s;
1191 std::unique_lock<std::mutex> _l(cb->mMutex);
1192 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001193
Steven Morelandc7d40132021-06-10 03:42:11 +00001194 EXPECT_EQ(cb->mValues.size(), 1)
1195 << "callIsOneway: " << callIsOneway
1196 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1197 if (cb->mValues.empty()) continue;
1198 EXPECT_EQ(cb->mValues.at(0), kTestString)
1199 << "callIsOneway: " << callIsOneway
1200 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001201
Steven Morelandc7d40132021-06-10 03:42:11 +00001202 // since we are severing the connection, we need to go ahead and
1203 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001204 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1205 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1206 }
Steven Moreland659416d2021-05-11 00:47:50 +00001207
Steven Moreland1b304292021-07-15 22:59:34 +00001208 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001209 // need to manually shut it down
1210 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001211
Steven Morelandc7d40132021-06-10 03:42:11 +00001212 proc.expectAlreadyShutdown = true;
1213 }
Steven Moreland659416d2021-05-11 00:47:50 +00001214 }
1215 }
1216}
1217
Steven Moreland195edb82021-06-08 02:44:39 +00001218TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001219 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001220 auto cb = sp<MyBinderRpcCallback>::make();
1221
1222 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1223 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1224}
1225
Steven Morelandc1635952021-04-01 16:20:47 +00001226TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001227 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001228 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001229
1230 // make sure there is some state during crash
1231 // 1. we hold their binder
1232 sp<IBinderRpcSession> session;
1233 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1234 // 2. they hold our binder
1235 sp<IBinder> binder = new BBinder();
1236 EXPECT_OK(proc.rootIface->holdBinder(binder));
1237
1238 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1239 << "Do death cleanup: " << doDeathCleanup;
1240
Steven Morelandaf4ca712021-05-24 23:22:08 +00001241 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001242 }
1243}
1244
Steven Morelandd7302072021-05-15 01:32:04 +00001245TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001246 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001247
1248 // we can't allocate IPCThreadState so actually the first time should
1249 // succeed :(
1250 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1251
1252 // second time! we catch the error :)
1253 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1254
Steven Morelandaf4ca712021-05-24 23:22:08 +00001255 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001256}
1257
Steven Moreland37aff182021-03-26 02:04:16 +00001258TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001259 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001260
1261 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1262 ASSERT_NE(binder, nullptr);
1263
1264 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1265}
1266
1267TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001268 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001269
1270 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1271 ASSERT_NE(binder, nullptr);
1272
1273 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1274 ASSERT_NE(ndkBinder, nullptr);
1275
1276 std::string out;
1277 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1278 ASSERT_TRUE(status.isOk()) << status.getDescription();
1279 ASSERT_EQ("aoeuaoeu", out);
1280}
1281
Steven Moreland5553ac42020-11-11 02:14:45 +00001282ssize_t countFds() {
1283 DIR* dir = opendir("/proc/self/fd/");
1284 if (dir == nullptr) return -1;
1285 ssize_t ret = 0;
1286 dirent* ent;
1287 while ((ent = readdir(dir)) != nullptr) ret++;
1288 closedir(dir);
1289 return ret;
1290}
1291
Steven Morelandc1635952021-04-01 16:20:47 +00001292TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001293 ssize_t beforeFds = countFds();
1294 ASSERT_GE(beforeFds, 0);
1295 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001296 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001297 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1298 }
1299 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1300}
1301
Steven Morelandda573042021-06-12 01:13:45 +00001302static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001303 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001304 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001305 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001306 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland1eab3452021-08-05 16:56:20 -07001307 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1308 if (status == -EAFNOSUPPORT) {
1309 return false;
1310 }
1311 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1312 }
Steven Morelandda573042021-06-12 01:13:45 +00001313 server->start();
1314
Yifan Hongfdd9f692021-09-09 15:12:52 -07001315 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001316 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001317 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001318 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1319 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001320}
1321
Yifan Hong1deca4b2021-09-10 16:16:44 -07001322static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1323 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1324
1325 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001326
1327 static bool hasVsockLoopback = testSupportVsockLoopback();
1328
1329 if (hasVsockLoopback) {
1330 ret.push_back(SocketType::VSOCK);
1331 }
1332
1333 return ret;
1334}
1335
Yifan Hong702115c2021-06-24 15:39:18 -07001336INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1337 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1338 ::testing::ValuesIn(RpcSecurityValues())),
1339 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001340
Yifan Hong702115c2021-06-24 15:39:18 -07001341class BinderRpcServerRootObject
1342 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001343
1344TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1345 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1346 auto setRootObject = [](bool isStrong) -> SetFn {
1347 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1348 };
1349
Yifan Hong702115c2021-06-24 15:39:18 -07001350 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1351 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001352 auto binder1 = sp<BBinder>::make();
1353 IBinder* binderRaw1 = binder1.get();
1354 setRootObject(isStrong1)(server.get(), binder1);
1355 EXPECT_EQ(binderRaw1, server->getRootObject());
1356 binder1.clear();
1357 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1358
1359 auto binder2 = sp<BBinder>::make();
1360 IBinder* binderRaw2 = binder2.get();
1361 setRootObject(isStrong2)(server.get(), binder2);
1362 EXPECT_EQ(binderRaw2, server->getRootObject());
1363 binder2.clear();
1364 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1365}
1366
1367INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001368 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1369 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001370
Yifan Hong1a235852021-05-13 16:07:47 -07001371class OneOffSignal {
1372public:
1373 // If notify() was previously called, or is called within |duration|, return true; else false.
1374 template <typename R, typename P>
1375 bool wait(std::chrono::duration<R, P> duration) {
1376 std::unique_lock<std::mutex> lock(mMutex);
1377 return mCv.wait_for(lock, duration, [this] { return mValue; });
1378 }
1379 void notify() {
1380 std::unique_lock<std::mutex> lock(mMutex);
1381 mValue = true;
1382 lock.unlock();
1383 mCv.notify_all();
1384 }
1385
1386private:
1387 std::mutex mMutex;
1388 std::condition_variable mCv;
1389 bool mValue = false;
1390};
1391
Yifan Hong702115c2021-06-24 15:39:18 -07001392TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001393 auto addr = allocateSocketAddress();
Yifan Hong702115c2021-06-24 15:39:18 -07001394 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong1a235852021-05-13 16:07:47 -07001395 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001396 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001397 auto joinEnds = std::make_shared<OneOffSignal>();
1398
1399 // If things are broken and the thread never stops, don't block other tests. Because the thread
1400 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1401 // shared pointers are passed.
1402 std::thread([server, joinEnds] {
1403 server->join();
1404 joinEnds->notify();
1405 }).detach();
1406
1407 bool shutdown = false;
1408 for (int i = 0; i < 10 && !shutdown; i++) {
1409 usleep(300 * 1000); // 300ms; total 3s
1410 if (server->shutdown()) shutdown = true;
1411 }
1412 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1413
1414 ASSERT_TRUE(joinEnds->wait(2s))
1415 << "After server->shutdown() returns true, join() did not stop after 2s";
1416}
1417
Yifan Hong194acf22021-06-29 18:44:56 -07001418TEST(BinderRpc, Java) {
1419#if !defined(__ANDROID__)
1420 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1421 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1422 "to binderHostDeviceTest. Hence, just disable this test on host.";
1423#endif // !__ANDROID__
1424 sp<IServiceManager> sm = defaultServiceManager();
1425 ASSERT_NE(nullptr, sm);
1426 // Any Java service with non-empty getInterfaceDescriptor() would do.
1427 // Let's pick batteryproperties.
1428 auto binder = sm->checkService(String16("batteryproperties"));
1429 ASSERT_NE(nullptr, binder);
1430 auto descriptor = binder->getInterfaceDescriptor();
1431 ASSERT_GE(descriptor.size(), 0);
1432 ASSERT_EQ(OK, binder->pingBinder());
1433
1434 auto rpcServer = RpcServer::make();
1435 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1436 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001437 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001438 auto socket = rpcServer->releaseServer();
1439
1440 auto keepAlive = sp<BBinder>::make();
1441 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1442
1443 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001444 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001445 auto rpcBinder = rpcSession->getRootObject();
1446 ASSERT_NE(nullptr, rpcBinder);
1447
1448 ASSERT_EQ(OK, rpcBinder->pingBinder());
1449
1450 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1451 << "getInterfaceDescriptor should not crash system_server";
1452 ASSERT_EQ(OK, rpcBinder->pingBinder());
1453}
1454
Yifan Hong702115c2021-06-24 15:39:18 -07001455INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1456 BinderRpcSimple::PrintTestParam);
1457
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001458class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001459public:
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001460 using Param = std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001461 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001462
1463 // A server that handles client socket connections.
1464 class Server {
1465 public:
1466 explicit Server() {}
1467 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001468 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001469 [[nodiscard]] AssertionResult setUp(
1470 const Param& param,
1471 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
1472 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001473 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
1474 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1475 switch (socketType) {
1476 case SocketType::PRECONNECTED: {
1477 return AssertionFailure() << "Not supported by this test";
1478 } break;
1479 case SocketType::UNIX: {
1480 auto addr = allocateSocketAddress();
1481 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1482 if (status != OK) {
1483 return AssertionFailure()
1484 << "setupUnixDomainServer: " << statusToString(status);
1485 }
1486 mConnectToServer = [addr] {
1487 return connectTo(UnixSocketAddress(addr.c_str()));
1488 };
1489 } break;
1490 case SocketType::VSOCK: {
1491 auto port = allocateVsockPort();
1492 auto status = rpcServer->setupVsockServer(port);
1493 if (status != OK) {
1494 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1495 }
1496 mConnectToServer = [port] {
1497 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1498 };
1499 } break;
1500 case SocketType::INET: {
1501 unsigned int port;
1502 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1503 if (status != OK) {
1504 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1505 }
1506 mConnectToServer = [port] {
1507 const char* addr = kLocalInetAddress;
1508 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1509 if (aiStart == nullptr) return base::unique_fd{};
1510 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1511 auto fd = connectTo(
1512 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1513 if (fd.ok()) return fd;
1514 }
1515 ALOGE("None of the socket address resolved for %s:%u can be connected",
1516 addr, port);
1517 return base::unique_fd{};
1518 };
1519 }
1520 }
1521 mFd = rpcServer->releaseServer();
1522 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001523 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001524 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1525 mSetup = true;
1526 return AssertionSuccess();
1527 }
1528 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1529 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1530 return mCertVerifier;
1531 }
1532 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1533 void start() {
1534 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1535 mThread = std::make_unique<std::thread>(&Server::run, this);
1536 }
1537 void run() {
1538 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1539
1540 std::vector<std::thread> threads;
1541 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1542 base::unique_fd acceptedFd(
1543 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1544 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1545 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1546 }
1547
1548 for (auto& thread : threads) thread.join();
1549 }
1550 void handleOne(android::base::unique_fd acceptedFd) {
1551 ASSERT_TRUE(acceptedFd.ok());
1552 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1553 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001554 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001555 }
Yifan Honge07d2732021-09-13 21:59:14 -07001556 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001557 shutdown();
1558 join();
1559 }
1560 void shutdown() { mFdTrigger->trigger(); }
1561
1562 void setPostConnect(
1563 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1564 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001565 }
1566
1567 private:
1568 std::unique_ptr<std::thread> mThread;
1569 ConnectToServer mConnectToServer;
1570 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1571 base::unique_fd mFd;
1572 std::unique_ptr<RpcTransportCtx> mCtx;
1573 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1574 std::make_shared<RpcCertificateVerifierSimple>();
1575 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001576 // The function invoked after connection and handshake. By default, it is
1577 // |defaultPostConnect| that sends |kMessage| to the client.
1578 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1579 Server::defaultPostConnect;
1580
1581 void join() {
1582 if (mThread != nullptr) {
1583 mThread->join();
1584 mThread = nullptr;
1585 }
1586 }
1587
1588 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1589 FdTrigger* fdTrigger) {
1590 std::string message(kMessage);
1591 auto status = serverTransport->interruptableWriteFully(fdTrigger, message.data(),
Steven Moreland43921d52021-09-27 17:15:56 -07001592 message.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001593 if (status != OK) return AssertionFailure() << statusToString(status);
1594 return AssertionSuccess();
1595 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001596 };
1597
1598 class Client {
1599 public:
1600 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1601 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001602 [[nodiscard]] AssertionResult setUp(const Param& param) {
1603 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001604 mFdTrigger = FdTrigger::make();
1605 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1606 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1607 return AssertionSuccess();
1608 }
1609 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1610 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1611 return mCertVerifier;
1612 }
Yifan Hong67519322021-09-13 18:51:16 -07001613 // connect() and do handshake
1614 bool setUpTransport() {
1615 mFd = mConnectToServer();
1616 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1617 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1618 return mClientTransport != nullptr;
1619 }
1620 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1621 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1622 std::string readMessage(expectedMessage.size(), '\0');
1623 status_t readStatus =
1624 mClientTransport->interruptableReadFully(mFdTrigger.get(), readMessage.data(),
Steven Moreland43921d52021-09-27 17:15:56 -07001625 readMessage.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001626 if (readStatus != OK) {
1627 return AssertionFailure() << statusToString(readStatus);
1628 }
1629 if (readMessage != expectedMessage) {
1630 return AssertionFailure()
1631 << "Expected " << expectedMessage << ", actual " << readMessage;
1632 }
1633 return AssertionSuccess();
1634 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001635 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001636 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001637 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1638 return;
1639 }
1640 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001641 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001642 }
1643
1644 private:
1645 ConnectToServer mConnectToServer;
1646 base::unique_fd mFd;
1647 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1648 std::unique_ptr<RpcTransportCtx> mCtx;
1649 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1650 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001651 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001652 };
1653
1654 // Make A trust B.
1655 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001656 static status_t trust(RpcSecurity rpcSecurity,
1657 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1658 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001659 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001660 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1661 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1662 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001663 }
1664
1665 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001666};
1667
1668class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1669public:
1670 using Server = RpcTransportTestUtils::Server;
1671 using Client = RpcTransportTestUtils::Client;
1672 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1673 auto [socketType, rpcSecurity, certificateFormat] = info.param;
1674 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1675 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
1676 return ret;
1677 }
1678 static std::vector<ParamType> getRpcTranportTestParams() {
1679 std::vector<ParamType> ret;
1680 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1681 for (auto rpcSecurity : RpcSecurityValues()) {
1682 switch (rpcSecurity) {
1683 case RpcSecurity::RAW: {
1684 ret.emplace_back(socketType, rpcSecurity, std::nullopt);
1685 } break;
1686 case RpcSecurity::TLS: {
1687 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM);
1688 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER);
1689 } break;
1690 }
1691 }
1692 }
1693 return ret;
1694 }
1695 template <typename A, typename B>
1696 status_t trust(const A& a, const B& b) {
1697 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1698 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1699 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001700};
1701
1702TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001703 auto server = std::make_unique<Server>();
1704 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001705
1706 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001707 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001708
1709 ASSERT_EQ(OK, trust(&client, server));
1710 ASSERT_EQ(OK, trust(server, &client));
1711
1712 server->start();
1713 client.run();
1714}
1715
1716TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001717 auto server = std::make_unique<Server>();
1718 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001719
1720 std::vector<Client> clients;
1721 for (int i = 0; i < 2; i++) {
1722 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001723 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001724 ASSERT_EQ(OK, trust(&client, server));
1725 ASSERT_EQ(OK, trust(server, &client));
1726 }
1727
1728 server->start();
1729 for (auto& client : clients) client.run();
1730}
1731
1732TEST_P(RpcTransportTest, UntrustedServer) {
1733 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1734
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001735 auto untrustedServer = std::make_unique<Server>();
1736 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001737
1738 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001739 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001740
1741 ASSERT_EQ(OK, trust(untrustedServer, &client));
1742
1743 untrustedServer->start();
1744
1745 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1746 // the client can't verify the server's identity.
1747 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1748 client.run(handshakeOk);
1749}
1750TEST_P(RpcTransportTest, MaliciousServer) {
1751 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001752 auto validServer = std::make_unique<Server>();
1753 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001754
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001755 auto maliciousServer = std::make_unique<Server>();
1756 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001757
1758 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001759 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001760
1761 ASSERT_EQ(OK, trust(&client, validServer));
1762 ASSERT_EQ(OK, trust(validServer, &client));
1763 ASSERT_EQ(OK, trust(maliciousServer, &client));
1764
1765 maliciousServer->start();
1766
1767 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1768 // the client can't verify the server's identity.
1769 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1770 client.run(handshakeOk);
1771}
1772
1773TEST_P(RpcTransportTest, UntrustedClient) {
1774 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001775 auto server = std::make_unique<Server>();
1776 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001777
1778 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001779 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001780
1781 ASSERT_EQ(OK, trust(&client, server));
1782
1783 server->start();
1784
1785 // For TLS, Client should be able to verify server's identity, so client should see
1786 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1787 // identity and should drop the connection, so client shouldn't be able to read anything.
1788 bool readOk = rpcSecurity != RpcSecurity::TLS;
1789 client.run(true, readOk);
1790}
1791
1792TEST_P(RpcTransportTest, MaliciousClient) {
1793 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001794 auto server = std::make_unique<Server>();
1795 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001796
1797 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001798 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001799 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001800 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001801
1802 ASSERT_EQ(OK, trust(&validClient, server));
1803 ASSERT_EQ(OK, trust(&maliciousClient, server));
1804
1805 server->start();
1806
1807 // See UntrustedClient.
1808 bool readOk = rpcSecurity != RpcSecurity::TLS;
1809 maliciousClient.run(true, readOk);
1810}
1811
Yifan Hong67519322021-09-13 18:51:16 -07001812TEST_P(RpcTransportTest, Trigger) {
1813 std::string msg2 = ", world!";
1814 std::mutex writeMutex;
1815 std::condition_variable writeCv;
1816 bool shouldContinueWriting = false;
1817 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001818 std::string message(RpcTransportTestUtils::kMessage);
Steven Moreland43921d52021-09-27 17:15:56 -07001819 auto status = serverTransport->interruptableWriteFully(fdTrigger, message.data(),
1820 message.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001821 if (status != OK) return AssertionFailure() << statusToString(status);
1822
1823 {
1824 std::unique_lock<std::mutex> lock(writeMutex);
1825 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1826 return AssertionFailure() << "write barrier not cleared in time!";
1827 }
1828 }
1829
Steven Moreland43921d52021-09-27 17:15:56 -07001830 status = serverTransport->interruptableWriteFully(fdTrigger, msg2.data(), msg2.size(), {});
Steven Morelandc591b472021-09-16 13:56:11 -07001831 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001832 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001833 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001834 << statusToString(status);
1835 return AssertionSuccess();
1836 };
1837
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001838 auto server = std::make_unique<Server>();
1839 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001840
1841 // Set up client
1842 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001843 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001844
1845 // Exchange keys
1846 ASSERT_EQ(OK, trust(&client, server));
1847 ASSERT_EQ(OK, trust(server, &client));
1848
1849 server->setPostConnect(serverPostConnect);
1850
Yifan Hong67519322021-09-13 18:51:16 -07001851 server->start();
1852 // connect() to server and do handshake
1853 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001854 // read the first message. This ensures that server has finished handshake and start handling
1855 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001856 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001857 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1858 // write is on an FdTrigger that has been shut down.
1859 server->shutdown();
1860 // Continues server thread to write the second message.
1861 {
Yifan Hong22211f82021-09-14 12:32:25 -07001862 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001863 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001864 }
Yifan Hong22211f82021-09-14 12:32:25 -07001865 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001866 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001867 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001868 // On the client side, second read fails with DEAD_OBJECT
1869 ASSERT_FALSE(client.readMessage(msg2));
1870}
1871
Yifan Hong1deca4b2021-09-10 16:16:44 -07001872INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001873 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001874 RpcTransportTest::PrintParamInfo);
1875
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001876class RpcTransportTlsKeyTest
1877 : public testing::TestWithParam<std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat>> {
1878public:
1879 template <typename A, typename B>
1880 status_t trust(const A& a, const B& b) {
1881 auto [socketType, certificateFormat, keyFormat] = GetParam();
1882 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1883 }
1884 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1885 auto [socketType, certificateFormat, keyFormat] = info.param;
1886 auto ret = PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1887 "_key_" + PrintToString(keyFormat);
1888 return ret;
1889 };
1890};
1891
1892TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
1893 auto [socketType, certificateFormat, keyFormat] = GetParam();
1894
1895 std::vector<uint8_t> pkeyData, certData;
1896 {
1897 auto pkey = makeKeyPairForSelfSignedCert();
1898 ASSERT_NE(nullptr, pkey);
1899 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1900 ASSERT_NE(nullptr, cert);
1901 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1902 certData = serializeCertificate(cert.get(), certificateFormat);
1903 }
1904
1905 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1906 auto desCert = deserializeCertificate(certData, certificateFormat);
1907 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
1908 auto utilsParam =
1909 std::make_tuple(socketType, RpcSecurity::TLS, std::make_optional(certificateFormat));
1910
1911 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1912 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1913
1914 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1915 ASSERT_TRUE(client.setUp(utilsParam));
1916
1917 ASSERT_EQ(OK, trust(&client, server));
1918 ASSERT_EQ(OK, trust(server, &client));
1919
1920 server->start();
1921 client.run();
1922}
1923
1924INSTANTIATE_TEST_CASE_P(
1925 BinderRpc, RpcTransportTlsKeyTest,
1926 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1927 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
1928 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER)),
1929 RpcTransportTlsKeyTest::PrintParamInfo);
1930
Steven Morelandc1635952021-04-01 16:20:47 +00001931} // namespace android
1932
1933int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001934 ::testing::InitGoogleTest(&argc, argv);
1935 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1936 return RUN_ALL_TESTS();
1937}