blob: bc23b151ca5e17b3bf6856e0a07c3d0bdc153b98 [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 Moreland51c44a92021-10-14 16:50:35 -0700177 int port = 0;
Steven Moreland5553ac42020-11-11 02:14:45 +0000178
179 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000180 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000181 return Status::ok();
182 }
183 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000184 *strstr = str + str;
185 return Status::ok();
186 }
Steven Moreland51c44a92021-10-14 16:50:35 -0700187 Status getClientPort(int* out) override {
188 *out = port;
189 return Status::ok();
190 }
Steven Moreland736664b2021-05-01 04:27:25 +0000191 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000192 sp<RpcServer> spServer = server.promote();
193 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000194 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
195 }
Steven Moreland736664b2021-05-01 04:27:25 +0000196 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000197 for (auto session : spServer->listSessions()) {
198 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000199 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000200 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000201 return Status::ok();
202 }
203 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
204 if (binder == nullptr) {
205 std::cout << "Received null binder!" << std::endl;
206 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
207 }
208 *out = binder->pingBinder();
209 return Status::ok();
210 }
211 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
212 *out = binder;
213 return Status::ok();
214 }
215 static sp<IBinder> mHeldBinder;
216 Status holdBinder(const sp<IBinder>& binder) override {
217 mHeldBinder = binder;
218 return Status::ok();
219 }
220 Status getHeldBinder(sp<IBinder>* held) override {
221 *held = mHeldBinder;
222 return Status::ok();
223 }
224 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
225 if (count <= 0) return Status::ok();
226 return binder->nestMe(this, count - 1);
227 }
228 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
229 static sp<IBinder> binder = new BBinder;
230 *out = binder;
231 return Status::ok();
232 }
233 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
234 *out = new MyBinderRpcSession(name);
235 return Status::ok();
236 }
237 Status getNumOpenSessions(int32_t* out) override {
238 *out = MyBinderRpcSession::gNum;
239 return Status::ok();
240 }
241
242 std::mutex blockMutex;
243 Status lock() override {
244 blockMutex.lock();
245 return Status::ok();
246 }
247 Status unlockInMsAsync(int32_t ms) override {
248 usleep(ms * 1000);
249 blockMutex.unlock();
250 return Status::ok();
251 }
252 Status lockUnlock() override {
253 std::lock_guard<std::mutex> _l(blockMutex);
254 return Status::ok();
255 }
256
257 Status sleepMs(int32_t ms) override {
258 usleep(ms * 1000);
259 return Status::ok();
260 }
261
262 Status sleepMsAsync(int32_t ms) override {
263 // In-process binder calls are asynchronous, but the call to this method
264 // is synchronous wrt its client. This in/out-process threading model
265 // diffentiation is a classic binder leaky abstraction (for better or
266 // worse) and is preserved here the way binder sockets plugs itself
267 // into BpBinder, as nothing is changed at the higher levels
268 // (IInterface) which result in this behavior.
269 return sleepMs(ms);
270 }
271
Steven Moreland659416d2021-05-11 00:47:50 +0000272 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
273 const std::string& value) override {
274 if (callback == nullptr) {
275 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
276 }
277
278 if (delayed) {
279 std::thread([=]() {
280 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000281 Status status = doCallback(callback, oneway, false, value);
282 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000283 }).detach();
284 return Status::ok();
285 }
286
287 if (oneway) {
288 return callback->sendOnewayCallback(value);
289 }
290
291 return callback->sendCallback(value);
292 }
293
Steven Morelandc7d40132021-06-10 03:42:11 +0000294 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
295 const std::string& value) override {
296 return doCallback(callback, oneway, delayed, value);
297 }
298
Steven Moreland5553ac42020-11-11 02:14:45 +0000299 Status die(bool cleanup) override {
300 if (cleanup) {
301 exit(1);
302 } else {
303 _exit(1);
304 }
305 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000306
307 Status scheduleShutdown() override {
308 sp<RpcServer> strongServer = server.promote();
309 if (strongServer == nullptr) {
310 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
311 }
312 std::thread([=] {
313 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
314 }).detach();
315 return Status::ok();
316 }
317
Steven Morelandd7302072021-05-15 01:32:04 +0000318 Status useKernelBinderCallingId() override {
319 // this is WRONG! It does not make sense when using RPC binder, and
320 // because it is SO wrong, and so much code calls this, it should abort!
321
322 (void)IPCThreadState::self()->getCallingPid();
323 return Status::ok();
324 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000325};
326sp<IBinder> MyBinderRpcTest::mHeldBinder;
327
328class Process {
329public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700330 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700331 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
332 android::base::borrowed_fd /* readEnd */)>& f) {
333 android::base::unique_fd childWriteEnd;
334 android::base::unique_fd childReadEnd;
335 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
336 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000337 if (0 == (mPid = fork())) {
338 // racey: assume parent doesn't crash before this is set
339 prctl(PR_SET_PDEATHSIG, SIGHUP);
340
Yifan Hong1deca4b2021-09-10 16:16:44 -0700341 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000342
343 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000344 }
345 }
346 ~Process() {
347 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000348 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000349 }
350 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700351 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700352 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000353
354private:
355 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700356 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700357 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000358};
359
360static std::string allocateSocketAddress() {
361 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000362 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700363 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
364 unlink(ret.c_str());
365 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000366};
367
Steven Morelandda573042021-06-12 01:13:45 +0000368static unsigned int allocateVsockPort() {
369 static unsigned int vsockPort = 3456;
370 return vsockPort++;
371}
372
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000373struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000374 // reference to process hosting a socket server
375 Process host;
376
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000377 struct SessionInfo {
378 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000379 sp<IBinder> root;
380 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000381
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000382 // client session objects associated with other process
383 // each one represents a separate session
384 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000385
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000386 ProcessSession(ProcessSession&&) = default;
387 ~ProcessSession() {
388 for (auto& session : sessions) {
389 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000390 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000391
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000392 for (auto& info : sessions) {
393 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000394
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395 EXPECT_NE(nullptr, session);
396 EXPECT_NE(nullptr, session->state());
397 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000398
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000399 wp<RpcSession> weakSession = session;
400 session = nullptr;
401 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000402 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000403 }
404};
405
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000406// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000407// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000408struct BinderRpcTestProcessSession {
409 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000410
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000411 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000412 sp<IBinder> rootBinder;
413
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000414 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000415 sp<IBinderRpcTest> rootIface;
416
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000417 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000418 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000419
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000420 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
421 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000422 EXPECT_NE(nullptr, rootIface);
423 if (rootIface == nullptr) return;
424
Steven Morelandaf4ca712021-05-24 23:22:08 +0000425 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000426 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000427 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000428 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000429 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000430 for (auto remoteCount : remoteCounts) {
431 EXPECT_EQ(remoteCount, 1);
432 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000433
Steven Moreland798e0d12021-07-14 23:19:25 +0000434 // even though it is on another thread, shutdown races with
435 // the transaction reply being written
436 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
437 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
438 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000439 }
440
441 rootIface = nullptr;
442 rootBinder = nullptr;
443 }
444};
445
Steven Morelandc1635952021-04-01 16:20:47 +0000446enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700447 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000448 UNIX,
449 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700450 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000451};
Yifan Hong702115c2021-06-24 15:39:18 -0700452static inline std::string PrintToString(SocketType socketType) {
453 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700454 case SocketType::PRECONNECTED:
455 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000456 case SocketType::UNIX:
457 return "unix_domain_socket";
458 case SocketType::VSOCK:
459 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700460 case SocketType::INET:
461 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000462 default:
463 LOG_ALWAYS_FATAL("Unknown socket type");
464 return "";
465 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000466}
Steven Morelandda573042021-06-12 01:13:45 +0000467
Yifan Hong1deca4b2021-09-10 16:16:44 -0700468static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700469 base::unique_fd serverFd(
470 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
471 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700472 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
473 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700474
475 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
476 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700477 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
478 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700479 }
480 return serverFd;
481}
482
Yifan Hong702115c2021-06-24 15:39:18 -0700483class BinderRpc : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000484public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000485 struct Options {
486 size_t numThreads = 1;
487 size_t numSessions = 1;
488 size_t numIncomingConnections = 0;
Yifan Hong1f44f982021-10-08 17:16:47 -0700489 size_t numOutgoingConnections = SIZE_MAX;
Steven Moreland4313d7e2021-07-15 23:41:22 +0000490 };
491
Yifan Hong702115c2021-06-24 15:39:18 -0700492 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
493 auto [type, security] = info.param;
494 return PrintToString(type) + "_" + newFactory(security)->toCString();
495 }
496
Yifan Hong1deca4b2021-09-10 16:16:44 -0700497 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
498 uint64_t length = str.length();
499 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
500 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
501 }
502
503 static inline std::string readString(android::base::borrowed_fd fd) {
504 uint64_t length;
505 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
506 std::string ret(length, '\0');
507 CHECK(android::base::ReadFully(fd, ret.data(), length));
508 return ret;
509 }
510
511 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
512 Parcel parcel;
513 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
514 writeString(fd,
515 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
516 }
517
518 template <typename T>
519 static inline T readFromFd(android::base::borrowed_fd fd) {
520 std::string data = readString(fd);
521 Parcel parcel;
522 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
523 T object;
524 CHECK_EQ(OK, object.readFromParcel(&parcel));
525 return object;
526 }
527
Steven Morelandc1635952021-04-01 16:20:47 +0000528 // This creates a new process serving an interface on a certain number of
529 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000530 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000531 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
532 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000533
Yifan Hong702115c2021-06-24 15:39:18 -0700534 SocketType socketType = std::get<0>(GetParam());
535 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000536
Steven Morelandda573042021-06-12 01:13:45 +0000537 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000538 std::string addr = allocateSocketAddress();
Steven Morelandc1635952021-04-01 16:20:47 +0000539
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000540 auto ret = ProcessSession{
Yifan Hong1deca4b2021-09-10 16:16:44 -0700541 .host = Process([&](android::base::borrowed_fd writeEnd,
542 android::base::borrowed_fd readEnd) {
543 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
544 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
Steven Morelandc1635952021-04-01 16:20:47 +0000545
546 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000547 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000548
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000549 unsigned int outPort = 0;
550
Steven Morelandc1635952021-04-01 16:20:47 +0000551 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700552 case SocketType::PRECONNECTED:
553 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000554 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700555 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000556 break;
557 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700558 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000559 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700560 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700561 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700562 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700563 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700564 }
Steven Morelandc1635952021-04-01 16:20:47 +0000565 default:
566 LOG_ALWAYS_FATAL("Unknown socket type");
567 }
568
Yifan Hong1deca4b2021-09-10 16:16:44 -0700569 BinderRpcTestServerInfo serverInfo;
570 serverInfo.port = static_cast<int64_t>(outPort);
Yifan Hong9734cfc2021-09-13 16:14:09 -0700571 serverInfo.cert.data = server->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700572 writeToFd(writeEnd, serverInfo);
573 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
574
575 if (rpcSecurity == RpcSecurity::TLS) {
576 for (const auto& clientCert : clientInfo.certs) {
577 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700578 certVerifier
579 ->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
580 clientCert.data));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700581 }
582 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000583
Steven Moreland611d15f2021-05-01 01:28:27 +0000584 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000585
Steven Morelandf137de92021-04-24 01:54:26 +0000586 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000587
588 // Another thread calls shutdown. Wait for it to complete.
589 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000590 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000591 };
592
Yifan Hong1deca4b2021-09-10 16:16:44 -0700593 std::vector<sp<RpcSession>> sessions;
594 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
595 for (size_t i = 0; i < options.numSessions; i++) {
596 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
597 }
598
599 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
600 BinderRpcTestClientInfo clientInfo;
601 for (const auto& session : sessions) {
602 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700603 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700604 }
605 writeToFd(ret.host.writeEnd(), clientInfo);
606
607 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700608 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700609 CHECK_NE(0, serverInfo.port);
610 }
611
612 if (rpcSecurity == RpcSecurity::TLS) {
613 const auto& serverCert = serverInfo.cert.data;
614 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700615 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
616 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700617 }
618
Steven Moreland2372f9d2021-08-05 15:42:01 -0700619 status_t status;
620
Yifan Hong1deca4b2021-09-10 16:16:44 -0700621 for (const auto& session : sessions) {
Yifan Hong10423062021-10-08 16:26:32 -0700622 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700623 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000624
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000625 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700626 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700627 status = session->setupPreconnectedClient({}, [=]() {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700628 return connectTo(UnixSocketAddress(addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700629 });
Steven Moreland4198a122021-08-03 17:37:58 -0700630 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000631 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700632 status = session->setupUnixDomainClient(addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000633 break;
634 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700635 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000636 break;
637 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700638 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000639 break;
640 default:
641 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000642 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700643 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000644 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000645 }
Steven Morelandc1635952021-04-01 16:20:47 +0000646 return ret;
647 }
648
Steven Moreland4313d7e2021-07-15 23:41:22 +0000649 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000650 BinderRpcTestProcessSession ret{
Steven Moreland51c44a92021-10-14 16:50:35 -0700651 .proc = createRpcTestSocketServerProcess(
652 options,
653 [&](const sp<RpcServer>& server) {
654 server->setPerSessionRootObject([&](const sockaddr* addr,
655 socklen_t len) {
656 sp<MyBinderRpcTest> service = sp<MyBinderRpcTest>::make();
657 switch (addr->sa_family) {
658 case AF_UNIX:
659 // nothing to save
660 break;
661 case AF_VSOCK:
662 CHECK_EQ(len, sizeof(sockaddr_vm));
663 service->port = reinterpret_cast<const sockaddr_vm*>(addr)
664 ->svm_port;
665 break;
666 case AF_INET:
667 CHECK_EQ(len, sizeof(sockaddr_in));
668 service->port = reinterpret_cast<const sockaddr_in*>(addr)
669 ->sin_port;
670 break;
671 case AF_INET6:
672 CHECK_EQ(len, sizeof(sockaddr_in));
673 service->port = reinterpret_cast<const sockaddr_in6*>(addr)
674 ->sin6_port;
675 break;
676 default:
677 LOG_ALWAYS_FATAL("Unrecognized address family %d",
678 addr->sa_family);
679 }
680 service->server = server;
681 return service;
682 });
683 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000684 };
685
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000686 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000687 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
688
689 return ret;
690 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700691
692 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
693 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000694};
695
Steven Morelandc1635952021-04-01 16:20:47 +0000696TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000697 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000698 ASSERT_NE(proc.rootBinder, nullptr);
699 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
700}
701
Steven Moreland4cf688f2021-03-31 01:48:58 +0000702TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000703 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000704 ASSERT_NE(proc.rootBinder, nullptr);
705 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
706}
707
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000708TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000709 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000710 for (auto session : proc.proc.sessions) {
711 ASSERT_NE(nullptr, session.root);
712 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000713 }
714}
715
Steven Moreland51c44a92021-10-14 16:50:35 -0700716TEST_P(BinderRpc, SeparateRootObject) {
717 SocketType type = std::get<0>(GetParam());
718 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
719 // we can't get port numbers for unix sockets
720 return;
721 }
722
723 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
724
725 int port1 = 0;
726 EXPECT_OK(proc.rootIface->getClientPort(&port1));
727
728 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
729 int port2;
730 EXPECT_OK(rootIface2->getClientPort(&port2));
731
732 // we should have a different IBinderRpcTest object created for each
733 // session, because we use setPerSessionRootObject
734 EXPECT_NE(port1, port2);
735}
736
Steven Morelandc1635952021-04-01 16:20:47 +0000737TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000738 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000739 Parcel data;
740 Parcel reply;
741 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
742}
743
Steven Moreland67753c32021-04-02 18:45:19 +0000744TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700745 auto proc1 = createRpcTestSocketServerProcess({});
746 auto proc2 = createRpcTestSocketServerProcess({});
747
748 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000749
750 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700751 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000752 p1.writeInt32(3);
753
Steven Moreland2034eff2021-10-13 11:24:35 -0700754 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, p1.dataSize()));
755 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
756
Steven Moreland67753c32021-04-02 18:45:19 +0000757 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700758 p2.markForBinder(proc2.rootBinder);
759 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000760
761 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
762 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
763}
764
Steven Morelandc1635952021-04-01 16:20:47 +0000765TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000766 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000767 Parcel data;
768 data.markForBinder(proc.rootBinder);
769 Parcel reply;
770 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
771}
772
Steven Morelandc1635952021-04-01 16:20:47 +0000773TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000774 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000775 EXPECT_OK(proc.rootIface->sendString("asdf"));
776}
777
Steven Morelandc1635952021-04-01 16:20:47 +0000778TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000779 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000780 std::string doubled;
781 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
782 EXPECT_EQ("cool cool ", doubled);
783}
784
Steven Morelandc1635952021-04-01 16:20:47 +0000785TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000786 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000787 std::string single = std::string(1024, 'a');
788 std::string doubled;
789 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
790 EXPECT_EQ(single + single, doubled);
791}
792
Steven Morelandc1635952021-04-01 16:20:47 +0000793TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000794 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000795
796 int32_t pingResult;
797 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
798 EXPECT_EQ(OK, pingResult);
799
800 EXPECT_EQ(0, MyBinderRpcSession::gNum);
801}
802
Steven Morelandc1635952021-04-01 16:20:47 +0000803TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000804 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000805
806 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
807 sp<IBinder> outBinder;
808 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
809 EXPECT_EQ(inBinder, outBinder);
810
811 wp<IBinder> weak = inBinder;
812 inBinder = nullptr;
813 outBinder = nullptr;
814
815 // Force reading a reply, to process any pending dec refs from the other
816 // process (the other process will process dec refs there before processing
817 // the ping here).
818 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
819
820 EXPECT_EQ(nullptr, weak.promote());
821
822 EXPECT_EQ(0, MyBinderRpcSession::gNum);
823}
824
Steven Morelandc1635952021-04-01 16:20:47 +0000825TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000826 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000827
828 sp<IBinderRpcSession> session;
829 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
830
831 sp<IBinder> inBinder = IInterface::asBinder(session);
832 sp<IBinder> outBinder;
833 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
834 EXPECT_EQ(inBinder, outBinder);
835
836 wp<IBinder> weak = inBinder;
837 session = nullptr;
838 inBinder = nullptr;
839 outBinder = nullptr;
840
841 // Force reading a reply, to process any pending dec refs from the other
842 // process (the other process will process dec refs there before processing
843 // the ping here).
844 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
845
846 EXPECT_EQ(nullptr, weak.promote());
847}
848
Steven Morelandc1635952021-04-01 16:20:47 +0000849TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000850 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000851
852 sp<IBinder> outBinder;
853 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
854 EXPECT_EQ(nullptr, outBinder);
855}
856
Steven Morelandc1635952021-04-01 16:20:47 +0000857TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000858 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000859
860 IBinder* ptr = nullptr;
861 {
862 sp<IBinder> binder = new BBinder();
863 ptr = binder.get();
864 EXPECT_OK(proc.rootIface->holdBinder(binder));
865 }
866
867 sp<IBinder> held;
868 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
869
870 EXPECT_EQ(held.get(), ptr);
871
872 // stop holding binder, because we test to make sure references are cleaned
873 // up
874 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
875 // and flush ref counts
876 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
877}
878
879// START TESTS FOR LIMITATIONS OF SOCKET BINDER
880// These are behavioral differences form regular binder, where certain usecases
881// aren't supported.
882
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000883TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000884 auto proc1 = createRpcTestSocketServerProcess({});
885 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000886
887 sp<IBinder> outBinder;
888 EXPECT_EQ(INVALID_OPERATION,
889 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
890}
891
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000892TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000893 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000894
895 sp<IBinder> outBinder;
896 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000897 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000898 .transactionError());
899}
900
Steven Morelandc1635952021-04-01 16:20:47 +0000901TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000902 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000903
904 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
905 sp<IBinder> outBinder;
906 EXPECT_EQ(INVALID_OPERATION,
907 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
908}
909
Steven Morelandc1635952021-04-01 16:20:47 +0000910TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000911 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000912
913 // for historical reasons, IServiceManager interface only returns the
914 // exception code
915 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
916 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
917}
918
919// END TESTS FOR LIMITATIONS OF SOCKET BINDER
920
Steven Morelandc1635952021-04-01 16:20:47 +0000921TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000922 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000923
924 sp<IBinder> outBinder;
925 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
926 EXPECT_EQ(proc.rootBinder, outBinder);
927}
928
Steven Morelandc1635952021-04-01 16:20:47 +0000929TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000930 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000931
932 auto nastyNester = sp<MyBinderRpcTest>::make();
933 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
934
935 wp<IBinder> weak = nastyNester;
936 nastyNester = nullptr;
937 EXPECT_EQ(nullptr, weak.promote());
938}
939
Steven Morelandc1635952021-04-01 16:20:47 +0000940TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000941 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000942
943 sp<IBinder> a;
944 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
945
946 sp<IBinder> b;
947 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
948
949 EXPECT_EQ(a, b);
950}
951
Steven Morelandc1635952021-04-01 16:20:47 +0000952TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000953 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000954
955 sp<IBinder> a;
956 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
957 wp<IBinder> weak = a;
958 a = nullptr;
959
960 sp<IBinder> b;
961 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
962
963 // this is the wrong behavior, since BpBinder
964 // doesn't implement onIncStrongAttempted
965 // but make sure there is no crash
966 EXPECT_EQ(nullptr, weak.promote());
967
968 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
969
970 // In order to fix this:
971 // - need to have incStrongAttempted reflected across IPC boundary (wait for
972 // response to promote - round trip...)
973 // - sendOnLastWeakRef, to delete entries out of RpcState table
974 EXPECT_EQ(b, weak.promote());
975}
976
977#define expectSessions(expected, iface) \
978 do { \
979 int session; \
980 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
981 EXPECT_EQ(expected, session); \
982 } while (false)
983
Steven Morelandc1635952021-04-01 16:20:47 +0000984TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000985 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000986
987 sp<IBinderRpcSession> session;
988 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
989 std::string out;
990 EXPECT_OK(session->getName(&out));
991 EXPECT_EQ("aoeu", out);
992
993 expectSessions(1, proc.rootIface);
994 session = nullptr;
995 expectSessions(0, proc.rootIface);
996}
997
Steven Morelandc1635952021-04-01 16:20:47 +0000998TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000999 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001000
1001 std::vector<sp<IBinderRpcSession>> sessions;
1002
1003 for (size_t i = 0; i < 15; i++) {
1004 expectSessions(i, proc.rootIface);
1005 sp<IBinderRpcSession> session;
1006 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
1007 sessions.push_back(session);
1008 }
1009 expectSessions(sessions.size(), proc.rootIface);
1010 for (size_t i = 0; i < sessions.size(); i++) {
1011 std::string out;
1012 EXPECT_OK(sessions.at(i)->getName(&out));
1013 EXPECT_EQ(std::to_string(i), out);
1014 }
1015 expectSessions(sessions.size(), proc.rootIface);
1016
1017 while (!sessions.empty()) {
1018 sessions.pop_back();
1019 expectSessions(sessions.size(), proc.rootIface);
1020 }
1021 expectSessions(0, proc.rootIface);
1022}
1023
1024size_t epochMillis() {
1025 using std::chrono::duration_cast;
1026 using std::chrono::milliseconds;
1027 using std::chrono::seconds;
1028 using std::chrono::system_clock;
1029 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1030}
1031
Steven Morelandc1635952021-04-01 16:20:47 +00001032TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001033 constexpr size_t kNumThreads = 10;
1034
Steven Moreland4313d7e2021-07-15 23:41:22 +00001035 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001036
1037 EXPECT_OK(proc.rootIface->lock());
1038
1039 // block all but one thread taking locks
1040 std::vector<std::thread> ts;
1041 for (size_t i = 0; i < kNumThreads - 1; i++) {
1042 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
1043 }
1044
1045 usleep(100000); // give chance for calls on other threads
1046
1047 // other calls still work
1048 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1049
1050 constexpr size_t blockTimeMs = 500;
1051 size_t epochMsBefore = epochMillis();
1052 // after this, we should never see a response within this time
1053 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
1054
1055 // this call should be blocked for blockTimeMs
1056 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1057
1058 size_t epochMsAfter = epochMillis();
1059 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
1060
1061 for (auto& t : ts) t.join();
1062}
1063
Yifan Hong1f44f982021-10-08 17:16:47 -07001064void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
1065 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001066 size_t epochMsBefore = epochMillis();
1067
1068 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -07001069 for (size_t i = 0; i < numCalls; i++) {
1070 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +00001071 }
1072
1073 for (auto& t : ts) t.join();
1074
1075 size_t epochMsAfter = epochMillis();
1076
Yifan Hong1f44f982021-10-08 17:16:47 -07001077 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +00001078
1079 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -07001080 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
1081}
1082
1083TEST_P(BinderRpc, ThreadPoolOverSaturated) {
1084 constexpr size_t kNumThreads = 10;
1085 constexpr size_t kNumCalls = kNumThreads + 3;
1086 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1087 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
1088}
1089
1090TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
1091 constexpr size_t kNumThreads = 20;
1092 constexpr size_t kNumOutgoingConnections = 10;
1093 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
1094 auto proc = createRpcTestSocketServerProcess(
1095 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
1096 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +00001097}
1098
Steven Morelandc1635952021-04-01 16:20:47 +00001099TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001100 constexpr size_t kNumClientThreads = 10;
1101 constexpr size_t kNumServerThreads = 10;
1102 constexpr size_t kNumCalls = 100;
1103
Steven Moreland4313d7e2021-07-15 23:41:22 +00001104 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001105
1106 std::vector<std::thread> threads;
1107 for (size_t i = 0; i < kNumClientThreads; i++) {
1108 threads.push_back(std::thread([&] {
1109 for (size_t j = 0; j < kNumCalls; j++) {
1110 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001111 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001112 EXPECT_EQ(proc.rootBinder, out);
1113 }
1114 }));
1115 }
1116
1117 for (auto& t : threads) t.join();
1118}
1119
Steven Moreland925ba0a2021-09-17 18:06:32 -07001120static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
1121 std::vector<std::thread> threads;
1122 for (size_t i = 0; i < threadCount; i++) {
1123 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
1124 }
1125 for (auto& t : threads) t.join();
1126}
1127
Steven Morelandc6046982021-04-20 00:49:42 +00001128TEST_P(BinderRpc, OnewayStressTest) {
1129 constexpr size_t kNumClientThreads = 10;
1130 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -07001131 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +00001132
Steven Moreland4313d7e2021-07-15 23:41:22 +00001133 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001134
1135 std::vector<std::thread> threads;
1136 for (size_t i = 0; i < kNumClientThreads; i++) {
1137 threads.push_back(std::thread([&] {
1138 for (size_t j = 0; j < kNumCalls; j++) {
1139 EXPECT_OK(proc.rootIface->sendString("a"));
1140 }
Steven Morelandc6046982021-04-20 00:49:42 +00001141 }));
1142 }
1143
1144 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -07001145
1146 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +00001147}
1148
Steven Morelandc1635952021-04-01 16:20:47 +00001149TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001150 constexpr size_t kReallyLongTimeMs = 100;
1151 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1152
Steven Moreland4313d7e2021-07-15 23:41:22 +00001153 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001154
1155 size_t epochMsBefore = epochMillis();
1156
1157 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1158
1159 size_t epochMsAfter = epochMillis();
1160 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1161}
1162
Steven Morelandc1635952021-04-01 16:20:47 +00001163TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001164 constexpr size_t kNumSleeps = 10;
1165 constexpr size_t kNumExtraServerThreads = 4;
1166 constexpr size_t kSleepMs = 50;
1167
1168 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001169 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001170
1171 EXPECT_OK(proc.rootIface->lock());
1172
Steven Moreland1c678802021-09-17 16:48:47 -07001173 size_t epochMsBefore = epochMillis();
1174
1175 // all these *Async commands should be queued on the server sequentially,
1176 // even though there are multiple threads.
1177 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001178 proc.rootIface->sleepMsAsync(kSleepMs);
1179 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001180 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1181
Steven Moreland1c678802021-09-17 16:48:47 -07001182 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +00001183 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -07001184
Steven Moreland5553ac42020-11-11 02:14:45 +00001185 size_t epochMsAfter = epochMillis();
1186
1187 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001188
Steven Moreland925ba0a2021-09-17 18:06:32 -07001189 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001190}
1191
Steven Morelandd45be622021-06-04 02:19:37 +00001192TEST_P(BinderRpc, OnewayCallExhaustion) {
1193 constexpr size_t kNumClients = 2;
1194 constexpr size_t kTooLongMs = 1000;
1195
Steven Moreland4313d7e2021-07-15 23:41:22 +00001196 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001197
1198 // Build up oneway calls on the second session to make sure it terminates
1199 // and shuts down. The first session should be unaffected (proc destructor
1200 // checks the first session).
1201 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1202
1203 std::vector<std::thread> threads;
1204 for (size_t i = 0; i < kNumClients; i++) {
1205 // one of these threads will get stuck queueing a transaction once the
1206 // socket fills up, the other will be able to fill up transactions on
1207 // this object
1208 threads.push_back(std::thread([&] {
1209 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1210 }
1211 }));
1212 }
1213 for (auto& t : threads) t.join();
1214
1215 Status status = iface->sleepMsAsync(kTooLongMs);
1216 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1217
Steven Moreland798e0d12021-07-14 23:19:25 +00001218 // now that it has died, wait for the remote session to shutdown
1219 std::vector<int32_t> remoteCounts;
1220 do {
1221 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1222 } while (remoteCounts.size() == kNumClients);
1223
Steven Morelandd45be622021-06-04 02:19:37 +00001224 // the second session should be shutdown in the other process by the time we
1225 // are able to join above (it'll only be hung up once it finishes processing
1226 // any pending commands). We need to erase this session from the record
1227 // here, so that the destructor for our session won't check that this
1228 // session is valid, but we still want it to test the other session.
1229 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1230}
1231
Steven Moreland659416d2021-05-11 00:47:50 +00001232TEST_P(BinderRpc, Callbacks) {
1233 const static std::string kTestString = "good afternoon!";
1234
Steven Morelandc7d40132021-06-10 03:42:11 +00001235 for (bool callIsOneway : {true, false}) {
1236 for (bool callbackIsOneway : {true, false}) {
1237 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001238 auto proc = createRpcTestSocketServerProcess(
1239 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001240 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001241
Steven Morelandc7d40132021-06-10 03:42:11 +00001242 if (callIsOneway) {
1243 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1244 kTestString));
1245 } else {
1246 EXPECT_OK(
1247 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1248 }
Steven Moreland659416d2021-05-11 00:47:50 +00001249
Steven Morelandc7d40132021-06-10 03:42:11 +00001250 using std::literals::chrono_literals::operator""s;
1251 std::unique_lock<std::mutex> _l(cb->mMutex);
1252 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001253
Steven Morelandc7d40132021-06-10 03:42:11 +00001254 EXPECT_EQ(cb->mValues.size(), 1)
1255 << "callIsOneway: " << callIsOneway
1256 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1257 if (cb->mValues.empty()) continue;
1258 EXPECT_EQ(cb->mValues.at(0), kTestString)
1259 << "callIsOneway: " << callIsOneway
1260 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001261
Steven Morelandc7d40132021-06-10 03:42:11 +00001262 // since we are severing the connection, we need to go ahead and
1263 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001264 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1265 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1266 }
Steven Moreland659416d2021-05-11 00:47:50 +00001267
Steven Moreland1b304292021-07-15 22:59:34 +00001268 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001269 // need to manually shut it down
1270 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001271
Steven Morelandc7d40132021-06-10 03:42:11 +00001272 proc.expectAlreadyShutdown = true;
1273 }
Steven Moreland659416d2021-05-11 00:47:50 +00001274 }
1275 }
1276}
1277
Steven Moreland195edb82021-06-08 02:44:39 +00001278TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001279 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001280 auto cb = sp<MyBinderRpcCallback>::make();
1281
1282 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1283 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1284}
1285
Steven Morelandc1635952021-04-01 16:20:47 +00001286TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001287 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001288 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001289
1290 // make sure there is some state during crash
1291 // 1. we hold their binder
1292 sp<IBinderRpcSession> session;
1293 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1294 // 2. they hold our binder
1295 sp<IBinder> binder = new BBinder();
1296 EXPECT_OK(proc.rootIface->holdBinder(binder));
1297
1298 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1299 << "Do death cleanup: " << doDeathCleanup;
1300
Steven Morelandaf4ca712021-05-24 23:22:08 +00001301 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001302 }
1303}
1304
Steven Morelandd7302072021-05-15 01:32:04 +00001305TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001306 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001307
1308 // we can't allocate IPCThreadState so actually the first time should
1309 // succeed :(
1310 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1311
1312 // second time! we catch the error :)
1313 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1314
Steven Morelandaf4ca712021-05-24 23:22:08 +00001315 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001316}
1317
Steven Moreland37aff182021-03-26 02:04:16 +00001318TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001319 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001320
1321 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1322 ASSERT_NE(binder, nullptr);
1323
1324 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1325}
1326
1327TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001328 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001329
1330 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1331 ASSERT_NE(binder, nullptr);
1332
1333 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1334 ASSERT_NE(ndkBinder, nullptr);
1335
1336 std::string out;
1337 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1338 ASSERT_TRUE(status.isOk()) << status.getDescription();
1339 ASSERT_EQ("aoeuaoeu", out);
1340}
1341
Steven Moreland5553ac42020-11-11 02:14:45 +00001342ssize_t countFds() {
1343 DIR* dir = opendir("/proc/self/fd/");
1344 if (dir == nullptr) return -1;
1345 ssize_t ret = 0;
1346 dirent* ent;
1347 while ((ent = readdir(dir)) != nullptr) ret++;
1348 closedir(dir);
1349 return ret;
1350}
1351
Steven Morelandc1635952021-04-01 16:20:47 +00001352TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001353 ssize_t beforeFds = countFds();
1354 ASSERT_GE(beforeFds, 0);
1355 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001356 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001357 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1358 }
1359 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1360}
1361
Steven Morelandda573042021-06-12 01:13:45 +00001362static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001363 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001364 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001365 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001366 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland1eab3452021-08-05 16:56:20 -07001367 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1368 if (status == -EAFNOSUPPORT) {
1369 return false;
1370 }
1371 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1372 }
Steven Morelandda573042021-06-12 01:13:45 +00001373 server->start();
1374
Yifan Hongfdd9f692021-09-09 15:12:52 -07001375 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001376 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001377 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001378 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1379 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001380}
1381
Yifan Hong1deca4b2021-09-10 16:16:44 -07001382static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1383 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1384
1385 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001386
1387 static bool hasVsockLoopback = testSupportVsockLoopback();
1388
1389 if (hasVsockLoopback) {
1390 ret.push_back(SocketType::VSOCK);
1391 }
1392
1393 return ret;
1394}
1395
Yifan Hong702115c2021-06-24 15:39:18 -07001396INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1397 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1398 ::testing::ValuesIn(RpcSecurityValues())),
1399 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001400
Yifan Hong702115c2021-06-24 15:39:18 -07001401class BinderRpcServerRootObject
1402 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001403
1404TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1405 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1406 auto setRootObject = [](bool isStrong) -> SetFn {
1407 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1408 };
1409
Yifan Hong702115c2021-06-24 15:39:18 -07001410 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1411 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001412 auto binder1 = sp<BBinder>::make();
1413 IBinder* binderRaw1 = binder1.get();
1414 setRootObject(isStrong1)(server.get(), binder1);
1415 EXPECT_EQ(binderRaw1, server->getRootObject());
1416 binder1.clear();
1417 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1418
1419 auto binder2 = sp<BBinder>::make();
1420 IBinder* binderRaw2 = binder2.get();
1421 setRootObject(isStrong2)(server.get(), binder2);
1422 EXPECT_EQ(binderRaw2, server->getRootObject());
1423 binder2.clear();
1424 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1425}
1426
1427INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001428 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1429 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001430
Yifan Hong1a235852021-05-13 16:07:47 -07001431class OneOffSignal {
1432public:
1433 // If notify() was previously called, or is called within |duration|, return true; else false.
1434 template <typename R, typename P>
1435 bool wait(std::chrono::duration<R, P> duration) {
1436 std::unique_lock<std::mutex> lock(mMutex);
1437 return mCv.wait_for(lock, duration, [this] { return mValue; });
1438 }
1439 void notify() {
1440 std::unique_lock<std::mutex> lock(mMutex);
1441 mValue = true;
1442 lock.unlock();
1443 mCv.notify_all();
1444 }
1445
1446private:
1447 std::mutex mMutex;
1448 std::condition_variable mCv;
1449 bool mValue = false;
1450};
1451
Yifan Hong702115c2021-06-24 15:39:18 -07001452TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001453 auto addr = allocateSocketAddress();
Yifan Hong702115c2021-06-24 15:39:18 -07001454 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong1a235852021-05-13 16:07:47 -07001455 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001456 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001457 auto joinEnds = std::make_shared<OneOffSignal>();
1458
1459 // If things are broken and the thread never stops, don't block other tests. Because the thread
1460 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1461 // shared pointers are passed.
1462 std::thread([server, joinEnds] {
1463 server->join();
1464 joinEnds->notify();
1465 }).detach();
1466
1467 bool shutdown = false;
1468 for (int i = 0; i < 10 && !shutdown; i++) {
1469 usleep(300 * 1000); // 300ms; total 3s
1470 if (server->shutdown()) shutdown = true;
1471 }
1472 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1473
1474 ASSERT_TRUE(joinEnds->wait(2s))
1475 << "After server->shutdown() returns true, join() did not stop after 2s";
1476}
1477
Yifan Hong194acf22021-06-29 18:44:56 -07001478TEST(BinderRpc, Java) {
1479#if !defined(__ANDROID__)
1480 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1481 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1482 "to binderHostDeviceTest. Hence, just disable this test on host.";
1483#endif // !__ANDROID__
1484 sp<IServiceManager> sm = defaultServiceManager();
1485 ASSERT_NE(nullptr, sm);
1486 // Any Java service with non-empty getInterfaceDescriptor() would do.
1487 // Let's pick batteryproperties.
1488 auto binder = sm->checkService(String16("batteryproperties"));
1489 ASSERT_NE(nullptr, binder);
1490 auto descriptor = binder->getInterfaceDescriptor();
1491 ASSERT_GE(descriptor.size(), 0);
1492 ASSERT_EQ(OK, binder->pingBinder());
1493
1494 auto rpcServer = RpcServer::make();
1495 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1496 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001497 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001498 auto socket = rpcServer->releaseServer();
1499
1500 auto keepAlive = sp<BBinder>::make();
1501 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1502
1503 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001504 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001505 auto rpcBinder = rpcSession->getRootObject();
1506 ASSERT_NE(nullptr, rpcBinder);
1507
1508 ASSERT_EQ(OK, rpcBinder->pingBinder());
1509
1510 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1511 << "getInterfaceDescriptor should not crash system_server";
1512 ASSERT_EQ(OK, rpcBinder->pingBinder());
1513}
1514
Yifan Hong702115c2021-06-24 15:39:18 -07001515INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1516 BinderRpcSimple::PrintTestParam);
1517
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001518class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001519public:
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001520 using Param = std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001521 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001522
1523 // A server that handles client socket connections.
1524 class Server {
1525 public:
1526 explicit Server() {}
1527 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001528 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001529 [[nodiscard]] AssertionResult setUp(
1530 const Param& param,
1531 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
1532 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001533 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
1534 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1535 switch (socketType) {
1536 case SocketType::PRECONNECTED: {
1537 return AssertionFailure() << "Not supported by this test";
1538 } break;
1539 case SocketType::UNIX: {
1540 auto addr = allocateSocketAddress();
1541 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1542 if (status != OK) {
1543 return AssertionFailure()
1544 << "setupUnixDomainServer: " << statusToString(status);
1545 }
1546 mConnectToServer = [addr] {
1547 return connectTo(UnixSocketAddress(addr.c_str()));
1548 };
1549 } break;
1550 case SocketType::VSOCK: {
1551 auto port = allocateVsockPort();
1552 auto status = rpcServer->setupVsockServer(port);
1553 if (status != OK) {
1554 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1555 }
1556 mConnectToServer = [port] {
1557 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1558 };
1559 } break;
1560 case SocketType::INET: {
1561 unsigned int port;
1562 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1563 if (status != OK) {
1564 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1565 }
1566 mConnectToServer = [port] {
1567 const char* addr = kLocalInetAddress;
1568 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1569 if (aiStart == nullptr) return base::unique_fd{};
1570 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1571 auto fd = connectTo(
1572 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1573 if (fd.ok()) return fd;
1574 }
1575 ALOGE("None of the socket address resolved for %s:%u can be connected",
1576 addr, port);
1577 return base::unique_fd{};
1578 };
1579 }
1580 }
1581 mFd = rpcServer->releaseServer();
1582 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001583 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001584 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1585 mSetup = true;
1586 return AssertionSuccess();
1587 }
1588 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1589 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1590 return mCertVerifier;
1591 }
1592 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1593 void start() {
1594 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1595 mThread = std::make_unique<std::thread>(&Server::run, this);
1596 }
1597 void run() {
1598 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1599
1600 std::vector<std::thread> threads;
1601 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1602 base::unique_fd acceptedFd(
1603 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1604 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1605 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1606 }
1607
1608 for (auto& thread : threads) thread.join();
1609 }
1610 void handleOne(android::base::unique_fd acceptedFd) {
1611 ASSERT_TRUE(acceptedFd.ok());
1612 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1613 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001614 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001615 }
Yifan Honge07d2732021-09-13 21:59:14 -07001616 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001617 shutdown();
1618 join();
1619 }
1620 void shutdown() { mFdTrigger->trigger(); }
1621
1622 void setPostConnect(
1623 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1624 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001625 }
1626
1627 private:
1628 std::unique_ptr<std::thread> mThread;
1629 ConnectToServer mConnectToServer;
1630 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1631 base::unique_fd mFd;
1632 std::unique_ptr<RpcTransportCtx> mCtx;
1633 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1634 std::make_shared<RpcCertificateVerifierSimple>();
1635 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001636 // The function invoked after connection and handshake. By default, it is
1637 // |defaultPostConnect| that sends |kMessage| to the client.
1638 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1639 Server::defaultPostConnect;
1640
1641 void join() {
1642 if (mThread != nullptr) {
1643 mThread->join();
1644 mThread = nullptr;
1645 }
1646 }
1647
1648 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1649 FdTrigger* fdTrigger) {
1650 std::string message(kMessage);
1651 auto status = serverTransport->interruptableWriteFully(fdTrigger, message.data(),
Steven Moreland43921d52021-09-27 17:15:56 -07001652 message.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001653 if (status != OK) return AssertionFailure() << statusToString(status);
1654 return AssertionSuccess();
1655 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001656 };
1657
1658 class Client {
1659 public:
1660 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1661 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001662 [[nodiscard]] AssertionResult setUp(const Param& param) {
1663 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001664 mFdTrigger = FdTrigger::make();
1665 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1666 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1667 return AssertionSuccess();
1668 }
1669 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1670 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1671 return mCertVerifier;
1672 }
Yifan Hong67519322021-09-13 18:51:16 -07001673 // connect() and do handshake
1674 bool setUpTransport() {
1675 mFd = mConnectToServer();
1676 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1677 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1678 return mClientTransport != nullptr;
1679 }
1680 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1681 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1682 std::string readMessage(expectedMessage.size(), '\0');
1683 status_t readStatus =
1684 mClientTransport->interruptableReadFully(mFdTrigger.get(), readMessage.data(),
Steven Moreland43921d52021-09-27 17:15:56 -07001685 readMessage.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001686 if (readStatus != OK) {
1687 return AssertionFailure() << statusToString(readStatus);
1688 }
1689 if (readMessage != expectedMessage) {
1690 return AssertionFailure()
1691 << "Expected " << expectedMessage << ", actual " << readMessage;
1692 }
1693 return AssertionSuccess();
1694 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001695 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001696 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001697 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1698 return;
1699 }
1700 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001701 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001702 }
1703
1704 private:
1705 ConnectToServer mConnectToServer;
1706 base::unique_fd mFd;
1707 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1708 std::unique_ptr<RpcTransportCtx> mCtx;
1709 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1710 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001711 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001712 };
1713
1714 // Make A trust B.
1715 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001716 static status_t trust(RpcSecurity rpcSecurity,
1717 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1718 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001719 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001720 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1721 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1722 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001723 }
1724
1725 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001726};
1727
1728class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1729public:
1730 using Server = RpcTransportTestUtils::Server;
1731 using Client = RpcTransportTestUtils::Client;
1732 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1733 auto [socketType, rpcSecurity, certificateFormat] = info.param;
1734 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1735 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
1736 return ret;
1737 }
1738 static std::vector<ParamType> getRpcTranportTestParams() {
1739 std::vector<ParamType> ret;
1740 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1741 for (auto rpcSecurity : RpcSecurityValues()) {
1742 switch (rpcSecurity) {
1743 case RpcSecurity::RAW: {
1744 ret.emplace_back(socketType, rpcSecurity, std::nullopt);
1745 } break;
1746 case RpcSecurity::TLS: {
1747 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM);
1748 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER);
1749 } break;
1750 }
1751 }
1752 }
1753 return ret;
1754 }
1755 template <typename A, typename B>
1756 status_t trust(const A& a, const B& b) {
1757 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1758 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1759 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001760};
1761
1762TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001763 auto server = std::make_unique<Server>();
1764 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001765
1766 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001767 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001768
1769 ASSERT_EQ(OK, trust(&client, server));
1770 ASSERT_EQ(OK, trust(server, &client));
1771
1772 server->start();
1773 client.run();
1774}
1775
1776TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001777 auto server = std::make_unique<Server>();
1778 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001779
1780 std::vector<Client> clients;
1781 for (int i = 0; i < 2; i++) {
1782 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001783 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001784 ASSERT_EQ(OK, trust(&client, server));
1785 ASSERT_EQ(OK, trust(server, &client));
1786 }
1787
1788 server->start();
1789 for (auto& client : clients) client.run();
1790}
1791
1792TEST_P(RpcTransportTest, UntrustedServer) {
1793 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1794
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001795 auto untrustedServer = std::make_unique<Server>();
1796 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001797
1798 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001799 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001800
1801 ASSERT_EQ(OK, trust(untrustedServer, &client));
1802
1803 untrustedServer->start();
1804
1805 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1806 // the client can't verify the server's identity.
1807 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1808 client.run(handshakeOk);
1809}
1810TEST_P(RpcTransportTest, MaliciousServer) {
1811 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001812 auto validServer = std::make_unique<Server>();
1813 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001814
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001815 auto maliciousServer = std::make_unique<Server>();
1816 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001817
1818 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001819 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001820
1821 ASSERT_EQ(OK, trust(&client, validServer));
1822 ASSERT_EQ(OK, trust(validServer, &client));
1823 ASSERT_EQ(OK, trust(maliciousServer, &client));
1824
1825 maliciousServer->start();
1826
1827 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1828 // the client can't verify the server's identity.
1829 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1830 client.run(handshakeOk);
1831}
1832
1833TEST_P(RpcTransportTest, UntrustedClient) {
1834 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001835 auto server = std::make_unique<Server>();
1836 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001837
1838 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001839 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001840
1841 ASSERT_EQ(OK, trust(&client, server));
1842
1843 server->start();
1844
1845 // For TLS, Client should be able to verify server's identity, so client should see
1846 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1847 // identity and should drop the connection, so client shouldn't be able to read anything.
1848 bool readOk = rpcSecurity != RpcSecurity::TLS;
1849 client.run(true, readOk);
1850}
1851
1852TEST_P(RpcTransportTest, MaliciousClient) {
1853 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001854 auto server = std::make_unique<Server>();
1855 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001856
1857 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001858 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001859 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001860 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001861
1862 ASSERT_EQ(OK, trust(&validClient, server));
1863 ASSERT_EQ(OK, trust(&maliciousClient, server));
1864
1865 server->start();
1866
1867 // See UntrustedClient.
1868 bool readOk = rpcSecurity != RpcSecurity::TLS;
1869 maliciousClient.run(true, readOk);
1870}
1871
Yifan Hong67519322021-09-13 18:51:16 -07001872TEST_P(RpcTransportTest, Trigger) {
1873 std::string msg2 = ", world!";
1874 std::mutex writeMutex;
1875 std::condition_variable writeCv;
1876 bool shouldContinueWriting = false;
1877 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001878 std::string message(RpcTransportTestUtils::kMessage);
Steven Moreland43921d52021-09-27 17:15:56 -07001879 auto status = serverTransport->interruptableWriteFully(fdTrigger, message.data(),
1880 message.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001881 if (status != OK) return AssertionFailure() << statusToString(status);
1882
1883 {
1884 std::unique_lock<std::mutex> lock(writeMutex);
1885 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1886 return AssertionFailure() << "write barrier not cleared in time!";
1887 }
1888 }
1889
Steven Moreland43921d52021-09-27 17:15:56 -07001890 status = serverTransport->interruptableWriteFully(fdTrigger, msg2.data(), msg2.size(), {});
Steven Morelandc591b472021-09-16 13:56:11 -07001891 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001892 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001893 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001894 << statusToString(status);
1895 return AssertionSuccess();
1896 };
1897
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001898 auto server = std::make_unique<Server>();
1899 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001900
1901 // Set up client
1902 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001903 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001904
1905 // Exchange keys
1906 ASSERT_EQ(OK, trust(&client, server));
1907 ASSERT_EQ(OK, trust(server, &client));
1908
1909 server->setPostConnect(serverPostConnect);
1910
Yifan Hong67519322021-09-13 18:51:16 -07001911 server->start();
1912 // connect() to server and do handshake
1913 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001914 // read the first message. This ensures that server has finished handshake and start handling
1915 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001916 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001917 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1918 // write is on an FdTrigger that has been shut down.
1919 server->shutdown();
1920 // Continues server thread to write the second message.
1921 {
Yifan Hong22211f82021-09-14 12:32:25 -07001922 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001923 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001924 }
Yifan Hong22211f82021-09-14 12:32:25 -07001925 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001926 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001927 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001928 // On the client side, second read fails with DEAD_OBJECT
1929 ASSERT_FALSE(client.readMessage(msg2));
1930}
1931
Yifan Hong1deca4b2021-09-10 16:16:44 -07001932INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001933 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001934 RpcTransportTest::PrintParamInfo);
1935
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001936class RpcTransportTlsKeyTest
1937 : public testing::TestWithParam<std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat>> {
1938public:
1939 template <typename A, typename B>
1940 status_t trust(const A& a, const B& b) {
1941 auto [socketType, certificateFormat, keyFormat] = GetParam();
1942 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1943 }
1944 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1945 auto [socketType, certificateFormat, keyFormat] = info.param;
1946 auto ret = PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1947 "_key_" + PrintToString(keyFormat);
1948 return ret;
1949 };
1950};
1951
1952TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
1953 auto [socketType, certificateFormat, keyFormat] = GetParam();
1954
1955 std::vector<uint8_t> pkeyData, certData;
1956 {
1957 auto pkey = makeKeyPairForSelfSignedCert();
1958 ASSERT_NE(nullptr, pkey);
1959 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1960 ASSERT_NE(nullptr, cert);
1961 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1962 certData = serializeCertificate(cert.get(), certificateFormat);
1963 }
1964
1965 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1966 auto desCert = deserializeCertificate(certData, certificateFormat);
1967 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
1968 auto utilsParam =
1969 std::make_tuple(socketType, RpcSecurity::TLS, std::make_optional(certificateFormat));
1970
1971 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1972 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1973
1974 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1975 ASSERT_TRUE(client.setUp(utilsParam));
1976
1977 ASSERT_EQ(OK, trust(&client, server));
1978 ASSERT_EQ(OK, trust(server, &client));
1979
1980 server->start();
1981 client.run();
1982}
1983
1984INSTANTIATE_TEST_CASE_P(
1985 BinderRpc, RpcTransportTlsKeyTest,
1986 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1987 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
1988 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER)),
1989 RpcTransportTlsKeyTest::PrintParamInfo);
1990
Steven Morelandc1635952021-04-01 16:20:47 +00001991} // namespace android
1992
1993int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001994 ::testing::InitGoogleTest(&argc, argv);
1995 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1996 return RUN_ALL_TESTS();
1997}