blob: 0cbb88038b465f4fcf2a07c26abfb9f84e1c2efd [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));
666 service->port = reinterpret_cast<const sockaddr_in*>(addr)
667 ->sin_port;
668 break;
669 case AF_INET6:
670 CHECK_EQ(len, sizeof(sockaddr_in));
671 service->port = reinterpret_cast<const sockaddr_in6*>(addr)
672 ->sin6_port;
673 break;
674 default:
675 LOG_ALWAYS_FATAL("Unrecognized address family %d",
676 addr->sa_family);
677 }
678 service->server = server;
679 return service;
680 });
681 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000682 };
683
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000684 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000685 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
686
687 return ret;
688 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700689
690 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
691 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000692};
693
Steven Morelandc1635952021-04-01 16:20:47 +0000694TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000695 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000696 ASSERT_NE(proc.rootBinder, nullptr);
697 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
698}
699
Steven Moreland4cf688f2021-03-31 01:48:58 +0000700TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000701 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000702 ASSERT_NE(proc.rootBinder, nullptr);
703 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
704}
705
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000706TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000707 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000708 for (auto session : proc.proc.sessions) {
709 ASSERT_NE(nullptr, session.root);
710 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000711 }
712}
713
Steven Moreland51c44a92021-10-14 16:50:35 -0700714TEST_P(BinderRpc, SeparateRootObject) {
715 SocketType type = std::get<0>(GetParam());
716 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
717 // we can't get port numbers for unix sockets
718 return;
719 }
720
721 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
722
723 int port1 = 0;
724 EXPECT_OK(proc.rootIface->getClientPort(&port1));
725
726 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
727 int port2;
728 EXPECT_OK(rootIface2->getClientPort(&port2));
729
730 // we should have a different IBinderRpcTest object created for each
731 // session, because we use setPerSessionRootObject
732 EXPECT_NE(port1, port2);
733}
734
Steven Morelandc1635952021-04-01 16:20:47 +0000735TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000736 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000737 Parcel data;
738 Parcel reply;
739 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
740}
741
Steven Moreland67753c32021-04-02 18:45:19 +0000742TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700743 auto proc1 = createRpcTestSocketServerProcess({});
744 auto proc2 = createRpcTestSocketServerProcess({});
745
746 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000747
748 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700749 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000750 p1.writeInt32(3);
751
Steven Moreland2034eff2021-10-13 11:24:35 -0700752 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, p1.dataSize()));
753 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
754
Steven Moreland67753c32021-04-02 18:45:19 +0000755 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700756 p2.markForBinder(proc2.rootBinder);
757 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000758
759 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
760 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
761}
762
Steven Morelandc1635952021-04-01 16:20:47 +0000763TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000764 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000765 Parcel data;
766 data.markForBinder(proc.rootBinder);
767 Parcel reply;
768 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
769}
770
Steven Morelandc1635952021-04-01 16:20:47 +0000771TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000772 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000773 EXPECT_OK(proc.rootIface->sendString("asdf"));
774}
775
Steven Morelandc1635952021-04-01 16:20:47 +0000776TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000777 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000778 std::string doubled;
779 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
780 EXPECT_EQ("cool cool ", doubled);
781}
782
Steven Morelandc1635952021-04-01 16:20:47 +0000783TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000784 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000785 std::string single = std::string(1024, 'a');
786 std::string doubled;
787 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
788 EXPECT_EQ(single + single, doubled);
789}
790
Steven Morelandc1635952021-04-01 16:20:47 +0000791TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000792 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000793
794 int32_t pingResult;
795 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
796 EXPECT_EQ(OK, pingResult);
797
798 EXPECT_EQ(0, MyBinderRpcSession::gNum);
799}
800
Steven Morelandc1635952021-04-01 16:20:47 +0000801TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000802 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000803
804 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
805 sp<IBinder> outBinder;
806 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
807 EXPECT_EQ(inBinder, outBinder);
808
809 wp<IBinder> weak = inBinder;
810 inBinder = nullptr;
811 outBinder = nullptr;
812
813 // Force reading a reply, to process any pending dec refs from the other
814 // process (the other process will process dec refs there before processing
815 // the ping here).
816 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
817
818 EXPECT_EQ(nullptr, weak.promote());
819
820 EXPECT_EQ(0, MyBinderRpcSession::gNum);
821}
822
Steven Morelandc1635952021-04-01 16:20:47 +0000823TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000824 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000825
826 sp<IBinderRpcSession> session;
827 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
828
829 sp<IBinder> inBinder = IInterface::asBinder(session);
830 sp<IBinder> outBinder;
831 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
832 EXPECT_EQ(inBinder, outBinder);
833
834 wp<IBinder> weak = inBinder;
835 session = nullptr;
836 inBinder = nullptr;
837 outBinder = nullptr;
838
839 // Force reading a reply, to process any pending dec refs from the other
840 // process (the other process will process dec refs there before processing
841 // the ping here).
842 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
843
844 EXPECT_EQ(nullptr, weak.promote());
845}
846
Steven Morelandc1635952021-04-01 16:20:47 +0000847TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000848 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000849
850 sp<IBinder> outBinder;
851 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
852 EXPECT_EQ(nullptr, outBinder);
853}
854
Steven Morelandc1635952021-04-01 16:20:47 +0000855TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000856 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000857
858 IBinder* ptr = nullptr;
859 {
860 sp<IBinder> binder = new BBinder();
861 ptr = binder.get();
862 EXPECT_OK(proc.rootIface->holdBinder(binder));
863 }
864
865 sp<IBinder> held;
866 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
867
868 EXPECT_EQ(held.get(), ptr);
869
870 // stop holding binder, because we test to make sure references are cleaned
871 // up
872 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
873 // and flush ref counts
874 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
875}
876
877// START TESTS FOR LIMITATIONS OF SOCKET BINDER
878// These are behavioral differences form regular binder, where certain usecases
879// aren't supported.
880
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000881TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000882 auto proc1 = createRpcTestSocketServerProcess({});
883 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000884
885 sp<IBinder> outBinder;
886 EXPECT_EQ(INVALID_OPERATION,
887 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
888}
889
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000890TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000891 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000892
893 sp<IBinder> outBinder;
894 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000895 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000896 .transactionError());
897}
898
Steven Morelandc1635952021-04-01 16:20:47 +0000899TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000900 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000901
902 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
903 sp<IBinder> outBinder;
904 EXPECT_EQ(INVALID_OPERATION,
905 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
906}
907
Steven Morelandc1635952021-04-01 16:20:47 +0000908TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000909 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000910
911 // for historical reasons, IServiceManager interface only returns the
912 // exception code
913 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
914 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
915}
916
917// END TESTS FOR LIMITATIONS OF SOCKET BINDER
918
Steven Morelandc1635952021-04-01 16:20:47 +0000919TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000920 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000921
922 sp<IBinder> outBinder;
923 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
924 EXPECT_EQ(proc.rootBinder, outBinder);
925}
926
Steven Morelandc1635952021-04-01 16:20:47 +0000927TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000928 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000929
930 auto nastyNester = sp<MyBinderRpcTest>::make();
931 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
932
933 wp<IBinder> weak = nastyNester;
934 nastyNester = nullptr;
935 EXPECT_EQ(nullptr, weak.promote());
936}
937
Steven Morelandc1635952021-04-01 16:20:47 +0000938TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000939 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000940
941 sp<IBinder> a;
942 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
943
944 sp<IBinder> b;
945 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
946
947 EXPECT_EQ(a, b);
948}
949
Steven Morelandc1635952021-04-01 16:20:47 +0000950TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000951 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000952
953 sp<IBinder> a;
954 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
955 wp<IBinder> weak = a;
956 a = nullptr;
957
958 sp<IBinder> b;
959 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
960
961 // this is the wrong behavior, since BpBinder
962 // doesn't implement onIncStrongAttempted
963 // but make sure there is no crash
964 EXPECT_EQ(nullptr, weak.promote());
965
966 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
967
968 // In order to fix this:
969 // - need to have incStrongAttempted reflected across IPC boundary (wait for
970 // response to promote - round trip...)
971 // - sendOnLastWeakRef, to delete entries out of RpcState table
972 EXPECT_EQ(b, weak.promote());
973}
974
975#define expectSessions(expected, iface) \
976 do { \
977 int session; \
978 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
979 EXPECT_EQ(expected, session); \
980 } while (false)
981
Steven Morelandc1635952021-04-01 16:20:47 +0000982TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000983 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000984
985 sp<IBinderRpcSession> session;
986 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
987 std::string out;
988 EXPECT_OK(session->getName(&out));
989 EXPECT_EQ("aoeu", out);
990
991 expectSessions(1, proc.rootIface);
992 session = nullptr;
993 expectSessions(0, proc.rootIface);
994}
995
Steven Morelandc1635952021-04-01 16:20:47 +0000996TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000997 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000998
999 std::vector<sp<IBinderRpcSession>> sessions;
1000
1001 for (size_t i = 0; i < 15; i++) {
1002 expectSessions(i, proc.rootIface);
1003 sp<IBinderRpcSession> session;
1004 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
1005 sessions.push_back(session);
1006 }
1007 expectSessions(sessions.size(), proc.rootIface);
1008 for (size_t i = 0; i < sessions.size(); i++) {
1009 std::string out;
1010 EXPECT_OK(sessions.at(i)->getName(&out));
1011 EXPECT_EQ(std::to_string(i), out);
1012 }
1013 expectSessions(sessions.size(), proc.rootIface);
1014
1015 while (!sessions.empty()) {
1016 sessions.pop_back();
1017 expectSessions(sessions.size(), proc.rootIface);
1018 }
1019 expectSessions(0, proc.rootIface);
1020}
1021
1022size_t epochMillis() {
1023 using std::chrono::duration_cast;
1024 using std::chrono::milliseconds;
1025 using std::chrono::seconds;
1026 using std::chrono::system_clock;
1027 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1028}
1029
Steven Morelandc1635952021-04-01 16:20:47 +00001030TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001031 constexpr size_t kNumThreads = 10;
1032
Steven Moreland4313d7e2021-07-15 23:41:22 +00001033 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001034
1035 EXPECT_OK(proc.rootIface->lock());
1036
1037 // block all but one thread taking locks
1038 std::vector<std::thread> ts;
1039 for (size_t i = 0; i < kNumThreads - 1; i++) {
1040 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
1041 }
1042
1043 usleep(100000); // give chance for calls on other threads
1044
1045 // other calls still work
1046 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1047
1048 constexpr size_t blockTimeMs = 500;
1049 size_t epochMsBefore = epochMillis();
1050 // after this, we should never see a response within this time
1051 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
1052
1053 // this call should be blocked for blockTimeMs
1054 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1055
1056 size_t epochMsAfter = epochMillis();
1057 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
1058
1059 for (auto& t : ts) t.join();
1060}
1061
Yifan Hong1f44f982021-10-08 17:16:47 -07001062void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
1063 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001064 size_t epochMsBefore = epochMillis();
1065
1066 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -07001067 for (size_t i = 0; i < numCalls; i++) {
1068 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +00001069 }
1070
1071 for (auto& t : ts) t.join();
1072
1073 size_t epochMsAfter = epochMillis();
1074
Yifan Hong1f44f982021-10-08 17:16:47 -07001075 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +00001076
1077 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -07001078 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
1079}
1080
1081TEST_P(BinderRpc, ThreadPoolOverSaturated) {
1082 constexpr size_t kNumThreads = 10;
1083 constexpr size_t kNumCalls = kNumThreads + 3;
1084 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1085 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
1086}
1087
1088TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
1089 constexpr size_t kNumThreads = 20;
1090 constexpr size_t kNumOutgoingConnections = 10;
1091 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
1092 auto proc = createRpcTestSocketServerProcess(
1093 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
1094 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +00001095}
1096
Steven Morelandc1635952021-04-01 16:20:47 +00001097TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001098 constexpr size_t kNumClientThreads = 10;
1099 constexpr size_t kNumServerThreads = 10;
1100 constexpr size_t kNumCalls = 100;
1101
Steven Moreland4313d7e2021-07-15 23:41:22 +00001102 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001103
1104 std::vector<std::thread> threads;
1105 for (size_t i = 0; i < kNumClientThreads; i++) {
1106 threads.push_back(std::thread([&] {
1107 for (size_t j = 0; j < kNumCalls; j++) {
1108 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001109 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001110 EXPECT_EQ(proc.rootBinder, out);
1111 }
1112 }));
1113 }
1114
1115 for (auto& t : threads) t.join();
1116}
1117
Steven Moreland925ba0a2021-09-17 18:06:32 -07001118static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
1119 std::vector<std::thread> threads;
1120 for (size_t i = 0; i < threadCount; i++) {
1121 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
1122 }
1123 for (auto& t : threads) t.join();
1124}
1125
Steven Morelandc6046982021-04-20 00:49:42 +00001126TEST_P(BinderRpc, OnewayStressTest) {
1127 constexpr size_t kNumClientThreads = 10;
1128 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -07001129 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +00001130
Steven Moreland4313d7e2021-07-15 23:41:22 +00001131 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001132
1133 std::vector<std::thread> threads;
1134 for (size_t i = 0; i < kNumClientThreads; i++) {
1135 threads.push_back(std::thread([&] {
1136 for (size_t j = 0; j < kNumCalls; j++) {
1137 EXPECT_OK(proc.rootIface->sendString("a"));
1138 }
Steven Morelandc6046982021-04-20 00:49:42 +00001139 }));
1140 }
1141
1142 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -07001143
1144 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +00001145}
1146
Steven Morelandc1635952021-04-01 16:20:47 +00001147TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001148 constexpr size_t kReallyLongTimeMs = 100;
1149 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1150
Steven Moreland4313d7e2021-07-15 23:41:22 +00001151 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001152
1153 size_t epochMsBefore = epochMillis();
1154
1155 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1156
1157 size_t epochMsAfter = epochMillis();
1158 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1159}
1160
Steven Morelandc1635952021-04-01 16:20:47 +00001161TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001162 constexpr size_t kNumSleeps = 10;
1163 constexpr size_t kNumExtraServerThreads = 4;
1164 constexpr size_t kSleepMs = 50;
1165
1166 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001167 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001168
1169 EXPECT_OK(proc.rootIface->lock());
1170
Steven Moreland1c678802021-09-17 16:48:47 -07001171 size_t epochMsBefore = epochMillis();
1172
1173 // all these *Async commands should be queued on the server sequentially,
1174 // even though there are multiple threads.
1175 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001176 proc.rootIface->sleepMsAsync(kSleepMs);
1177 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001178 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1179
Steven Moreland1c678802021-09-17 16:48:47 -07001180 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +00001181 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -07001182
Steven Moreland5553ac42020-11-11 02:14:45 +00001183 size_t epochMsAfter = epochMillis();
1184
1185 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001186
Steven Moreland925ba0a2021-09-17 18:06:32 -07001187 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001188}
1189
Steven Morelandd45be622021-06-04 02:19:37 +00001190TEST_P(BinderRpc, OnewayCallExhaustion) {
1191 constexpr size_t kNumClients = 2;
1192 constexpr size_t kTooLongMs = 1000;
1193
Steven Moreland4313d7e2021-07-15 23:41:22 +00001194 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001195
1196 // Build up oneway calls on the second session to make sure it terminates
1197 // and shuts down. The first session should be unaffected (proc destructor
1198 // checks the first session).
1199 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1200
1201 std::vector<std::thread> threads;
1202 for (size_t i = 0; i < kNumClients; i++) {
1203 // one of these threads will get stuck queueing a transaction once the
1204 // socket fills up, the other will be able to fill up transactions on
1205 // this object
1206 threads.push_back(std::thread([&] {
1207 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1208 }
1209 }));
1210 }
1211 for (auto& t : threads) t.join();
1212
1213 Status status = iface->sleepMsAsync(kTooLongMs);
1214 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1215
Steven Moreland798e0d12021-07-14 23:19:25 +00001216 // now that it has died, wait for the remote session to shutdown
1217 std::vector<int32_t> remoteCounts;
1218 do {
1219 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1220 } while (remoteCounts.size() == kNumClients);
1221
Steven Morelandd45be622021-06-04 02:19:37 +00001222 // the second session should be shutdown in the other process by the time we
1223 // are able to join above (it'll only be hung up once it finishes processing
1224 // any pending commands). We need to erase this session from the record
1225 // here, so that the destructor for our session won't check that this
1226 // session is valid, but we still want it to test the other session.
1227 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1228}
1229
Steven Moreland659416d2021-05-11 00:47:50 +00001230TEST_P(BinderRpc, Callbacks) {
1231 const static std::string kTestString = "good afternoon!";
1232
Steven Morelandc7d40132021-06-10 03:42:11 +00001233 for (bool callIsOneway : {true, false}) {
1234 for (bool callbackIsOneway : {true, false}) {
1235 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001236 auto proc = createRpcTestSocketServerProcess(
1237 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001238 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001239
Steven Morelandc7d40132021-06-10 03:42:11 +00001240 if (callIsOneway) {
1241 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1242 kTestString));
1243 } else {
1244 EXPECT_OK(
1245 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1246 }
Steven Moreland659416d2021-05-11 00:47:50 +00001247
Steven Morelandc7d40132021-06-10 03:42:11 +00001248 using std::literals::chrono_literals::operator""s;
1249 std::unique_lock<std::mutex> _l(cb->mMutex);
1250 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001251
Steven Morelandc7d40132021-06-10 03:42:11 +00001252 EXPECT_EQ(cb->mValues.size(), 1)
1253 << "callIsOneway: " << callIsOneway
1254 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1255 if (cb->mValues.empty()) continue;
1256 EXPECT_EQ(cb->mValues.at(0), kTestString)
1257 << "callIsOneway: " << callIsOneway
1258 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001259
Steven Morelandc7d40132021-06-10 03:42:11 +00001260 // since we are severing the connection, we need to go ahead and
1261 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001262 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1263 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1264 }
Steven Moreland659416d2021-05-11 00:47:50 +00001265
Steven Moreland1b304292021-07-15 22:59:34 +00001266 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001267 // need to manually shut it down
1268 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001269
Steven Morelandc7d40132021-06-10 03:42:11 +00001270 proc.expectAlreadyShutdown = true;
1271 }
Steven Moreland659416d2021-05-11 00:47:50 +00001272 }
1273 }
1274}
1275
Steven Moreland195edb82021-06-08 02:44:39 +00001276TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001277 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001278 auto cb = sp<MyBinderRpcCallback>::make();
1279
1280 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1281 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1282}
1283
Steven Morelandc1635952021-04-01 16:20:47 +00001284TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001285 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001286 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001287
1288 // make sure there is some state during crash
1289 // 1. we hold their binder
1290 sp<IBinderRpcSession> session;
1291 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1292 // 2. they hold our binder
1293 sp<IBinder> binder = new BBinder();
1294 EXPECT_OK(proc.rootIface->holdBinder(binder));
1295
1296 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1297 << "Do death cleanup: " << doDeathCleanup;
1298
Steven Morelandaf4ca712021-05-24 23:22:08 +00001299 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001300 }
1301}
1302
Steven Morelandd7302072021-05-15 01:32:04 +00001303TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001304 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001305
1306 // we can't allocate IPCThreadState so actually the first time should
1307 // succeed :(
1308 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1309
1310 // second time! we catch the error :)
1311 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1312
Steven Morelandaf4ca712021-05-24 23:22:08 +00001313 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001314}
1315
Steven Moreland37aff182021-03-26 02:04:16 +00001316TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001317 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001318
1319 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1320 ASSERT_NE(binder, nullptr);
1321
1322 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1323}
1324
1325TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001326 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001327
1328 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1329 ASSERT_NE(binder, nullptr);
1330
1331 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1332 ASSERT_NE(ndkBinder, nullptr);
1333
1334 std::string out;
1335 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1336 ASSERT_TRUE(status.isOk()) << status.getDescription();
1337 ASSERT_EQ("aoeuaoeu", out);
1338}
1339
Steven Moreland5553ac42020-11-11 02:14:45 +00001340ssize_t countFds() {
1341 DIR* dir = opendir("/proc/self/fd/");
1342 if (dir == nullptr) return -1;
1343 ssize_t ret = 0;
1344 dirent* ent;
1345 while ((ent = readdir(dir)) != nullptr) ret++;
1346 closedir(dir);
1347 return ret;
1348}
1349
Steven Morelandc1635952021-04-01 16:20:47 +00001350TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001351 ssize_t beforeFds = countFds();
1352 ASSERT_GE(beforeFds, 0);
1353 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001354 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001355 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1356 }
1357 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1358}
1359
Devin Moore800b2252021-10-15 16:22:57 +00001360TEST_P(BinderRpc, AidlDelegatorTest) {
1361 auto proc = createRpcTestSocketServerProcess({});
1362 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1363 ASSERT_NE(nullptr, myDelegator);
1364
1365 std::string doubled;
1366 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1367 EXPECT_EQ("cool cool ", doubled);
1368}
1369
Steven Morelandda573042021-06-12 01:13:45 +00001370static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001371 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001372 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001373 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland1eab3452021-08-05 16:56:20 -07001374 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1375 if (status == -EAFNOSUPPORT) {
1376 return false;
1377 }
1378 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1379 }
Steven Morelandda573042021-06-12 01:13:45 +00001380 server->start();
1381
Yifan Hongfdd9f692021-09-09 15:12:52 -07001382 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001383 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001384 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001385 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1386 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001387}
1388
Yifan Hong1deca4b2021-09-10 16:16:44 -07001389static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1390 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1391
1392 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001393
1394 static bool hasVsockLoopback = testSupportVsockLoopback();
1395
1396 if (hasVsockLoopback) {
1397 ret.push_back(SocketType::VSOCK);
1398 }
1399
1400 return ret;
1401}
1402
Yifan Hong702115c2021-06-24 15:39:18 -07001403INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1404 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1405 ::testing::ValuesIn(RpcSecurityValues())),
1406 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001407
Yifan Hong702115c2021-06-24 15:39:18 -07001408class BinderRpcServerRootObject
1409 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001410
1411TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1412 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1413 auto setRootObject = [](bool isStrong) -> SetFn {
1414 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1415 };
1416
Yifan Hong702115c2021-06-24 15:39:18 -07001417 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1418 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001419 auto binder1 = sp<BBinder>::make();
1420 IBinder* binderRaw1 = binder1.get();
1421 setRootObject(isStrong1)(server.get(), binder1);
1422 EXPECT_EQ(binderRaw1, server->getRootObject());
1423 binder1.clear();
1424 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1425
1426 auto binder2 = sp<BBinder>::make();
1427 IBinder* binderRaw2 = binder2.get();
1428 setRootObject(isStrong2)(server.get(), binder2);
1429 EXPECT_EQ(binderRaw2, server->getRootObject());
1430 binder2.clear();
1431 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1432}
1433
1434INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001435 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1436 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001437
Yifan Hong1a235852021-05-13 16:07:47 -07001438class OneOffSignal {
1439public:
1440 // If notify() was previously called, or is called within |duration|, return true; else false.
1441 template <typename R, typename P>
1442 bool wait(std::chrono::duration<R, P> duration) {
1443 std::unique_lock<std::mutex> lock(mMutex);
1444 return mCv.wait_for(lock, duration, [this] { return mValue; });
1445 }
1446 void notify() {
1447 std::unique_lock<std::mutex> lock(mMutex);
1448 mValue = true;
1449 lock.unlock();
1450 mCv.notify_all();
1451 }
1452
1453private:
1454 std::mutex mMutex;
1455 std::condition_variable mCv;
1456 bool mValue = false;
1457};
1458
Yifan Hong702115c2021-06-24 15:39:18 -07001459TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001460 auto addr = allocateSocketAddress();
Yifan Hong702115c2021-06-24 15:39:18 -07001461 auto server = RpcServer::make(newFactory(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001462 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001463 auto joinEnds = std::make_shared<OneOffSignal>();
1464
1465 // If things are broken and the thread never stops, don't block other tests. Because the thread
1466 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1467 // shared pointers are passed.
1468 std::thread([server, joinEnds] {
1469 server->join();
1470 joinEnds->notify();
1471 }).detach();
1472
1473 bool shutdown = false;
1474 for (int i = 0; i < 10 && !shutdown; i++) {
1475 usleep(300 * 1000); // 300ms; total 3s
1476 if (server->shutdown()) shutdown = true;
1477 }
1478 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1479
1480 ASSERT_TRUE(joinEnds->wait(2s))
1481 << "After server->shutdown() returns true, join() did not stop after 2s";
1482}
1483
Yifan Hong194acf22021-06-29 18:44:56 -07001484TEST(BinderRpc, Java) {
1485#if !defined(__ANDROID__)
1486 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1487 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1488 "to binderHostDeviceTest. Hence, just disable this test on host.";
1489#endif // !__ANDROID__
1490 sp<IServiceManager> sm = defaultServiceManager();
1491 ASSERT_NE(nullptr, sm);
1492 // Any Java service with non-empty getInterfaceDescriptor() would do.
1493 // Let's pick batteryproperties.
1494 auto binder = sm->checkService(String16("batteryproperties"));
1495 ASSERT_NE(nullptr, binder);
1496 auto descriptor = binder->getInterfaceDescriptor();
1497 ASSERT_GE(descriptor.size(), 0);
1498 ASSERT_EQ(OK, binder->pingBinder());
1499
1500 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001501 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001502 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001503 auto socket = rpcServer->releaseServer();
1504
1505 auto keepAlive = sp<BBinder>::make();
1506 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1507
1508 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001509 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001510 auto rpcBinder = rpcSession->getRootObject();
1511 ASSERT_NE(nullptr, rpcBinder);
1512
1513 ASSERT_EQ(OK, rpcBinder->pingBinder());
1514
1515 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1516 << "getInterfaceDescriptor should not crash system_server";
1517 ASSERT_EQ(OK, rpcBinder->pingBinder());
1518}
1519
Yifan Hong702115c2021-06-24 15:39:18 -07001520INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1521 BinderRpcSimple::PrintTestParam);
1522
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001523class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001524public:
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001525 using Param = std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001526 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001527
1528 // A server that handles client socket connections.
1529 class Server {
1530 public:
1531 explicit Server() {}
1532 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001533 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001534 [[nodiscard]] AssertionResult setUp(
1535 const Param& param,
1536 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
1537 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001538 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001539 switch (socketType) {
1540 case SocketType::PRECONNECTED: {
1541 return AssertionFailure() << "Not supported by this test";
1542 } break;
1543 case SocketType::UNIX: {
1544 auto addr = allocateSocketAddress();
1545 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1546 if (status != OK) {
1547 return AssertionFailure()
1548 << "setupUnixDomainServer: " << statusToString(status);
1549 }
1550 mConnectToServer = [addr] {
1551 return connectTo(UnixSocketAddress(addr.c_str()));
1552 };
1553 } break;
1554 case SocketType::VSOCK: {
1555 auto port = allocateVsockPort();
1556 auto status = rpcServer->setupVsockServer(port);
1557 if (status != OK) {
1558 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1559 }
1560 mConnectToServer = [port] {
1561 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1562 };
1563 } break;
1564 case SocketType::INET: {
1565 unsigned int port;
1566 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1567 if (status != OK) {
1568 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1569 }
1570 mConnectToServer = [port] {
1571 const char* addr = kLocalInetAddress;
1572 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1573 if (aiStart == nullptr) return base::unique_fd{};
1574 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1575 auto fd = connectTo(
1576 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1577 if (fd.ok()) return fd;
1578 }
1579 ALOGE("None of the socket address resolved for %s:%u can be connected",
1580 addr, port);
1581 return base::unique_fd{};
1582 };
1583 }
1584 }
1585 mFd = rpcServer->releaseServer();
1586 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001587 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001588 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1589 mSetup = true;
1590 return AssertionSuccess();
1591 }
1592 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1593 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1594 return mCertVerifier;
1595 }
1596 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1597 void start() {
1598 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1599 mThread = std::make_unique<std::thread>(&Server::run, this);
1600 }
1601 void run() {
1602 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1603
1604 std::vector<std::thread> threads;
1605 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1606 base::unique_fd acceptedFd(
1607 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1608 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1609 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1610 }
1611
1612 for (auto& thread : threads) thread.join();
1613 }
1614 void handleOne(android::base::unique_fd acceptedFd) {
1615 ASSERT_TRUE(acceptedFd.ok());
1616 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1617 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001618 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001619 }
Yifan Honge07d2732021-09-13 21:59:14 -07001620 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001621 shutdown();
1622 join();
1623 }
1624 void shutdown() { mFdTrigger->trigger(); }
1625
1626 void setPostConnect(
1627 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1628 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001629 }
1630
1631 private:
1632 std::unique_ptr<std::thread> mThread;
1633 ConnectToServer mConnectToServer;
1634 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1635 base::unique_fd mFd;
1636 std::unique_ptr<RpcTransportCtx> mCtx;
1637 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1638 std::make_shared<RpcCertificateVerifierSimple>();
1639 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001640 // The function invoked after connection and handshake. By default, it is
1641 // |defaultPostConnect| that sends |kMessage| to the client.
1642 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1643 Server::defaultPostConnect;
1644
1645 void join() {
1646 if (mThread != nullptr) {
1647 mThread->join();
1648 mThread = nullptr;
1649 }
1650 }
1651
1652 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1653 FdTrigger* fdTrigger) {
1654 std::string message(kMessage);
1655 auto status = serverTransport->interruptableWriteFully(fdTrigger, message.data(),
Steven Moreland43921d52021-09-27 17:15:56 -07001656 message.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001657 if (status != OK) return AssertionFailure() << statusToString(status);
1658 return AssertionSuccess();
1659 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001660 };
1661
1662 class Client {
1663 public:
1664 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1665 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001666 [[nodiscard]] AssertionResult setUp(const Param& param) {
1667 auto [socketType, rpcSecurity, certificateFormat] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001668 mFdTrigger = FdTrigger::make();
1669 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1670 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1671 return AssertionSuccess();
1672 }
1673 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1674 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1675 return mCertVerifier;
1676 }
Yifan Hong67519322021-09-13 18:51:16 -07001677 // connect() and do handshake
1678 bool setUpTransport() {
1679 mFd = mConnectToServer();
1680 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1681 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1682 return mClientTransport != nullptr;
1683 }
1684 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1685 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1686 std::string readMessage(expectedMessage.size(), '\0');
1687 status_t readStatus =
1688 mClientTransport->interruptableReadFully(mFdTrigger.get(), readMessage.data(),
Steven Moreland43921d52021-09-27 17:15:56 -07001689 readMessage.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001690 if (readStatus != OK) {
1691 return AssertionFailure() << statusToString(readStatus);
1692 }
1693 if (readMessage != expectedMessage) {
1694 return AssertionFailure()
1695 << "Expected " << expectedMessage << ", actual " << readMessage;
1696 }
1697 return AssertionSuccess();
1698 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001699 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07001700 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001701 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1702 return;
1703 }
1704 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07001705 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07001706 }
1707
1708 private:
1709 ConnectToServer mConnectToServer;
1710 base::unique_fd mFd;
1711 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1712 std::unique_ptr<RpcTransportCtx> mCtx;
1713 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1714 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07001715 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001716 };
1717
1718 // Make A trust B.
1719 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001720 static status_t trust(RpcSecurity rpcSecurity,
1721 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
1722 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001723 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07001724 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
1725 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
1726 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001727 }
1728
1729 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001730};
1731
1732class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
1733public:
1734 using Server = RpcTransportTestUtils::Server;
1735 using Client = RpcTransportTestUtils::Client;
1736 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1737 auto [socketType, rpcSecurity, certificateFormat] = info.param;
1738 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
1739 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
1740 return ret;
1741 }
1742 static std::vector<ParamType> getRpcTranportTestParams() {
1743 std::vector<ParamType> ret;
1744 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
1745 for (auto rpcSecurity : RpcSecurityValues()) {
1746 switch (rpcSecurity) {
1747 case RpcSecurity::RAW: {
1748 ret.emplace_back(socketType, rpcSecurity, std::nullopt);
1749 } break;
1750 case RpcSecurity::TLS: {
1751 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM);
1752 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER);
1753 } break;
1754 }
1755 }
1756 }
1757 return ret;
1758 }
1759 template <typename A, typename B>
1760 status_t trust(const A& a, const B& b) {
1761 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1762 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
1763 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001764};
1765
1766TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001767 auto server = std::make_unique<Server>();
1768 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001769
1770 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001771 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001772
1773 ASSERT_EQ(OK, trust(&client, server));
1774 ASSERT_EQ(OK, trust(server, &client));
1775
1776 server->start();
1777 client.run();
1778}
1779
1780TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001781 auto server = std::make_unique<Server>();
1782 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001783
1784 std::vector<Client> clients;
1785 for (int i = 0; i < 2; i++) {
1786 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001787 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001788 ASSERT_EQ(OK, trust(&client, server));
1789 ASSERT_EQ(OK, trust(server, &client));
1790 }
1791
1792 server->start();
1793 for (auto& client : clients) client.run();
1794}
1795
1796TEST_P(RpcTransportTest, UntrustedServer) {
1797 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1798
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001799 auto untrustedServer = std::make_unique<Server>();
1800 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001801
1802 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001803 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001804
1805 ASSERT_EQ(OK, trust(untrustedServer, &client));
1806
1807 untrustedServer->start();
1808
1809 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1810 // the client can't verify the server's identity.
1811 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1812 client.run(handshakeOk);
1813}
1814TEST_P(RpcTransportTest, MaliciousServer) {
1815 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001816 auto validServer = std::make_unique<Server>();
1817 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001818
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001819 auto maliciousServer = std::make_unique<Server>();
1820 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001821
1822 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001823 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001824
1825 ASSERT_EQ(OK, trust(&client, validServer));
1826 ASSERT_EQ(OK, trust(validServer, &client));
1827 ASSERT_EQ(OK, trust(maliciousServer, &client));
1828
1829 maliciousServer->start();
1830
1831 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1832 // the client can't verify the server's identity.
1833 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1834 client.run(handshakeOk);
1835}
1836
1837TEST_P(RpcTransportTest, UntrustedClient) {
1838 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001839 auto server = std::make_unique<Server>();
1840 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001841
1842 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001843 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001844
1845 ASSERT_EQ(OK, trust(&client, server));
1846
1847 server->start();
1848
1849 // For TLS, Client should be able to verify server's identity, so client should see
1850 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1851 // identity and should drop the connection, so client shouldn't be able to read anything.
1852 bool readOk = rpcSecurity != RpcSecurity::TLS;
1853 client.run(true, readOk);
1854}
1855
1856TEST_P(RpcTransportTest, MaliciousClient) {
1857 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001858 auto server = std::make_unique<Server>();
1859 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001860
1861 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001862 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001863 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001864 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001865
1866 ASSERT_EQ(OK, trust(&validClient, server));
1867 ASSERT_EQ(OK, trust(&maliciousClient, server));
1868
1869 server->start();
1870
1871 // See UntrustedClient.
1872 bool readOk = rpcSecurity != RpcSecurity::TLS;
1873 maliciousClient.run(true, readOk);
1874}
1875
Yifan Hong67519322021-09-13 18:51:16 -07001876TEST_P(RpcTransportTest, Trigger) {
1877 std::string msg2 = ", world!";
1878 std::mutex writeMutex;
1879 std::condition_variable writeCv;
1880 bool shouldContinueWriting = false;
1881 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001882 std::string message(RpcTransportTestUtils::kMessage);
Steven Moreland43921d52021-09-27 17:15:56 -07001883 auto status = serverTransport->interruptableWriteFully(fdTrigger, message.data(),
1884 message.size(), {});
Yifan Hong67519322021-09-13 18:51:16 -07001885 if (status != OK) return AssertionFailure() << statusToString(status);
1886
1887 {
1888 std::unique_lock<std::mutex> lock(writeMutex);
1889 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
1890 return AssertionFailure() << "write barrier not cleared in time!";
1891 }
1892 }
1893
Steven Moreland43921d52021-09-27 17:15:56 -07001894 status = serverTransport->interruptableWriteFully(fdTrigger, msg2.data(), msg2.size(), {});
Steven Morelandc591b472021-09-16 13:56:11 -07001895 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07001896 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07001897 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07001898 << statusToString(status);
1899 return AssertionSuccess();
1900 };
1901
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001902 auto server = std::make_unique<Server>();
1903 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001904
1905 // Set up client
1906 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001907 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07001908
1909 // Exchange keys
1910 ASSERT_EQ(OK, trust(&client, server));
1911 ASSERT_EQ(OK, trust(server, &client));
1912
1913 server->setPostConnect(serverPostConnect);
1914
Yifan Hong67519322021-09-13 18:51:16 -07001915 server->start();
1916 // connect() to server and do handshake
1917 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07001918 // read the first message. This ensures that server has finished handshake and start handling
1919 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001920 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07001921 // Trigger server shutdown after server starts handling client FD. This ensures that the second
1922 // write is on an FdTrigger that has been shut down.
1923 server->shutdown();
1924 // Continues server thread to write the second message.
1925 {
Yifan Hong22211f82021-09-14 12:32:25 -07001926 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07001927 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07001928 }
Yifan Hong22211f82021-09-14 12:32:25 -07001929 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07001930 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07001931 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07001932 // On the client side, second read fails with DEAD_OBJECT
1933 ASSERT_FALSE(client.readMessage(msg2));
1934}
1935
Yifan Hong1deca4b2021-09-10 16:16:44 -07001936INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07001937 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07001938 RpcTransportTest::PrintParamInfo);
1939
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001940class RpcTransportTlsKeyTest
1941 : public testing::TestWithParam<std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat>> {
1942public:
1943 template <typename A, typename B>
1944 status_t trust(const A& a, const B& b) {
1945 auto [socketType, certificateFormat, keyFormat] = GetParam();
1946 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
1947 }
1948 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1949 auto [socketType, certificateFormat, keyFormat] = info.param;
1950 auto ret = PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
1951 "_key_" + PrintToString(keyFormat);
1952 return ret;
1953 };
1954};
1955
1956TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
1957 auto [socketType, certificateFormat, keyFormat] = GetParam();
1958
1959 std::vector<uint8_t> pkeyData, certData;
1960 {
1961 auto pkey = makeKeyPairForSelfSignedCert();
1962 ASSERT_NE(nullptr, pkey);
1963 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
1964 ASSERT_NE(nullptr, cert);
1965 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
1966 certData = serializeCertificate(cert.get(), certificateFormat);
1967 }
1968
1969 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
1970 auto desCert = deserializeCertificate(certData, certificateFormat);
1971 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
1972 auto utilsParam =
1973 std::make_tuple(socketType, RpcSecurity::TLS, std::make_optional(certificateFormat));
1974
1975 auto server = std::make_unique<RpcTransportTestUtils::Server>();
1976 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
1977
1978 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
1979 ASSERT_TRUE(client.setUp(utilsParam));
1980
1981 ASSERT_EQ(OK, trust(&client, server));
1982 ASSERT_EQ(OK, trust(server, &client));
1983
1984 server->start();
1985 client.run();
1986}
1987
1988INSTANTIATE_TEST_CASE_P(
1989 BinderRpc, RpcTransportTlsKeyTest,
1990 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
1991 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
1992 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER)),
1993 RpcTransportTlsKeyTest::PrintParamInfo);
1994
Steven Morelandc1635952021-04-01 16:20:47 +00001995} // namespace android
1996
1997int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001998 ::testing::InitGoogleTest(&argc, argv);
1999 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
2000 return RUN_ALL_TESTS();
2001}