blob: 55ad3c69758273db27da7d89dc429a0b9d65feda [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 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700113 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -0700114 ASSERT_TRUE(server->hasServer());
115 base::unique_fd retrieved = server->releaseServer();
116 ASSERT_FALSE(server->hasServer());
117 ASSERT_EQ(sinkFd, retrieved.get());
118}
119
Steven Morelandbf57bce2021-07-26 15:26:12 -0700120TEST(BinderRpc, CannotUseNextWireVersion) {
121 auto session = RpcSession::make();
122 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
123 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
124 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
125 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
126}
127
128TEST(BinderRpc, CanUseExperimentalWireVersion) {
129 auto session = RpcSession::make();
130 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
131}
132
Steven Moreland5553ac42020-11-11 02:14:45 +0000133using android::binder::Status;
134
135#define EXPECT_OK(status) \
136 do { \
137 Status stat = (status); \
138 EXPECT_TRUE(stat.isOk()) << stat; \
139 } while (false)
140
141class MyBinderRpcSession : public BnBinderRpcSession {
142public:
143 static std::atomic<int32_t> gNum;
144
145 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
146 Status getName(std::string* name) override {
147 *name = mName;
148 return Status::ok();
149 }
150 ~MyBinderRpcSession() { gNum--; }
151
152private:
153 std::string mName;
154};
155std::atomic<int32_t> MyBinderRpcSession::gNum;
156
Steven Moreland659416d2021-05-11 00:47:50 +0000157class MyBinderRpcCallback : public BnBinderRpcCallback {
158 Status sendCallback(const std::string& value) {
159 std::unique_lock _l(mMutex);
160 mValues.push_back(value);
161 _l.unlock();
162 mCv.notify_one();
163 return Status::ok();
164 }
165 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
166
167public:
168 std::mutex mMutex;
169 std::condition_variable mCv;
170 std::vector<std::string> mValues;
171};
172
Steven Moreland5553ac42020-11-11 02:14:45 +0000173class MyBinderRpcTest : public BnBinderRpcTest {
174public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000175 wp<RpcServer> server;
Steven Moreland51c44a92021-10-14 16:50:35 -0700176 int port = 0;
Steven Moreland5553ac42020-11-11 02:14:45 +0000177
178 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000179 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000180 return Status::ok();
181 }
182 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000183 *strstr = str + str;
184 return Status::ok();
185 }
Steven Moreland51c44a92021-10-14 16:50:35 -0700186 Status getClientPort(int* out) override {
187 *out = port;
188 return Status::ok();
189 }
Steven Moreland736664b2021-05-01 04:27:25 +0000190 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000191 sp<RpcServer> spServer = server.promote();
192 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000193 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
194 }
Steven Moreland736664b2021-05-01 04:27:25 +0000195 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000196 for (auto session : spServer->listSessions()) {
197 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000198 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000199 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000200 return Status::ok();
201 }
202 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
203 if (binder == nullptr) {
204 std::cout << "Received null binder!" << std::endl;
205 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
206 }
207 *out = binder->pingBinder();
208 return Status::ok();
209 }
210 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
211 *out = binder;
212 return Status::ok();
213 }
214 static sp<IBinder> mHeldBinder;
215 Status holdBinder(const sp<IBinder>& binder) override {
216 mHeldBinder = binder;
217 return Status::ok();
218 }
219 Status getHeldBinder(sp<IBinder>* held) override {
220 *held = mHeldBinder;
221 return Status::ok();
222 }
223 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
224 if (count <= 0) return Status::ok();
225 return binder->nestMe(this, count - 1);
226 }
227 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
228 static sp<IBinder> binder = new BBinder;
229 *out = binder;
230 return Status::ok();
231 }
232 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
233 *out = new MyBinderRpcSession(name);
234 return Status::ok();
235 }
236 Status getNumOpenSessions(int32_t* out) override {
237 *out = MyBinderRpcSession::gNum;
238 return Status::ok();
239 }
240
241 std::mutex blockMutex;
242 Status lock() override {
243 blockMutex.lock();
244 return Status::ok();
245 }
246 Status unlockInMsAsync(int32_t ms) override {
247 usleep(ms * 1000);
248 blockMutex.unlock();
249 return Status::ok();
250 }
251 Status lockUnlock() override {
252 std::lock_guard<std::mutex> _l(blockMutex);
253 return Status::ok();
254 }
255
256 Status sleepMs(int32_t ms) override {
257 usleep(ms * 1000);
258 return Status::ok();
259 }
260
261 Status sleepMsAsync(int32_t ms) override {
262 // In-process binder calls are asynchronous, but the call to this method
263 // is synchronous wrt its client. This in/out-process threading model
264 // diffentiation is a classic binder leaky abstraction (for better or
265 // worse) and is preserved here the way binder sockets plugs itself
266 // into BpBinder, as nothing is changed at the higher levels
267 // (IInterface) which result in this behavior.
268 return sleepMs(ms);
269 }
270
Steven Moreland659416d2021-05-11 00:47:50 +0000271 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
272 const std::string& value) override {
273 if (callback == nullptr) {
274 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
275 }
276
277 if (delayed) {
278 std::thread([=]() {
279 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000280 Status status = doCallback(callback, oneway, false, value);
281 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000282 }).detach();
283 return Status::ok();
284 }
285
286 if (oneway) {
287 return callback->sendOnewayCallback(value);
288 }
289
290 return callback->sendCallback(value);
291 }
292
Steven Morelandc7d40132021-06-10 03:42:11 +0000293 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
294 const std::string& value) override {
295 return doCallback(callback, oneway, delayed, value);
296 }
297
Steven Moreland5553ac42020-11-11 02:14:45 +0000298 Status die(bool cleanup) override {
299 if (cleanup) {
300 exit(1);
301 } else {
302 _exit(1);
303 }
304 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000305
306 Status scheduleShutdown() override {
307 sp<RpcServer> strongServer = server.promote();
308 if (strongServer == nullptr) {
309 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
310 }
311 std::thread([=] {
312 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
313 }).detach();
314 return Status::ok();
315 }
316
Steven Morelandd7302072021-05-15 01:32:04 +0000317 Status useKernelBinderCallingId() override {
318 // this is WRONG! It does not make sense when using RPC binder, and
319 // because it is SO wrong, and so much code calls this, it should abort!
320
321 (void)IPCThreadState::self()->getCallingPid();
322 return Status::ok();
323 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000324};
325sp<IBinder> MyBinderRpcTest::mHeldBinder;
326
327class Process {
328public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700329 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700330 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
331 android::base::borrowed_fd /* readEnd */)>& f) {
332 android::base::unique_fd childWriteEnd;
333 android::base::unique_fd childReadEnd;
334 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
335 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000336 if (0 == (mPid = fork())) {
337 // racey: assume parent doesn't crash before this is set
338 prctl(PR_SET_PDEATHSIG, SIGHUP);
339
Yifan Hong1deca4b2021-09-10 16:16:44 -0700340 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000341
342 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000343 }
344 }
345 ~Process() {
346 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000347 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000348 }
349 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700350 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700351 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000352
353private:
354 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700355 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700356 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000357};
358
359static std::string allocateSocketAddress() {
360 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000361 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700362 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
363 unlink(ret.c_str());
364 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000365};
366
Steven Morelandda573042021-06-12 01:13:45 +0000367static unsigned int allocateVsockPort() {
368 static unsigned int vsockPort = 3456;
369 return vsockPort++;
370}
371
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000372struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000373 // reference to process hosting a socket server
374 Process host;
375
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000376 struct SessionInfo {
377 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000378 sp<IBinder> root;
379 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000380
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000381 // client session objects associated with other process
382 // each one represents a separate session
383 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000384
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000385 ProcessSession(ProcessSession&&) = default;
386 ~ProcessSession() {
387 for (auto& session : sessions) {
388 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000389 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000390
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000391 for (auto& info : sessions) {
392 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000393
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000394 EXPECT_NE(nullptr, session);
395 EXPECT_NE(nullptr, session->state());
396 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000397
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000398 wp<RpcSession> weakSession = session;
399 session = nullptr;
400 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000401 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000402 }
403};
404
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000405// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000406// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000407struct BinderRpcTestProcessSession {
408 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000409
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000410 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000411 sp<IBinder> rootBinder;
412
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000413 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000414 sp<IBinderRpcTest> rootIface;
415
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000416 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000417 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000418
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000419 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
420 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000421 EXPECT_NE(nullptr, rootIface);
422 if (rootIface == nullptr) return;
423
Steven Morelandaf4ca712021-05-24 23:22:08 +0000424 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000425 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000426 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000427 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000428 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000429 for (auto remoteCount : remoteCounts) {
430 EXPECT_EQ(remoteCount, 1);
431 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000432
Steven Moreland798e0d12021-07-14 23:19:25 +0000433 // even though it is on another thread, shutdown races with
434 // the transaction reply being written
435 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
436 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
437 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000438 }
439
440 rootIface = nullptr;
441 rootBinder = nullptr;
442 }
443};
444
Steven Morelandc1635952021-04-01 16:20:47 +0000445enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700446 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000447 UNIX,
448 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700449 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000450};
Yifan Hong702115c2021-06-24 15:39:18 -0700451static inline std::string PrintToString(SocketType socketType) {
452 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700453 case SocketType::PRECONNECTED:
454 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000455 case SocketType::UNIX:
456 return "unix_domain_socket";
457 case SocketType::VSOCK:
458 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700459 case SocketType::INET:
460 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000461 default:
462 LOG_ALWAYS_FATAL("Unknown socket type");
463 return "";
464 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000465}
Steven Morelandda573042021-06-12 01:13:45 +0000466
Yifan Hong1deca4b2021-09-10 16:16:44 -0700467static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700468 base::unique_fd serverFd(
469 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
470 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700471 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
472 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700473
474 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
475 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700476 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
477 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700478 }
479 return serverFd;
480}
481
Yifan Hong702115c2021-06-24 15:39:18 -0700482class BinderRpc : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000483public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000484 struct Options {
485 size_t numThreads = 1;
486 size_t numSessions = 1;
487 size_t numIncomingConnections = 0;
Yifan Hong1f44f982021-10-08 17:16:47 -0700488 size_t numOutgoingConnections = SIZE_MAX;
Steven Moreland4313d7e2021-07-15 23:41:22 +0000489 };
490
Yifan Hong702115c2021-06-24 15:39:18 -0700491 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
492 auto [type, security] = info.param;
493 return PrintToString(type) + "_" + newFactory(security)->toCString();
494 }
495
Yifan Hong1deca4b2021-09-10 16:16:44 -0700496 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
497 uint64_t length = str.length();
498 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
499 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
500 }
501
502 static inline std::string readString(android::base::borrowed_fd fd) {
503 uint64_t length;
504 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
505 std::string ret(length, '\0');
506 CHECK(android::base::ReadFully(fd, ret.data(), length));
507 return ret;
508 }
509
510 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
511 Parcel parcel;
512 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
513 writeString(fd,
514 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
515 }
516
517 template <typename T>
518 static inline T readFromFd(android::base::borrowed_fd fd) {
519 std::string data = readString(fd);
520 Parcel parcel;
521 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
522 T object;
523 CHECK_EQ(OK, object.readFromParcel(&parcel));
524 return object;
525 }
526
Steven Morelandc1635952021-04-01 16:20:47 +0000527 // This creates a new process serving an interface on a certain number of
528 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000529 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000530 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
531 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000532
Yifan Hong702115c2021-06-24 15:39:18 -0700533 SocketType socketType = std::get<0>(GetParam());
534 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000535
Steven Morelandda573042021-06-12 01:13:45 +0000536 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000537 std::string addr = allocateSocketAddress();
Steven Morelandc1635952021-04-01 16:20:47 +0000538
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000539 auto ret = ProcessSession{
Yifan Hong1deca4b2021-09-10 16:16:44 -0700540 .host = Process([&](android::base::borrowed_fd writeEnd,
541 android::base::borrowed_fd readEnd) {
542 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
543 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
Steven Morelandc1635952021-04-01 16:20:47 +0000544
Steven Moreland4313d7e2021-07-15 23:41:22 +0000545 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000546
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000547 unsigned int outPort = 0;
548
Steven Morelandc1635952021-04-01 16:20:47 +0000549 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700550 case SocketType::PRECONNECTED:
551 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000552 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700553 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000554 break;
555 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700556 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000557 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700558 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700559 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700560 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700561 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700562 }
Steven Morelandc1635952021-04-01 16:20:47 +0000563 default:
564 LOG_ALWAYS_FATAL("Unknown socket type");
565 }
566
Yifan Hong1deca4b2021-09-10 16:16:44 -0700567 BinderRpcTestServerInfo serverInfo;
568 serverInfo.port = static_cast<int64_t>(outPort);
Yifan Hong9734cfc2021-09-13 16:14:09 -0700569 serverInfo.cert.data = server->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700570 writeToFd(writeEnd, serverInfo);
571 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
572
573 if (rpcSecurity == RpcSecurity::TLS) {
574 for (const auto& clientCert : clientInfo.certs) {
575 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700576 certVerifier
577 ->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
578 clientCert.data));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700579 }
580 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000581
Steven Moreland611d15f2021-05-01 01:28:27 +0000582 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000583
Steven Morelandf137de92021-04-24 01:54:26 +0000584 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000585
586 // Another thread calls shutdown. Wait for it to complete.
587 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000588 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000589 };
590
Yifan Hong1deca4b2021-09-10 16:16:44 -0700591 std::vector<sp<RpcSession>> sessions;
592 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
593 for (size_t i = 0; i < options.numSessions; i++) {
594 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
595 }
596
597 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
598 BinderRpcTestClientInfo clientInfo;
599 for (const auto& session : sessions) {
600 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700601 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700602 }
603 writeToFd(ret.host.writeEnd(), clientInfo);
604
605 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700606 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700607 CHECK_NE(0, serverInfo.port);
608 }
609
610 if (rpcSecurity == RpcSecurity::TLS) {
611 const auto& serverCert = serverInfo.cert.data;
612 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700613 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
614 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700615 }
616
Steven Moreland2372f9d2021-08-05 15:42:01 -0700617 status_t status;
618
Yifan Hong1deca4b2021-09-10 16:16:44 -0700619 for (const auto& session : sessions) {
Yifan Hong10423062021-10-08 16:26:32 -0700620 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700621 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000622
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000623 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700624 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700625 status = session->setupPreconnectedClient({}, [=]() {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700626 return connectTo(UnixSocketAddress(addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700627 });
Steven Moreland4198a122021-08-03 17:37:58 -0700628 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000629 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700630 status = session->setupUnixDomainClient(addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000631 break;
632 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700633 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000634 break;
635 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700636 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000637 break;
638 default:
639 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000640 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700641 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000642 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000643 }
Steven Morelandc1635952021-04-01 16:20:47 +0000644 return ret;
645 }
646
Steven Moreland4313d7e2021-07-15 23:41:22 +0000647 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000648 BinderRpcTestProcessSession ret{
Steven Moreland51c44a92021-10-14 16:50:35 -0700649 .proc = createRpcTestSocketServerProcess(
650 options,
651 [&](const sp<RpcServer>& server) {
652 server->setPerSessionRootObject([&](const sockaddr* addr,
653 socklen_t len) {
654 sp<MyBinderRpcTest> service = sp<MyBinderRpcTest>::make();
655 switch (addr->sa_family) {
656 case AF_UNIX:
657 // nothing to save
658 break;
659 case AF_VSOCK:
660 CHECK_EQ(len, sizeof(sockaddr_vm));
661 service->port = reinterpret_cast<const sockaddr_vm*>(addr)
662 ->svm_port;
663 break;
664 case AF_INET:
665 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700666 service->port =
667 ntohs(reinterpret_cast<const sockaddr_in*>(addr)
668 ->sin_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700669 break;
670 case AF_INET6:
671 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700672 service->port =
673 ntohs(reinterpret_cast<const sockaddr_in6*>(addr)
674 ->sin6_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700675 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 Morelanda83191d2021-10-27 10:14:53 -07001306 bool okToFork = ProcessState::selfOrNull() == nullptr;
1307
Steven Moreland4313d7e2021-07-15 23:41:22 +00001308 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001309
Steven Morelanda83191d2021-10-27 10:14:53 -07001310 // If this process has used ProcessState already, then the forked process
1311 // cannot use it at all. If this process hasn't used it (depending on the
1312 // order tests are run), then the forked process can use it, and we'll only
1313 // catch the invalid usage the second time. Such is the burden of global
1314 // state!
1315 if (okToFork) {
1316 // we can't allocate IPCThreadState so actually the first time should
1317 // succeed :(
1318 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1319 }
Steven Morelandd7302072021-05-15 01:32:04 +00001320
1321 // second time! we catch the error :)
1322 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1323
Steven Morelandaf4ca712021-05-24 23:22:08 +00001324 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001325}
1326
Steven Moreland37aff182021-03-26 02:04:16 +00001327TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
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 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1334}
1335
1336TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001337 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001338
1339 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1340 ASSERT_NE(binder, nullptr);
1341
1342 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1343 ASSERT_NE(ndkBinder, nullptr);
1344
1345 std::string out;
1346 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1347 ASSERT_TRUE(status.isOk()) << status.getDescription();
1348 ASSERT_EQ("aoeuaoeu", out);
1349}
1350
Steven Moreland5553ac42020-11-11 02:14:45 +00001351ssize_t countFds() {
1352 DIR* dir = opendir("/proc/self/fd/");
1353 if (dir == nullptr) return -1;
1354 ssize_t ret = 0;
1355 dirent* ent;
1356 while ((ent = readdir(dir)) != nullptr) ret++;
1357 closedir(dir);
1358 return ret;
1359}
1360
Steven Morelandc1635952021-04-01 16:20:47 +00001361TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001362 ssize_t beforeFds = countFds();
1363 ASSERT_GE(beforeFds, 0);
1364 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001365 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001366 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1367 }
1368 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1369}
1370
Devin Moore800b2252021-10-15 16:22:57 +00001371TEST_P(BinderRpc, AidlDelegatorTest) {
1372 auto proc = createRpcTestSocketServerProcess({});
1373 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1374 ASSERT_NE(nullptr, myDelegator);
1375
1376 std::string doubled;
1377 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1378 EXPECT_EQ("cool cool ", doubled);
1379}
1380
Steven Morelandda573042021-06-12 01:13:45 +00001381static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001382 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001383 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001384 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland1eab3452021-08-05 16:56:20 -07001385 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1386 if (status == -EAFNOSUPPORT) {
1387 return false;
1388 }
1389 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1390 }
Steven Morelandda573042021-06-12 01:13:45 +00001391 server->start();
1392
Yifan Hongfdd9f692021-09-09 15:12:52 -07001393 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001394 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001395 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001396 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1397 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001398}
1399
Yifan Hong1deca4b2021-09-10 16:16:44 -07001400static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1401 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1402
1403 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001404
1405 static bool hasVsockLoopback = testSupportVsockLoopback();
1406
1407 if (hasVsockLoopback) {
1408 ret.push_back(SocketType::VSOCK);
1409 }
1410
1411 return ret;
1412}
1413
Yifan Hong702115c2021-06-24 15:39:18 -07001414INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1415 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1416 ::testing::ValuesIn(RpcSecurityValues())),
1417 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001418
Yifan Hong702115c2021-06-24 15:39:18 -07001419class BinderRpcServerRootObject
1420 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001421
1422TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1423 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1424 auto setRootObject = [](bool isStrong) -> SetFn {
1425 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1426 };
1427
Yifan Hong702115c2021-06-24 15:39:18 -07001428 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1429 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001430 auto binder1 = sp<BBinder>::make();
1431 IBinder* binderRaw1 = binder1.get();
1432 setRootObject(isStrong1)(server.get(), binder1);
1433 EXPECT_EQ(binderRaw1, server->getRootObject());
1434 binder1.clear();
1435 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1436
1437 auto binder2 = sp<BBinder>::make();
1438 IBinder* binderRaw2 = binder2.get();
1439 setRootObject(isStrong2)(server.get(), binder2);
1440 EXPECT_EQ(binderRaw2, server->getRootObject());
1441 binder2.clear();
1442 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1443}
1444
1445INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001446 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1447 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001448
Yifan Hong1a235852021-05-13 16:07:47 -07001449class OneOffSignal {
1450public:
1451 // If notify() was previously called, or is called within |duration|, return true; else false.
1452 template <typename R, typename P>
1453 bool wait(std::chrono::duration<R, P> duration) {
1454 std::unique_lock<std::mutex> lock(mMutex);
1455 return mCv.wait_for(lock, duration, [this] { return mValue; });
1456 }
1457 void notify() {
1458 std::unique_lock<std::mutex> lock(mMutex);
1459 mValue = true;
1460 lock.unlock();
1461 mCv.notify_all();
1462 }
1463
1464private:
1465 std::mutex mMutex;
1466 std::condition_variable mCv;
1467 bool mValue = false;
1468};
1469
Yifan Hong702115c2021-06-24 15:39:18 -07001470TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001471 auto addr = allocateSocketAddress();
Yifan Hong702115c2021-06-24 15:39:18 -07001472 auto server = RpcServer::make(newFactory(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001473 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001474 auto joinEnds = std::make_shared<OneOffSignal>();
1475
1476 // If things are broken and the thread never stops, don't block other tests. Because the thread
1477 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1478 // shared pointers are passed.
1479 std::thread([server, joinEnds] {
1480 server->join();
1481 joinEnds->notify();
1482 }).detach();
1483
1484 bool shutdown = false;
1485 for (int i = 0; i < 10 && !shutdown; i++) {
1486 usleep(300 * 1000); // 300ms; total 3s
1487 if (server->shutdown()) shutdown = true;
1488 }
1489 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1490
1491 ASSERT_TRUE(joinEnds->wait(2s))
1492 << "After server->shutdown() returns true, join() did not stop after 2s";
1493}
1494
Yifan Hong194acf22021-06-29 18:44:56 -07001495TEST(BinderRpc, Java) {
1496#if !defined(__ANDROID__)
1497 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1498 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1499 "to binderHostDeviceTest. Hence, just disable this test on host.";
1500#endif // !__ANDROID__
1501 sp<IServiceManager> sm = defaultServiceManager();
1502 ASSERT_NE(nullptr, sm);
1503 // Any Java service with non-empty getInterfaceDescriptor() would do.
1504 // Let's pick batteryproperties.
1505 auto binder = sm->checkService(String16("batteryproperties"));
1506 ASSERT_NE(nullptr, binder);
1507 auto descriptor = binder->getInterfaceDescriptor();
1508 ASSERT_GE(descriptor.size(), 0);
1509 ASSERT_EQ(OK, binder->pingBinder());
1510
1511 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001512 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001513 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001514 auto socket = rpcServer->releaseServer();
1515
1516 auto keepAlive = sp<BBinder>::make();
1517 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1518
1519 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001520 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001521 auto rpcBinder = rpcSession->getRootObject();
1522 ASSERT_NE(nullptr, rpcBinder);
1523
1524 ASSERT_EQ(OK, rpcBinder->pingBinder());
1525
1526 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1527 << "getInterfaceDescriptor should not crash system_server";
1528 ASSERT_EQ(OK, rpcBinder->pingBinder());
1529}
1530
Yifan Hong702115c2021-06-24 15:39:18 -07001531INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1532 BinderRpcSimple::PrintTestParam);
1533
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001534class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001535public:
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001536 using Param = std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001537 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001538
1539 // A server that handles client socket connections.
1540 class Server {
1541 public:
1542 explicit Server() {}
1543 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001544 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001545 [[nodiscard]] AssertionResult setUp(
1546 const Param& param,
1547 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
1548 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001549 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001550 switch (socketType) {
1551 case SocketType::PRECONNECTED: {
1552 return AssertionFailure() << "Not supported by this test";
1553 } break;
1554 case SocketType::UNIX: {
1555 auto addr = allocateSocketAddress();
1556 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1557 if (status != OK) {
1558 return AssertionFailure()
1559 << "setupUnixDomainServer: " << statusToString(status);
1560 }
1561 mConnectToServer = [addr] {
1562 return connectTo(UnixSocketAddress(addr.c_str()));
1563 };
1564 } break;
1565 case SocketType::VSOCK: {
1566 auto port = allocateVsockPort();
1567 auto status = rpcServer->setupVsockServer(port);
1568 if (status != OK) {
1569 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1570 }
1571 mConnectToServer = [port] {
1572 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1573 };
1574 } break;
1575 case SocketType::INET: {
1576 unsigned int port;
1577 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1578 if (status != OK) {
1579 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1580 }
1581 mConnectToServer = [port] {
1582 const char* addr = kLocalInetAddress;
1583 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1584 if (aiStart == nullptr) return base::unique_fd{};
1585 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1586 auto fd = connectTo(
1587 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1588 if (fd.ok()) return fd;
1589 }
1590 ALOGE("None of the socket address resolved for %s:%u can be connected",
1591 addr, port);
1592 return base::unique_fd{};
1593 };
1594 }
1595 }
1596 mFd = rpcServer->releaseServer();
1597 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001598 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001599 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1600 mSetup = true;
1601 return AssertionSuccess();
1602 }
1603 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1604 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1605 return mCertVerifier;
1606 }
1607 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1608 void start() {
1609 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1610 mThread = std::make_unique<std::thread>(&Server::run, this);
1611 }
1612 void run() {
1613 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1614
1615 std::vector<std::thread> threads;
1616 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1617 base::unique_fd acceptedFd(
1618 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1619 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1620 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1621 }
1622
1623 for (auto& thread : threads) thread.join();
1624 }
1625 void handleOne(android::base::unique_fd acceptedFd) {
1626 ASSERT_TRUE(acceptedFd.ok());
1627 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1628 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001629 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001630 }
Yifan Honge07d2732021-09-13 21:59:14 -07001631 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001632 shutdown();
1633 join();
1634 }
1635 void shutdown() { mFdTrigger->trigger(); }
1636
1637 void setPostConnect(
1638 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1639 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001640 }
1641
1642 private:
1643 std::unique_ptr<std::thread> mThread;
1644 ConnectToServer mConnectToServer;
1645 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1646 base::unique_fd mFd;
1647 std::unique_ptr<RpcTransportCtx> mCtx;
1648 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1649 std::make_shared<RpcCertificateVerifierSimple>();
1650 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001651 // The function invoked after connection and handshake. By default, it is
1652 // |defaultPostConnect| that sends |kMessage| to the client.
1653 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1654 Server::defaultPostConnect;
1655
1656 void join() {
1657 if (mThread != nullptr) {
1658 mThread->join();
1659 mThread = nullptr;
1660 }
1661 }
1662
1663 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1664 FdTrigger* fdTrigger) {
1665 std::string message(kMessage);
1666 auto status = serverTransport->interruptableWriteFully(fdTrigger, message.data(),
Steven Moreland43921d52021-09-27 17:15:56 -07001667 message.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001668 if (status != OK) return AssertionFailure() << statusToString(status);
1669 return AssertionSuccess();
1670 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001671 };
1672
1673 class Client {
1674 public:
1675 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1676 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001677 [[nodiscard]] AssertionResult setUp(const Param& param) {
1678 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001679 mFdTrigger = FdTrigger::make();
1680 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1681 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1682 return AssertionSuccess();
1683 }
1684 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1685 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1686 return mCertVerifier;
1687 }
Yifan Hong67519322021-09-13 18:51:16 -07001688 // connect() and do handshake
1689 bool setUpTransport() {
1690 mFd = mConnectToServer();
1691 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1692 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1693 return mClientTransport != nullptr;
1694 }
1695 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1696 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1697 std::string readMessage(expectedMessage.size(), '\0');
1698 status_t readStatus =
1699 mClientTransport->interruptableReadFully(mFdTrigger.get(), readMessage.data(),
Steven Moreland43921d52021-09-27 17:15:56 -07001700 readMessage.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001701 if (readStatus != OK) {
1702 return AssertionFailure() << statusToString(readStatus);
1703 }
1704 if (readMessage != expectedMessage) {
1705 return AssertionFailure()
1706 << "Expected " << expectedMessage << ", actual " << readMessage;
1707 }
1708 return AssertionSuccess();
1709 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001710 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001711 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001712 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1713 return;
1714 }
1715 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001716 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001717 }
1718
1719 private:
1720 ConnectToServer mConnectToServer;
1721 base::unique_fd mFd;
1722 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1723 std::unique_ptr<RpcTransportCtx> mCtx;
1724 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1725 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001726 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001727 };
1728
1729 // Make A trust B.
1730 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001731 static status_t trust(RpcSecurity rpcSecurity,
1732 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1733 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001734 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001735 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1736 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1737 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001738 }
1739
1740 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001741};
1742
1743class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1744public:
1745 using Server = RpcTransportTestUtils::Server;
1746 using Client = RpcTransportTestUtils::Client;
1747 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1748 auto [socketType, rpcSecurity, certificateFormat] = info.param;
1749 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1750 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
1751 return ret;
1752 }
1753 static std::vector<ParamType> getRpcTranportTestParams() {
1754 std::vector<ParamType> ret;
1755 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1756 for (auto rpcSecurity : RpcSecurityValues()) {
1757 switch (rpcSecurity) {
1758 case RpcSecurity::RAW: {
1759 ret.emplace_back(socketType, rpcSecurity, std::nullopt);
1760 } break;
1761 case RpcSecurity::TLS: {
1762 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM);
1763 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER);
1764 } break;
1765 }
1766 }
1767 }
1768 return ret;
1769 }
1770 template <typename A, typename B>
1771 status_t trust(const A& a, const B& b) {
1772 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1773 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1774 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001775};
1776
1777TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001778 auto server = std::make_unique<Server>();
1779 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001780
1781 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001782 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001783
1784 ASSERT_EQ(OK, trust(&client, server));
1785 ASSERT_EQ(OK, trust(server, &client));
1786
1787 server->start();
1788 client.run();
1789}
1790
1791TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001792 auto server = std::make_unique<Server>();
1793 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001794
1795 std::vector<Client> clients;
1796 for (int i = 0; i < 2; i++) {
1797 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001798 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001799 ASSERT_EQ(OK, trust(&client, server));
1800 ASSERT_EQ(OK, trust(server, &client));
1801 }
1802
1803 server->start();
1804 for (auto& client : clients) client.run();
1805}
1806
1807TEST_P(RpcTransportTest, UntrustedServer) {
1808 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1809
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001810 auto untrustedServer = std::make_unique<Server>();
1811 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001812
1813 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001814 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001815
1816 ASSERT_EQ(OK, trust(untrustedServer, &client));
1817
1818 untrustedServer->start();
1819
1820 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1821 // the client can't verify the server's identity.
1822 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1823 client.run(handshakeOk);
1824}
1825TEST_P(RpcTransportTest, MaliciousServer) {
1826 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001827 auto validServer = std::make_unique<Server>();
1828 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001829
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001830 auto maliciousServer = std::make_unique<Server>();
1831 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001832
1833 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001834 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001835
1836 ASSERT_EQ(OK, trust(&client, validServer));
1837 ASSERT_EQ(OK, trust(validServer, &client));
1838 ASSERT_EQ(OK, trust(maliciousServer, &client));
1839
1840 maliciousServer->start();
1841
1842 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1843 // the client can't verify the server's identity.
1844 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1845 client.run(handshakeOk);
1846}
1847
1848TEST_P(RpcTransportTest, UntrustedClient) {
1849 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001850 auto server = std::make_unique<Server>();
1851 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001852
1853 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001854 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001855
1856 ASSERT_EQ(OK, trust(&client, server));
1857
1858 server->start();
1859
1860 // For TLS, Client should be able to verify server's identity, so client should see
1861 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1862 // identity and should drop the connection, so client shouldn't be able to read anything.
1863 bool readOk = rpcSecurity != RpcSecurity::TLS;
1864 client.run(true, readOk);
1865}
1866
1867TEST_P(RpcTransportTest, MaliciousClient) {
1868 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001869 auto server = std::make_unique<Server>();
1870 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001871
1872 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001873 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001874 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001875 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001876
1877 ASSERT_EQ(OK, trust(&validClient, server));
1878 ASSERT_EQ(OK, trust(&maliciousClient, server));
1879
1880 server->start();
1881
1882 // See UntrustedClient.
1883 bool readOk = rpcSecurity != RpcSecurity::TLS;
1884 maliciousClient.run(true, readOk);
1885}
1886
Yifan Hong67519322021-09-13 18:51:16 -07001887TEST_P(RpcTransportTest, Trigger) {
1888 std::string msg2 = ", world!";
1889 std::mutex writeMutex;
1890 std::condition_variable writeCv;
1891 bool shouldContinueWriting = false;
1892 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001893 std::string message(RpcTransportTestUtils::kMessage);
Steven Moreland43921d52021-09-27 17:15:56 -07001894 auto status = serverTransport->interruptableWriteFully(fdTrigger, message.data(),
1895 message.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001896 if (status != OK) return AssertionFailure() << statusToString(status);
1897
1898 {
1899 std::unique_lock<std::mutex> lock(writeMutex);
1900 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1901 return AssertionFailure() << "write barrier not cleared in time!";
1902 }
1903 }
1904
Steven Moreland43921d52021-09-27 17:15:56 -07001905 status = serverTransport->interruptableWriteFully(fdTrigger, msg2.data(), msg2.size(), {});
Steven Morelandc591b472021-09-16 13:56:11 -07001906 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001907 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001908 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001909 << statusToString(status);
1910 return AssertionSuccess();
1911 };
1912
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001913 auto server = std::make_unique<Server>();
1914 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001915
1916 // Set up client
1917 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001918 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001919
1920 // Exchange keys
1921 ASSERT_EQ(OK, trust(&client, server));
1922 ASSERT_EQ(OK, trust(server, &client));
1923
1924 server->setPostConnect(serverPostConnect);
1925
Yifan Hong67519322021-09-13 18:51:16 -07001926 server->start();
1927 // connect() to server and do handshake
1928 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001929 // read the first message. This ensures that server has finished handshake and start handling
1930 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001931 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001932 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1933 // write is on an FdTrigger that has been shut down.
1934 server->shutdown();
1935 // Continues server thread to write the second message.
1936 {
Yifan Hong22211f82021-09-14 12:32:25 -07001937 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001938 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001939 }
Yifan Hong22211f82021-09-14 12:32:25 -07001940 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001941 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001942 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001943 // On the client side, second read fails with DEAD_OBJECT
1944 ASSERT_FALSE(client.readMessage(msg2));
1945}
1946
Yifan Hong1deca4b2021-09-10 16:16:44 -07001947INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001948 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001949 RpcTransportTest::PrintParamInfo);
1950
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001951class RpcTransportTlsKeyTest
1952 : public testing::TestWithParam<std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat>> {
1953public:
1954 template <typename A, typename B>
1955 status_t trust(const A& a, const B& b) {
1956 auto [socketType, certificateFormat, keyFormat] = GetParam();
1957 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1958 }
1959 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1960 auto [socketType, certificateFormat, keyFormat] = info.param;
1961 auto ret = PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1962 "_key_" + PrintToString(keyFormat);
1963 return ret;
1964 };
1965};
1966
1967TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
1968 auto [socketType, certificateFormat, keyFormat] = GetParam();
1969
1970 std::vector<uint8_t> pkeyData, certData;
1971 {
1972 auto pkey = makeKeyPairForSelfSignedCert();
1973 ASSERT_NE(nullptr, pkey);
1974 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1975 ASSERT_NE(nullptr, cert);
1976 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1977 certData = serializeCertificate(cert.get(), certificateFormat);
1978 }
1979
1980 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1981 auto desCert = deserializeCertificate(certData, certificateFormat);
1982 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
1983 auto utilsParam =
1984 std::make_tuple(socketType, RpcSecurity::TLS, std::make_optional(certificateFormat));
1985
1986 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1987 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1988
1989 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1990 ASSERT_TRUE(client.setUp(utilsParam));
1991
1992 ASSERT_EQ(OK, trust(&client, server));
1993 ASSERT_EQ(OK, trust(server, &client));
1994
1995 server->start();
1996 client.run();
1997}
1998
1999INSTANTIATE_TEST_CASE_P(
2000 BinderRpc, RpcTransportTlsKeyTest,
2001 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2002 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
2003 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER)),
2004 RpcTransportTlsKeyTest::PrintParamInfo);
2005
Steven Morelandc1635952021-04-01 16:20:47 +00002006} // namespace android
2007
2008int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002009 ::testing::InitGoogleTest(&argc, argv);
2010 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002011
Steven Moreland5553ac42020-11-11 02:14:45 +00002012 return RUN_ALL_TESTS();
2013}