blob: d32607b88ab4e6ba7a67a1c3010e54d114d42d6a [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yifan Hong1deca4b2021-09-10 16:16:44 -070017#include <BinderRpcTestClientInfo.h>
18#include <BinderRpcTestServerInfo.h>
Steven Moreland659416d2021-05-11 00:47:50 +000019#include <BnBinderRpcCallback.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000020#include <BnBinderRpcSession.h>
21#include <BnBinderRpcTest.h>
Steven Moreland37aff182021-03-26 02:04:16 +000022#include <aidl/IBinderRpcTest.h>
Yifan Hong6d82c8a2021-04-26 20:26:45 -070023#include <android-base/file.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000024#include <android-base/logging.h>
Yifan Hongfe4b83f2021-11-08 16:29:53 -080025#include <android-base/properties.h>
Frederick Maylea12b0962022-06-25 01:13:22 +000026#include <android-base/stringprintf.h>
Steven Moreland37aff182021-03-26 02:04:16 +000027#include <android/binder_auto_utils.h>
28#include <android/binder_libbinder.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000029#include <binder/Binder.h>
30#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000031#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000032#include <binder/IServiceManager.h>
33#include <binder/ProcessState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000034#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000035#include <binder/RpcSession.h>
Andrei Homescu12106de2022-04-27 04:42:21 +000036#include <binder/RpcThreads.h>
Yifan Honge0e53282021-09-23 18:37:21 -070037#include <binder/RpcTlsTestUtils.h>
Yifan Hongb1ce80c2021-09-17 22:10:58 -070038#include <binder/RpcTlsUtils.h>
Yifan Hong702115c2021-06-24 15:39:18 -070039#include <binder/RpcTransport.h>
40#include <binder/RpcTransportRaw.h>
Yifan Hong92409752021-07-30 21:25:32 -070041#include <binder/RpcTransportTls.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000042#include <gtest/gtest.h>
43
Steven Morelandc1635952021-04-01 16:20:47 +000044#include <chrono>
45#include <cstdlib>
46#include <iostream>
47#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000048#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000049
Yifan Hong1deca4b2021-09-10 16:16:44 -070050#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000051#include <sys/prctl.h>
Andrei Homescu992a4052022-06-28 21:26:18 +000052#include <sys/socket.h>
Steven Morelandc1635952021-04-01 16:20:47 +000053#include <unistd.h>
54
Andrei Homescu12106de2022-04-27 04:42:21 +000055#include "../BuildFlags.h"
Yifan Hong1deca4b2021-09-10 16:16:44 -070056#include "../FdTrigger.h"
Steven Moreland4198a122021-08-03 17:37:58 -070057#include "../RpcSocketAddress.h" // for testing preconnected clients
Yifan Hongffdaf952021-09-17 18:08:38 -070058#include "../RpcState.h" // for debugging
59#include "../vm_sockets.h" // for VMADDR_*
Frederick Mayle69a0c992022-05-26 20:38:39 +000060#include "utils/Errors.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000061
Yifan Hong1a235852021-05-13 16:07:47 -070062using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070063using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070064using testing::AssertionFailure;
65using testing::AssertionResult;
66using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070067
Steven Moreland5553ac42020-11-11 02:14:45 +000068namespace android {
69
Andrei Homescu12106de2022-04-27 04:42:21 +000070#ifdef BINDER_TEST_NO_SHARED_LIBS
71constexpr bool kEnableSharedLibs = false;
72#else
73constexpr bool kEnableSharedLibs = true;
74#endif
75
Steven Morelandbf57bce2021-07-26 15:26:12 -070076static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
77 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Devin Mooref3b9c4f2021-08-03 15:50:13 +000078const char* kLocalInetAddress = "127.0.0.1";
Steven Morelandbf57bce2021-07-26 15:26:12 -070079
Yifan Hong92409752021-07-30 21:25:32 -070080enum class RpcSecurity { RAW, TLS };
Yifan Hong702115c2021-06-24 15:39:18 -070081
82static inline std::vector<RpcSecurity> RpcSecurityValues() {
Yifan Hong92409752021-07-30 21:25:32 -070083 return {RpcSecurity::RAW, RpcSecurity::TLS};
Yifan Hong702115c2021-06-24 15:39:18 -070084}
85
Yifan Hong13c90062021-09-09 14:59:53 -070086static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(
Yifan Hongffdaf952021-09-17 18:08:38 -070087 RpcSecurity rpcSecurity, std::shared_ptr<RpcCertificateVerifier> verifier = nullptr,
88 std::unique_ptr<RpcAuth> auth = nullptr) {
Yifan Hong702115c2021-06-24 15:39:18 -070089 switch (rpcSecurity) {
90 case RpcSecurity::RAW:
91 return RpcTransportCtxFactoryRaw::make();
Yifan Hong13c90062021-09-09 14:59:53 -070092 case RpcSecurity::TLS: {
Yifan Hong13c90062021-09-09 14:59:53 -070093 if (verifier == nullptr) {
94 verifier = std::make_shared<RpcCertificateVerifierSimple>();
95 }
Yifan Hongffdaf952021-09-17 18:08:38 -070096 if (auth == nullptr) {
97 auth = std::make_unique<RpcAuthSelfSigned>();
98 }
99 return RpcTransportCtxFactoryTls::make(std::move(verifier), std::move(auth));
Yifan Hong13c90062021-09-09 14:59:53 -0700100 }
Yifan Hong702115c2021-06-24 15:39:18 -0700101 default:
102 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
103 }
104}
105
Frederick Mayle69a0c992022-05-26 20:38:39 +0000106// Create an FD that returns `contents` when read.
107static base::unique_fd mockFileDescriptor(std::string contents) {
108 android::base::unique_fd readFd, writeFd;
109 CHECK(android::base::Pipe(&readFd, &writeFd)) << strerror(errno);
Andrei Homescu12106de2022-04-27 04:42:21 +0000110 RpcMaybeThread([writeFd = std::move(writeFd), contents = std::move(contents)]() {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000111 signal(SIGPIPE, SIG_IGN); // ignore possible SIGPIPE from the write
112 if (!WriteStringToFd(contents, writeFd)) {
113 int savedErrno = errno;
114 EXPECT_EQ(EPIPE, savedErrno)
115 << "mockFileDescriptor write failed: " << strerror(savedErrno);
116 }
117 }).detach();
118 return readFd;
119}
120
Steven Moreland1fda67b2021-04-02 18:35:50 +0000121TEST(BinderRpcParcel, EntireParcelFormatted) {
122 Parcel p;
123 p.writeInt32(3);
124
125 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
126}
127
Frederick Mayledc07cf82022-05-26 20:30:12 +0000128class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
Yifan Hong702115c2021-06-24 15:39:18 -0700129public:
130 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000131 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
132 std::to_string(std::get<1>(info.param));
Yifan Hong702115c2021-06-24 15:39:18 -0700133 }
134};
135
Frederick Mayledc07cf82022-05-26 20:30:12 +0000136TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700137 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
138 int sinkFd = sink.get();
Frederick Mayledc07cf82022-05-26 20:30:12 +0000139 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
140 server->setProtocolVersion(std::get<1>(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -0700141 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700142 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -0700143 ASSERT_TRUE(server->hasServer());
144 base::unique_fd retrieved = server->releaseServer();
145 ASSERT_FALSE(server->hasServer());
146 ASSERT_EQ(sinkFd, retrieved.get());
147}
148
Steven Morelandbf57bce2021-07-26 15:26:12 -0700149TEST(BinderRpc, CannotUseNextWireVersion) {
150 auto session = RpcSession::make();
151 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
152 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
153 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
154 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
155}
156
157TEST(BinderRpc, CanUseExperimentalWireVersion) {
158 auto session = RpcSession::make();
159 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
160}
161
Steven Moreland5553ac42020-11-11 02:14:45 +0000162using android::binder::Status;
163
164#define EXPECT_OK(status) \
165 do { \
166 Status stat = (status); \
167 EXPECT_TRUE(stat.isOk()) << stat; \
168 } while (false)
169
170class MyBinderRpcSession : public BnBinderRpcSession {
171public:
172 static std::atomic<int32_t> gNum;
173
174 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
175 Status getName(std::string* name) override {
176 *name = mName;
177 return Status::ok();
178 }
179 ~MyBinderRpcSession() { gNum--; }
180
181private:
182 std::string mName;
183};
184std::atomic<int32_t> MyBinderRpcSession::gNum;
185
Steven Moreland659416d2021-05-11 00:47:50 +0000186class MyBinderRpcCallback : public BnBinderRpcCallback {
187 Status sendCallback(const std::string& value) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000188 RpcMutexUniqueLock _l(mMutex);
Steven Moreland659416d2021-05-11 00:47:50 +0000189 mValues.push_back(value);
190 _l.unlock();
191 mCv.notify_one();
192 return Status::ok();
193 }
194 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
195
196public:
Andrei Homescu12106de2022-04-27 04:42:21 +0000197 RpcMutex mMutex;
198 RpcConditionVariable mCv;
Steven Moreland659416d2021-05-11 00:47:50 +0000199 std::vector<std::string> mValues;
200};
201
Steven Moreland5553ac42020-11-11 02:14:45 +0000202class MyBinderRpcTest : public BnBinderRpcTest {
203public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000204 wp<RpcServer> server;
Steven Moreland51c44a92021-10-14 16:50:35 -0700205 int port = 0;
Steven Moreland5553ac42020-11-11 02:14:45 +0000206
207 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000208 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000209 return Status::ok();
210 }
211 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000212 *strstr = str + str;
213 return Status::ok();
214 }
Steven Moreland51c44a92021-10-14 16:50:35 -0700215 Status getClientPort(int* out) override {
216 *out = port;
217 return Status::ok();
218 }
Steven Moreland736664b2021-05-01 04:27:25 +0000219 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000220 sp<RpcServer> spServer = server.promote();
221 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000222 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
223 }
Steven Moreland736664b2021-05-01 04:27:25 +0000224 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000225 for (auto session : spServer->listSessions()) {
226 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000227 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000228 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000229 return Status::ok();
230 }
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000231 Status getNullBinder(sp<IBinder>* out) override {
232 out->clear();
233 return Status::ok();
234 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000235 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
236 if (binder == nullptr) {
237 std::cout << "Received null binder!" << std::endl;
238 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
239 }
240 *out = binder->pingBinder();
241 return Status::ok();
242 }
243 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
244 *out = binder;
245 return Status::ok();
246 }
247 static sp<IBinder> mHeldBinder;
248 Status holdBinder(const sp<IBinder>& binder) override {
249 mHeldBinder = binder;
250 return Status::ok();
251 }
252 Status getHeldBinder(sp<IBinder>* held) override {
253 *held = mHeldBinder;
254 return Status::ok();
255 }
256 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
257 if (count <= 0) return Status::ok();
258 return binder->nestMe(this, count - 1);
259 }
260 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
261 static sp<IBinder> binder = new BBinder;
262 *out = binder;
263 return Status::ok();
264 }
265 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
266 *out = new MyBinderRpcSession(name);
267 return Status::ok();
268 }
269 Status getNumOpenSessions(int32_t* out) override {
270 *out = MyBinderRpcSession::gNum;
271 return Status::ok();
272 }
273
Andrei Homescu12106de2022-04-27 04:42:21 +0000274 RpcMutex blockMutex;
Steven Moreland5553ac42020-11-11 02:14:45 +0000275 Status lock() override {
276 blockMutex.lock();
277 return Status::ok();
278 }
279 Status unlockInMsAsync(int32_t ms) override {
280 usleep(ms * 1000);
281 blockMutex.unlock();
282 return Status::ok();
283 }
284 Status lockUnlock() override {
Andrei Homescu12106de2022-04-27 04:42:21 +0000285 RpcMutexLockGuard _l(blockMutex);
Steven Moreland5553ac42020-11-11 02:14:45 +0000286 return Status::ok();
287 }
288
289 Status sleepMs(int32_t ms) override {
290 usleep(ms * 1000);
291 return Status::ok();
292 }
293
294 Status sleepMsAsync(int32_t ms) override {
295 // In-process binder calls are asynchronous, but the call to this method
296 // is synchronous wrt its client. This in/out-process threading model
297 // diffentiation is a classic binder leaky abstraction (for better or
298 // worse) and is preserved here the way binder sockets plugs itself
299 // into BpBinder, as nothing is changed at the higher levels
300 // (IInterface) which result in this behavior.
301 return sleepMs(ms);
302 }
303
Steven Moreland659416d2021-05-11 00:47:50 +0000304 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
305 const std::string& value) override {
306 if (callback == nullptr) {
307 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
308 }
309
310 if (delayed) {
Andrei Homescu12106de2022-04-27 04:42:21 +0000311 RpcMaybeThread([=]() {
Steven Moreland659416d2021-05-11 00:47:50 +0000312 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000313 Status status = doCallback(callback, oneway, false, value);
314 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000315 }).detach();
316 return Status::ok();
317 }
318
319 if (oneway) {
320 return callback->sendOnewayCallback(value);
321 }
322
323 return callback->sendCallback(value);
324 }
325
Steven Morelandc7d40132021-06-10 03:42:11 +0000326 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
327 const std::string& value) override {
328 return doCallback(callback, oneway, delayed, value);
329 }
330
Steven Moreland5553ac42020-11-11 02:14:45 +0000331 Status die(bool cleanup) override {
332 if (cleanup) {
333 exit(1);
334 } else {
335 _exit(1);
336 }
337 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000338
339 Status scheduleShutdown() override {
340 sp<RpcServer> strongServer = server.promote();
341 if (strongServer == nullptr) {
342 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
343 }
Andrei Homescu12106de2022-04-27 04:42:21 +0000344 RpcMaybeThread([=] {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000345 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
346 }).detach();
347 return Status::ok();
348 }
349
Steven Morelandd7302072021-05-15 01:32:04 +0000350 Status useKernelBinderCallingId() override {
351 // this is WRONG! It does not make sense when using RPC binder, and
352 // because it is SO wrong, and so much code calls this, it should abort!
353
Andrei Homescu12106de2022-04-27 04:42:21 +0000354 if constexpr (kEnableKernelIpc) {
355 (void)IPCThreadState::self()->getCallingPid();
356 }
Steven Morelandd7302072021-05-15 01:32:04 +0000357 return Status::ok();
358 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000359
360 Status echoAsFile(const std::string& content, android::os::ParcelFileDescriptor* out) override {
361 out->reset(mockFileDescriptor(content));
362 return Status::ok();
363 }
364
365 Status concatFiles(const std::vector<android::os::ParcelFileDescriptor>& files,
366 android::os::ParcelFileDescriptor* out) override {
367 std::string acc;
368 for (const auto& file : files) {
369 std::string result;
370 CHECK(android::base::ReadFdToString(file.get(), &result));
371 acc.append(result);
372 }
373 out->reset(mockFileDescriptor(acc));
374 return Status::ok();
375 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000376};
377sp<IBinder> MyBinderRpcTest::mHeldBinder;
378
Frederick Maylea12b0962022-06-25 01:13:22 +0000379static std::string WaitStatusToString(int wstatus) {
380 if (WIFEXITED(wstatus)) {
381 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
382 }
383 if (WIFSIGNALED(wstatus)) {
384 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
385 }
386 return base::StringPrintf("unexpected state %d", wstatus);
387}
388
Steven Moreland5553ac42020-11-11 02:14:45 +0000389class Process {
390public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700391 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700392 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
393 android::base::borrowed_fd /* readEnd */)>& f) {
394 android::base::unique_fd childWriteEnd;
395 android::base::unique_fd childReadEnd;
396 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
397 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000398 if (0 == (mPid = fork())) {
399 // racey: assume parent doesn't crash before this is set
400 prctl(PR_SET_PDEATHSIG, SIGHUP);
401
Yifan Hong1deca4b2021-09-10 16:16:44 -0700402 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000403
404 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000405 }
406 }
407 ~Process() {
408 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000409 int wstatus;
410 waitpid(mPid, &wstatus, 0);
411 if (mCustomExitStatusCheck) {
412 mCustomExitStatusCheck(wstatus);
413 } else {
414 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
415 << "server process failed: " << WaitStatusToString(wstatus);
416 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000417 }
418 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700419 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700420 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000421
Frederick Maylea12b0962022-06-25 01:13:22 +0000422 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
423 mCustomExitStatusCheck = std::move(f);
424 }
425
Frederick Mayle69a0c992022-05-26 20:38:39 +0000426 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
427 void terminate() { kill(mPid, SIGTERM); }
428
Steven Moreland5553ac42020-11-11 02:14:45 +0000429private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000430 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000431 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700432 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700433 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000434};
435
436static std::string allocateSocketAddress() {
437 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000438 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700439 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
440 unlink(ret.c_str());
441 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000442};
443
Steven Morelandda573042021-06-12 01:13:45 +0000444static unsigned int allocateVsockPort() {
445 static unsigned int vsockPort = 3456;
446 return vsockPort++;
447}
448
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000449struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000450 // reference to process hosting a socket server
451 Process host;
452
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000453 struct SessionInfo {
454 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000455 sp<IBinder> root;
456 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000457
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000458 // client session objects associated with other process
459 // each one represents a separate session
460 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000461
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000462 ProcessSession(ProcessSession&&) = default;
463 ~ProcessSession() {
464 for (auto& session : sessions) {
465 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000466 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000467
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000468 for (auto& info : sessions) {
469 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000470
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000471 EXPECT_NE(nullptr, session);
472 EXPECT_NE(nullptr, session->state());
473 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000474
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000475 wp<RpcSession> weakSession = session;
476 session = nullptr;
477 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000478 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000479 }
480};
481
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000482// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000483// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000484struct BinderRpcTestProcessSession {
485 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000486
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000487 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000488 sp<IBinder> rootBinder;
489
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000490 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000491 sp<IBinderRpcTest> rootIface;
492
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000493 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000494 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000495
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000496 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
497 ~BinderRpcTestProcessSession() {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000498 if (!expectAlreadyShutdown) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000499 EXPECT_NE(nullptr, rootIface);
500 if (rootIface == nullptr) return;
501
Steven Moreland736664b2021-05-01 04:27:25 +0000502 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000503 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000504 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000505 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000506 for (auto remoteCount : remoteCounts) {
507 EXPECT_EQ(remoteCount, 1);
508 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000509
Steven Moreland798e0d12021-07-14 23:19:25 +0000510 // even though it is on another thread, shutdown races with
511 // the transaction reply being written
512 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
513 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
514 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000515 }
516
517 rootIface = nullptr;
518 rootBinder = nullptr;
519 }
520};
521
Steven Morelandc1635952021-04-01 16:20:47 +0000522enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700523 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000524 UNIX,
525 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700526 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000527};
Yifan Hong702115c2021-06-24 15:39:18 -0700528static inline std::string PrintToString(SocketType socketType) {
529 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700530 case SocketType::PRECONNECTED:
531 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000532 case SocketType::UNIX:
533 return "unix_domain_socket";
534 case SocketType::VSOCK:
535 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700536 case SocketType::INET:
537 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000538 default:
539 LOG_ALWAYS_FATAL("Unknown socket type");
540 return "";
541 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000542}
Steven Morelandda573042021-06-12 01:13:45 +0000543
Yifan Hong1deca4b2021-09-10 16:16:44 -0700544static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700545 base::unique_fd serverFd(
546 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
547 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700548 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
549 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700550
551 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
552 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700553 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
554 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700555 }
556 return serverFd;
557}
558
Frederick Mayledc07cf82022-05-26 20:30:12 +0000559class BinderRpc
560 : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000561public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000562 struct Options {
563 size_t numThreads = 1;
564 size_t numSessions = 1;
565 size_t numIncomingConnections = 0;
Yifan Hong1f44f982021-10-08 17:16:47 -0700566 size_t numOutgoingConnections = SIZE_MAX;
Frederick Mayle69a0c992022-05-26 20:38:39 +0000567 RpcSession::FileDescriptorTransportMode clientFileDescriptorTransportMode =
568 RpcSession::FileDescriptorTransportMode::NONE;
569 std::vector<RpcSession::FileDescriptorTransportMode>
570 serverSupportedFileDescriptorTransportModes = {
571 RpcSession::FileDescriptorTransportMode::NONE};
572
573 // If true, connection failures will result in `ProcessSession::sessions` being empty
574 // instead of a fatal error.
575 bool allowConnectFailure = false;
Steven Moreland4313d7e2021-07-15 23:41:22 +0000576 };
577
Frederick Mayle69a0c992022-05-26 20:38:39 +0000578 SocketType socketType() const { return std::get<0>(GetParam()); }
579 RpcSecurity rpcSecurity() const { return std::get<1>(GetParam()); }
580 uint32_t clientVersion() const { return std::get<2>(GetParam()); }
581 uint32_t serverVersion() const { return std::get<3>(GetParam()); }
582
583 // Whether the test params support sending FDs in parcels.
584 bool supportsFdTransport() const {
585 return clientVersion() >= 1 && serverVersion() >= 1 && rpcSecurity() != RpcSecurity::TLS &&
586 (socketType() == SocketType::PRECONNECTED || socketType() == SocketType::UNIX);
587 }
588
Yifan Hong702115c2021-06-24 15:39:18 -0700589 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000590 auto [type, security, clientVersion, serverVersion] = info.param;
591 return PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
592 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Yifan Hong702115c2021-06-24 15:39:18 -0700593 }
594
Yifan Hong1deca4b2021-09-10 16:16:44 -0700595 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
596 uint64_t length = str.length();
597 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
598 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
599 }
600
601 static inline std::string readString(android::base::borrowed_fd fd) {
602 uint64_t length;
603 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
604 std::string ret(length, '\0');
605 CHECK(android::base::ReadFully(fd, ret.data(), length));
606 return ret;
607 }
608
609 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
610 Parcel parcel;
611 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
612 writeString(fd,
613 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
614 }
615
616 template <typename T>
617 static inline T readFromFd(android::base::borrowed_fd fd) {
618 std::string data = readString(fd);
619 Parcel parcel;
620 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
621 T object;
622 CHECK_EQ(OK, object.readFromParcel(&parcel));
623 return object;
624 }
625
Steven Morelandc1635952021-04-01 16:20:47 +0000626 // This creates a new process serving an interface on a certain number of
627 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000628 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000629 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
630 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000631
Yifan Hong702115c2021-06-24 15:39:18 -0700632 SocketType socketType = std::get<0>(GetParam());
633 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000634 uint32_t clientVersion = std::get<2>(GetParam());
635 uint32_t serverVersion = std::get<3>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000636
Steven Morelandda573042021-06-12 01:13:45 +0000637 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000638 std::string addr = allocateSocketAddress();
Steven Morelandc1635952021-04-01 16:20:47 +0000639
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000640 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000641 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700642 android::base::borrowed_fd readEnd) {
643 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
644 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
Steven Morelandc1635952021-04-01 16:20:47 +0000645
Frederick Mayledc07cf82022-05-26 20:30:12 +0000646 server->setProtocolVersion(serverVersion);
Steven Moreland4313d7e2021-07-15 23:41:22 +0000647 server->setMaxThreads(options.numThreads);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000648 server->setSupportedFileDescriptorTransportModes(
649 options.serverSupportedFileDescriptorTransportModes);
Steven Morelandc1635952021-04-01 16:20:47 +0000650
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000651 unsigned int outPort = 0;
652
Steven Morelandc1635952021-04-01 16:20:47 +0000653 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700654 case SocketType::PRECONNECTED:
655 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000656 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700657 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000658 break;
659 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700660 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000661 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700662 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700663 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700664 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700665 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700666 }
Steven Morelandc1635952021-04-01 16:20:47 +0000667 default:
668 LOG_ALWAYS_FATAL("Unknown socket type");
669 }
670
Yifan Hong1deca4b2021-09-10 16:16:44 -0700671 BinderRpcTestServerInfo serverInfo;
672 serverInfo.port = static_cast<int64_t>(outPort);
Yifan Hong9734cfc2021-09-13 16:14:09 -0700673 serverInfo.cert.data = server->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700674 writeToFd(writeEnd, serverInfo);
675 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
676
677 if (rpcSecurity == RpcSecurity::TLS) {
678 for (const auto& clientCert : clientInfo.certs) {
679 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700680 certVerifier
681 ->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
682 clientCert.data));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700683 }
684 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000685
Steven Moreland611d15f2021-05-01 01:28:27 +0000686 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000687
Steven Morelandf137de92021-04-24 01:54:26 +0000688 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000689
690 // Another thread calls shutdown. Wait for it to complete.
691 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000692 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000693 };
694
Yifan Hong1deca4b2021-09-10 16:16:44 -0700695 std::vector<sp<RpcSession>> sessions;
696 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
697 for (size_t i = 0; i < options.numSessions; i++) {
698 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
699 }
700
701 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
702 BinderRpcTestClientInfo clientInfo;
703 for (const auto& session : sessions) {
704 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700705 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700706 }
707 writeToFd(ret.host.writeEnd(), clientInfo);
708
709 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700710 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700711 CHECK_NE(0, serverInfo.port);
712 }
713
714 if (rpcSecurity == RpcSecurity::TLS) {
715 const auto& serverCert = serverInfo.cert.data;
716 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700717 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
718 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700719 }
720
Steven Moreland2372f9d2021-08-05 15:42:01 -0700721 status_t status;
722
Yifan Hong1deca4b2021-09-10 16:16:44 -0700723 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000724 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700725 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700726 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000727 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Moreland659416d2021-05-11 00:47:50 +0000728
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000729 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700730 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700731 status = session->setupPreconnectedClient({}, [=]() {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700732 return connectTo(UnixSocketAddress(addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700733 });
Steven Moreland4198a122021-08-03 17:37:58 -0700734 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000735 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700736 status = session->setupUnixDomainClient(addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000737 break;
738 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700739 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000740 break;
741 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700742 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000743 break;
744 default:
745 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000746 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000747 if (options.allowConnectFailure && status != OK) {
748 ret.sessions.clear();
749 break;
750 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700751 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000752 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000753 }
Steven Morelandc1635952021-04-01 16:20:47 +0000754 return ret;
755 }
756
Steven Moreland4313d7e2021-07-15 23:41:22 +0000757 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000758 BinderRpcTestProcessSession ret{
Steven Moreland51c44a92021-10-14 16:50:35 -0700759 .proc = createRpcTestSocketServerProcess(
760 options,
761 [&](const sp<RpcServer>& server) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000762 server->setPerSessionRootObject([&](const void* addrPtr, size_t len) {
763 // UNIX sockets with abstract addresses return
764 // sizeof(sa_family_t)==2 in addrlen
765 CHECK_GE(len, sizeof(sa_family_t));
766 const sockaddr* addr = reinterpret_cast<const sockaddr*>(addrPtr);
Steven Moreland51c44a92021-10-14 16:50:35 -0700767 sp<MyBinderRpcTest> service = sp<MyBinderRpcTest>::make();
768 switch (addr->sa_family) {
769 case AF_UNIX:
770 // nothing to save
771 break;
772 case AF_VSOCK:
773 CHECK_EQ(len, sizeof(sockaddr_vm));
774 service->port = reinterpret_cast<const sockaddr_vm*>(addr)
775 ->svm_port;
776 break;
777 case AF_INET:
778 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700779 service->port =
780 ntohs(reinterpret_cast<const sockaddr_in*>(addr)
781 ->sin_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700782 break;
783 case AF_INET6:
784 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700785 service->port =
786 ntohs(reinterpret_cast<const sockaddr_in6*>(addr)
787 ->sin6_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700788 break;
789 default:
790 LOG_ALWAYS_FATAL("Unrecognized address family %d",
791 addr->sa_family);
792 }
793 service->server = server;
794 return service;
795 });
796 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000797 };
798
Frederick Mayle69a0c992022-05-26 20:38:39 +0000799 ret.rootBinder = ret.proc.sessions.empty() ? nullptr : ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000800 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
801
802 return ret;
803 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700804
805 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
806 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000807};
808
Andrei Homescu12106de2022-04-27 04:42:21 +0000809// Test fixture for tests that start multiple threads.
810// This includes tests with one thread but multiple sessions,
811// since a server uses one thread per session.
812class BinderRpcThreads : public BinderRpc {
813public:
814 void SetUp() override {
815 if constexpr (!kEnableRpcThreads) {
816 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
817 }
818 }
819};
820
Steven Morelandc1635952021-04-01 16:20:47 +0000821TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000822 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000823 ASSERT_NE(proc.rootBinder, nullptr);
824 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
825}
826
Steven Moreland4cf688f2021-03-31 01:48:58 +0000827TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000828 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000829 ASSERT_NE(proc.rootBinder, nullptr);
830 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
831}
832
Andrei Homescu12106de2022-04-27 04:42:21 +0000833TEST_P(BinderRpcThreads, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000834 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000835 for (auto session : proc.proc.sessions) {
836 ASSERT_NE(nullptr, session.root);
837 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000838 }
839}
840
Andrei Homescu12106de2022-04-27 04:42:21 +0000841TEST_P(BinderRpcThreads, SeparateRootObject) {
Steven Moreland51c44a92021-10-14 16:50:35 -0700842 SocketType type = std::get<0>(GetParam());
843 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
844 // we can't get port numbers for unix sockets
845 return;
846 }
847
848 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
849
850 int port1 = 0;
851 EXPECT_OK(proc.rootIface->getClientPort(&port1));
852
853 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
854 int port2;
855 EXPECT_OK(rootIface2->getClientPort(&port2));
856
857 // we should have a different IBinderRpcTest object created for each
858 // session, because we use setPerSessionRootObject
859 EXPECT_NE(port1, port2);
860}
861
Steven Morelandc1635952021-04-01 16:20:47 +0000862TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000863 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000864 Parcel data;
865 Parcel reply;
866 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
867}
868
Steven Moreland67753c32021-04-02 18:45:19 +0000869TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700870 auto proc1 = createRpcTestSocketServerProcess({});
871 auto proc2 = createRpcTestSocketServerProcess({});
872
873 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000874
875 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700876 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000877 p1.writeInt32(3);
878
Frederick Maylea4ed5672022-06-17 22:03:38 +0000879 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700880 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
881
Steven Moreland67753c32021-04-02 18:45:19 +0000882 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700883 p2.markForBinder(proc2.rootBinder);
884 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000885
886 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
887 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
888}
889
Steven Morelandc1635952021-04-01 16:20:47 +0000890TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000891 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000892 Parcel data;
893 data.markForBinder(proc.rootBinder);
894 Parcel reply;
895 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
896}
897
Steven Morelandc1635952021-04-01 16:20:47 +0000898TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000899 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000900 EXPECT_OK(proc.rootIface->sendString("asdf"));
901}
902
Steven Morelandc1635952021-04-01 16:20:47 +0000903TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000904 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000905 std::string doubled;
906 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
907 EXPECT_EQ("cool cool ", doubled);
908}
909
Steven Morelandc1635952021-04-01 16:20:47 +0000910TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000911 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000912 std::string single = std::string(1024, 'a');
913 std::string doubled;
914 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
915 EXPECT_EQ(single + single, doubled);
916}
917
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000918TEST_P(BinderRpc, InvalidNullBinderReturn) {
919 auto proc = createRpcTestSocketServerProcess({});
920
921 sp<IBinder> outBinder;
922 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
923}
924
Steven Morelandc1635952021-04-01 16:20:47 +0000925TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000926 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000927
928 int32_t pingResult;
929 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
930 EXPECT_EQ(OK, pingResult);
931
932 EXPECT_EQ(0, MyBinderRpcSession::gNum);
933}
934
Steven Morelandc1635952021-04-01 16:20:47 +0000935TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000936 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000937
938 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
939 sp<IBinder> outBinder;
940 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
941 EXPECT_EQ(inBinder, outBinder);
942
943 wp<IBinder> weak = inBinder;
944 inBinder = nullptr;
945 outBinder = nullptr;
946
947 // Force reading a reply, to process any pending dec refs from the other
948 // process (the other process will process dec refs there before processing
949 // the ping here).
950 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
951
952 EXPECT_EQ(nullptr, weak.promote());
953
954 EXPECT_EQ(0, MyBinderRpcSession::gNum);
955}
956
Steven Morelandc1635952021-04-01 16:20:47 +0000957TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000958 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000959
960 sp<IBinderRpcSession> session;
961 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
962
963 sp<IBinder> inBinder = IInterface::asBinder(session);
964 sp<IBinder> outBinder;
965 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
966 EXPECT_EQ(inBinder, outBinder);
967
968 wp<IBinder> weak = inBinder;
969 session = nullptr;
970 inBinder = nullptr;
971 outBinder = nullptr;
972
973 // Force reading a reply, to process any pending dec refs from the other
974 // process (the other process will process dec refs there before processing
975 // the ping here).
976 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
977
978 EXPECT_EQ(nullptr, weak.promote());
979}
980
Steven Morelandc1635952021-04-01 16:20:47 +0000981TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000982 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000983
984 sp<IBinder> outBinder;
985 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
986 EXPECT_EQ(nullptr, outBinder);
987}
988
Steven Morelandc1635952021-04-01 16:20:47 +0000989TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000990 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000991
992 IBinder* ptr = nullptr;
993 {
994 sp<IBinder> binder = new BBinder();
995 ptr = binder.get();
996 EXPECT_OK(proc.rootIface->holdBinder(binder));
997 }
998
999 sp<IBinder> held;
1000 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
1001
1002 EXPECT_EQ(held.get(), ptr);
1003
1004 // stop holding binder, because we test to make sure references are cleaned
1005 // up
1006 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
1007 // and flush ref counts
1008 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1009}
1010
1011// START TESTS FOR LIMITATIONS OF SOCKET BINDER
1012// These are behavioral differences form regular binder, where certain usecases
1013// aren't supported.
1014
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001015TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001016 auto proc1 = createRpcTestSocketServerProcess({});
1017 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001018
1019 sp<IBinder> outBinder;
1020 EXPECT_EQ(INVALID_OPERATION,
1021 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
1022}
1023
Andrei Homescu12106de2022-04-27 04:42:21 +00001024TEST_P(BinderRpcThreads, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001025 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +00001026
1027 sp<IBinder> outBinder;
1028 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001029 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +00001030 .transactionError());
1031}
1032
Steven Morelandc1635952021-04-01 16:20:47 +00001033TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001034 if constexpr (!kEnableKernelIpc) {
1035 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1036 "at build time.";
1037 }
1038
Steven Moreland4313d7e2021-07-15 23:41:22 +00001039 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001040
1041 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
1042 sp<IBinder> outBinder;
1043 EXPECT_EQ(INVALID_OPERATION,
1044 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
1045}
1046
Steven Morelandc1635952021-04-01 16:20:47 +00001047TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001048 if constexpr (!kEnableKernelIpc) {
1049 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1050 "at build time.";
1051 }
1052
Steven Moreland4313d7e2021-07-15 23:41:22 +00001053 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001054
1055 // for historical reasons, IServiceManager interface only returns the
1056 // exception code
1057 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
1058 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
1059}
1060
1061// END TESTS FOR LIMITATIONS OF SOCKET BINDER
1062
Steven Morelandc1635952021-04-01 16:20:47 +00001063TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001064 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001065
1066 sp<IBinder> outBinder;
1067 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
1068 EXPECT_EQ(proc.rootBinder, outBinder);
1069}
1070
Steven Morelandc1635952021-04-01 16:20:47 +00001071TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +00001072 auto proc = createRpcTestSocketServerProcess({
1073 // Enable FD support because it uses more stack space and so represents
1074 // something closer to a worst case scenario.
1075 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1076 .serverSupportedFileDescriptorTransportModes =
1077 {RpcSession::FileDescriptorTransportMode::UNIX},
1078 });
Steven Moreland5553ac42020-11-11 02:14:45 +00001079
1080 auto nastyNester = sp<MyBinderRpcTest>::make();
1081 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
1082
1083 wp<IBinder> weak = nastyNester;
1084 nastyNester = nullptr;
1085 EXPECT_EQ(nullptr, weak.promote());
1086}
1087
Steven Morelandc1635952021-04-01 16:20:47 +00001088TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001089 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001090
1091 sp<IBinder> a;
1092 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
1093
1094 sp<IBinder> b;
1095 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
1096
1097 EXPECT_EQ(a, b);
1098}
1099
Steven Morelandc1635952021-04-01 16:20:47 +00001100TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001101 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001102
1103 sp<IBinder> a;
1104 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
1105 wp<IBinder> weak = a;
1106 a = nullptr;
1107
1108 sp<IBinder> b;
1109 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
1110
1111 // this is the wrong behavior, since BpBinder
1112 // doesn't implement onIncStrongAttempted
1113 // but make sure there is no crash
1114 EXPECT_EQ(nullptr, weak.promote());
1115
1116 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
1117
1118 // In order to fix this:
1119 // - need to have incStrongAttempted reflected across IPC boundary (wait for
1120 // response to promote - round trip...)
1121 // - sendOnLastWeakRef, to delete entries out of RpcState table
1122 EXPECT_EQ(b, weak.promote());
1123}
1124
1125#define expectSessions(expected, iface) \
1126 do { \
1127 int session; \
1128 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
1129 EXPECT_EQ(expected, session); \
1130 } while (false)
1131
Steven Morelandc1635952021-04-01 16:20:47 +00001132TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001133 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001134
1135 sp<IBinderRpcSession> session;
1136 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
1137 std::string out;
1138 EXPECT_OK(session->getName(&out));
1139 EXPECT_EQ("aoeu", out);
1140
1141 expectSessions(1, proc.rootIface);
1142 session = nullptr;
1143 expectSessions(0, proc.rootIface);
1144}
1145
Steven Morelandc1635952021-04-01 16:20:47 +00001146TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001147 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001148
1149 std::vector<sp<IBinderRpcSession>> sessions;
1150
1151 for (size_t i = 0; i < 15; i++) {
1152 expectSessions(i, proc.rootIface);
1153 sp<IBinderRpcSession> session;
1154 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
1155 sessions.push_back(session);
1156 }
1157 expectSessions(sessions.size(), proc.rootIface);
1158 for (size_t i = 0; i < sessions.size(); i++) {
1159 std::string out;
1160 EXPECT_OK(sessions.at(i)->getName(&out));
1161 EXPECT_EQ(std::to_string(i), out);
1162 }
1163 expectSessions(sessions.size(), proc.rootIface);
1164
1165 while (!sessions.empty()) {
1166 sessions.pop_back();
1167 expectSessions(sessions.size(), proc.rootIface);
1168 }
1169 expectSessions(0, proc.rootIface);
1170}
1171
1172size_t epochMillis() {
1173 using std::chrono::duration_cast;
1174 using std::chrono::milliseconds;
1175 using std::chrono::seconds;
1176 using std::chrono::system_clock;
1177 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1178}
1179
Andrei Homescu12106de2022-04-27 04:42:21 +00001180TEST_P(BinderRpcThreads, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001181 constexpr size_t kNumThreads = 10;
1182
Steven Moreland4313d7e2021-07-15 23:41:22 +00001183 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001184
1185 EXPECT_OK(proc.rootIface->lock());
1186
1187 // block all but one thread taking locks
1188 std::vector<std::thread> ts;
1189 for (size_t i = 0; i < kNumThreads - 1; i++) {
1190 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
1191 }
1192
1193 usleep(100000); // give chance for calls on other threads
1194
1195 // other calls still work
1196 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1197
1198 constexpr size_t blockTimeMs = 500;
1199 size_t epochMsBefore = epochMillis();
1200 // after this, we should never see a response within this time
1201 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
1202
1203 // this call should be blocked for blockTimeMs
1204 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1205
1206 size_t epochMsAfter = epochMillis();
1207 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
1208
1209 for (auto& t : ts) t.join();
1210}
1211
Yifan Hong1f44f982021-10-08 17:16:47 -07001212void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
1213 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001214 size_t epochMsBefore = epochMillis();
1215
1216 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -07001217 for (size_t i = 0; i < numCalls; i++) {
1218 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +00001219 }
1220
1221 for (auto& t : ts) t.join();
1222
1223 size_t epochMsAfter = epochMillis();
1224
Yifan Hong1f44f982021-10-08 17:16:47 -07001225 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +00001226
1227 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -07001228 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
1229}
1230
Andrei Homescu12106de2022-04-27 04:42:21 +00001231TEST_P(BinderRpcThreads, ThreadPoolOverSaturated) {
Yifan Hong1f44f982021-10-08 17:16:47 -07001232 constexpr size_t kNumThreads = 10;
1233 constexpr size_t kNumCalls = kNumThreads + 3;
1234 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1235 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
1236}
1237
Andrei Homescu12106de2022-04-27 04:42:21 +00001238TEST_P(BinderRpcThreads, ThreadPoolLimitOutgoing) {
Yifan Hong1f44f982021-10-08 17:16:47 -07001239 constexpr size_t kNumThreads = 20;
1240 constexpr size_t kNumOutgoingConnections = 10;
1241 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
1242 auto proc = createRpcTestSocketServerProcess(
1243 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
1244 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +00001245}
1246
Andrei Homescu12106de2022-04-27 04:42:21 +00001247TEST_P(BinderRpcThreads, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001248 constexpr size_t kNumClientThreads = 10;
1249 constexpr size_t kNumServerThreads = 10;
1250 constexpr size_t kNumCalls = 100;
1251
Steven Moreland4313d7e2021-07-15 23:41:22 +00001252 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001253
1254 std::vector<std::thread> threads;
1255 for (size_t i = 0; i < kNumClientThreads; i++) {
1256 threads.push_back(std::thread([&] {
1257 for (size_t j = 0; j < kNumCalls; j++) {
1258 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001259 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001260 EXPECT_EQ(proc.rootBinder, out);
1261 }
1262 }));
1263 }
1264
1265 for (auto& t : threads) t.join();
1266}
1267
Steven Moreland925ba0a2021-09-17 18:06:32 -07001268static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
1269 std::vector<std::thread> threads;
1270 for (size_t i = 0; i < threadCount; i++) {
1271 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
1272 }
1273 for (auto& t : threads) t.join();
1274}
1275
Andrei Homescu12106de2022-04-27 04:42:21 +00001276TEST_P(BinderRpcThreads, OnewayStressTest) {
Steven Morelandc6046982021-04-20 00:49:42 +00001277 constexpr size_t kNumClientThreads = 10;
1278 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -07001279 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +00001280
Steven Moreland4313d7e2021-07-15 23:41:22 +00001281 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001282
1283 std::vector<std::thread> threads;
1284 for (size_t i = 0; i < kNumClientThreads; i++) {
1285 threads.push_back(std::thread([&] {
1286 for (size_t j = 0; j < kNumCalls; j++) {
1287 EXPECT_OK(proc.rootIface->sendString("a"));
1288 }
Steven Morelandc6046982021-04-20 00:49:42 +00001289 }));
1290 }
1291
1292 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -07001293
1294 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +00001295}
1296
Steven Morelandc1635952021-04-01 16:20:47 +00001297TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001298 constexpr size_t kReallyLongTimeMs = 100;
1299 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1300
Steven Moreland4313d7e2021-07-15 23:41:22 +00001301 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001302
1303 size_t epochMsBefore = epochMillis();
1304
1305 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1306
1307 size_t epochMsAfter = epochMillis();
1308 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1309}
1310
Andrei Homescu12106de2022-04-27 04:42:21 +00001311TEST_P(BinderRpcThreads, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001312 constexpr size_t kNumSleeps = 10;
1313 constexpr size_t kNumExtraServerThreads = 4;
1314 constexpr size_t kSleepMs = 50;
1315
1316 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001317 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001318
1319 EXPECT_OK(proc.rootIface->lock());
1320
Steven Moreland1c678802021-09-17 16:48:47 -07001321 size_t epochMsBefore = epochMillis();
1322
1323 // all these *Async commands should be queued on the server sequentially,
1324 // even though there are multiple threads.
1325 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001326 proc.rootIface->sleepMsAsync(kSleepMs);
1327 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001328 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1329
Steven Moreland1c678802021-09-17 16:48:47 -07001330 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +00001331 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -07001332
Steven Moreland5553ac42020-11-11 02:14:45 +00001333 size_t epochMsAfter = epochMillis();
1334
1335 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001336
Steven Moreland925ba0a2021-09-17 18:06:32 -07001337 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001338}
1339
Andrei Homescu12106de2022-04-27 04:42:21 +00001340TEST_P(BinderRpcThreads, OnewayCallExhaustion) {
Steven Morelandd45be622021-06-04 02:19:37 +00001341 constexpr size_t kNumClients = 2;
1342 constexpr size_t kTooLongMs = 1000;
1343
Steven Moreland4313d7e2021-07-15 23:41:22 +00001344 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001345
1346 // Build up oneway calls on the second session to make sure it terminates
1347 // and shuts down. The first session should be unaffected (proc destructor
1348 // checks the first session).
1349 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1350
1351 std::vector<std::thread> threads;
1352 for (size_t i = 0; i < kNumClients; i++) {
1353 // one of these threads will get stuck queueing a transaction once the
1354 // socket fills up, the other will be able to fill up transactions on
1355 // this object
1356 threads.push_back(std::thread([&] {
1357 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1358 }
1359 }));
1360 }
1361 for (auto& t : threads) t.join();
1362
1363 Status status = iface->sleepMsAsync(kTooLongMs);
1364 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1365
Steven Moreland798e0d12021-07-14 23:19:25 +00001366 // now that it has died, wait for the remote session to shutdown
1367 std::vector<int32_t> remoteCounts;
1368 do {
1369 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1370 } while (remoteCounts.size() == kNumClients);
1371
Steven Morelandd45be622021-06-04 02:19:37 +00001372 // the second session should be shutdown in the other process by the time we
1373 // are able to join above (it'll only be hung up once it finishes processing
1374 // any pending commands). We need to erase this session from the record
1375 // here, so that the destructor for our session won't check that this
1376 // session is valid, but we still want it to test the other session.
1377 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1378}
1379
Steven Moreland659416d2021-05-11 00:47:50 +00001380TEST_P(BinderRpc, Callbacks) {
1381 const static std::string kTestString = "good afternoon!";
1382
Steven Morelandc7d40132021-06-10 03:42:11 +00001383 for (bool callIsOneway : {true, false}) {
1384 for (bool callbackIsOneway : {true, false}) {
1385 for (bool delayed : {true, false}) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001386 if (!kEnableRpcThreads && (callIsOneway || callbackIsOneway || delayed)) {
1387 // we have no incoming connections to receive the callback
1388 continue;
1389 }
1390
Steven Moreland4313d7e2021-07-15 23:41:22 +00001391 auto proc = createRpcTestSocketServerProcess(
Andrei Homescu12106de2022-04-27 04:42:21 +00001392 {.numThreads = 1,
1393 .numSessions = 1,
1394 .numIncomingConnections = kEnableRpcThreads ? 1 : 0});
Steven Morelandc7d40132021-06-10 03:42:11 +00001395 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001396
Steven Morelandc7d40132021-06-10 03:42:11 +00001397 if (callIsOneway) {
1398 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1399 kTestString));
1400 } else {
1401 EXPECT_OK(
1402 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1403 }
Steven Moreland659416d2021-05-11 00:47:50 +00001404
Steven Moreland03ecce62022-05-13 23:22:05 +00001405 // if both transactions are synchronous and the response is sent back on the
1406 // same thread, everything should have happened in a nested call. Otherwise,
1407 // the callback will be processed on another thread.
1408 if (callIsOneway || callbackIsOneway || delayed) {
1409 using std::literals::chrono_literals::operator""s;
Andrei Homescu12106de2022-04-27 04:42:21 +00001410 RpcMutexUniqueLock _l(cb->mMutex);
Steven Moreland03ecce62022-05-13 23:22:05 +00001411 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1412 }
Steven Moreland659416d2021-05-11 00:47:50 +00001413
Steven Morelandc7d40132021-06-10 03:42:11 +00001414 EXPECT_EQ(cb->mValues.size(), 1)
1415 << "callIsOneway: " << callIsOneway
1416 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1417 if (cb->mValues.empty()) continue;
1418 EXPECT_EQ(cb->mValues.at(0), kTestString)
1419 << "callIsOneway: " << callIsOneway
1420 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001421
Steven Morelandc7d40132021-06-10 03:42:11 +00001422 // since we are severing the connection, we need to go ahead and
1423 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001424 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1425 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1426 }
Steven Moreland659416d2021-05-11 00:47:50 +00001427
Steven Moreland1b304292021-07-15 22:59:34 +00001428 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001429 // need to manually shut it down
1430 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001431
Frederick Maylea12b0962022-06-25 01:13:22 +00001432 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1433 // Flaky. Sometimes gets SIGABRT.
1434 EXPECT_TRUE((WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0) ||
1435 (WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT))
1436 << "server process failed: " << WaitStatusToString(wstatus);
1437 });
Steven Morelandc7d40132021-06-10 03:42:11 +00001438 proc.expectAlreadyShutdown = true;
1439 }
Steven Moreland659416d2021-05-11 00:47:50 +00001440 }
1441 }
1442}
1443
Steven Moreland195edb82021-06-08 02:44:39 +00001444TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001445 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001446 auto cb = sp<MyBinderRpcCallback>::make();
1447
1448 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1449 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1450}
1451
Steven Morelandc1635952021-04-01 16:20:47 +00001452TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001453 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001454 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001455
1456 // make sure there is some state during crash
1457 // 1. we hold their binder
1458 sp<IBinderRpcSession> session;
1459 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1460 // 2. they hold our binder
1461 sp<IBinder> binder = new BBinder();
1462 EXPECT_OK(proc.rootIface->holdBinder(binder));
1463
1464 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1465 << "Do death cleanup: " << doDeathCleanup;
1466
Frederick Maylea12b0962022-06-25 01:13:22 +00001467 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1468 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1469 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1470 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001471 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001472 }
1473}
1474
Steven Morelandd7302072021-05-15 01:32:04 +00001475TEST_P(BinderRpc, UseKernelBinderCallingId) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001476 if constexpr (!kEnableKernelIpc) {
1477 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1478 "at build time.";
1479 }
1480
Steven Morelanda83191d2021-10-27 10:14:53 -07001481 bool okToFork = ProcessState::selfOrNull() == nullptr;
1482
Steven Moreland4313d7e2021-07-15 23:41:22 +00001483 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001484
Steven Morelanda83191d2021-10-27 10:14:53 -07001485 // If this process has used ProcessState already, then the forked process
1486 // cannot use it at all. If this process hasn't used it (depending on the
1487 // order tests are run), then the forked process can use it, and we'll only
1488 // catch the invalid usage the second time. Such is the burden of global
1489 // state!
1490 if (okToFork) {
1491 // we can't allocate IPCThreadState so actually the first time should
1492 // succeed :(
1493 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1494 }
Steven Morelandd7302072021-05-15 01:32:04 +00001495
1496 // second time! we catch the error :)
1497 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1498
Frederick Maylea12b0962022-06-25 01:13:22 +00001499 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1500 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1501 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1502 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001503 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001504}
1505
Frederick Mayle69a0c992022-05-26 20:38:39 +00001506TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1507 auto proc = createRpcTestSocketServerProcess({
1508 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1509 .serverSupportedFileDescriptorTransportModes =
1510 {RpcSession::FileDescriptorTransportMode::UNIX},
1511 .allowConnectFailure = true,
1512 });
1513 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1514 proc.proc.host.terminate();
1515 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1516 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1517 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1518 });
1519 proc.expectAlreadyShutdown = true;
1520}
1521
1522TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1523 auto proc = createRpcTestSocketServerProcess({
1524 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1525 .serverSupportedFileDescriptorTransportModes =
1526 {RpcSession::FileDescriptorTransportMode::NONE},
1527 .allowConnectFailure = true,
1528 });
1529 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1530 proc.proc.host.terminate();
1531 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1532 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1533 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1534 });
1535 proc.expectAlreadyShutdown = true;
1536}
1537
1538TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1539 auto proc = createRpcTestSocketServerProcess({
1540 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1541 .serverSupportedFileDescriptorTransportModes =
1542 {RpcSession::FileDescriptorTransportMode::NONE,
1543 RpcSession::FileDescriptorTransportMode::UNIX},
1544 });
1545
1546 android::os::ParcelFileDescriptor out;
1547 auto status = proc.rootIface->echoAsFile("hello", &out);
1548 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1549}
1550
1551TEST_P(BinderRpc, ReceiveFile) {
1552 auto proc = createRpcTestSocketServerProcess({
1553 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1554 .serverSupportedFileDescriptorTransportModes =
1555 {RpcSession::FileDescriptorTransportMode::UNIX},
1556 });
1557
1558 android::os::ParcelFileDescriptor out;
1559 auto status = proc.rootIface->echoAsFile("hello", &out);
1560 if (!supportsFdTransport()) {
1561 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1562 return;
1563 }
1564 ASSERT_TRUE(status.isOk()) << status;
1565
1566 std::string result;
1567 CHECK(android::base::ReadFdToString(out.get(), &result));
1568 EXPECT_EQ(result, "hello");
1569}
1570
1571TEST_P(BinderRpc, SendFiles) {
1572 auto proc = createRpcTestSocketServerProcess({
1573 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1574 .serverSupportedFileDescriptorTransportModes =
1575 {RpcSession::FileDescriptorTransportMode::UNIX},
1576 });
1577
1578 std::vector<android::os::ParcelFileDescriptor> files;
1579 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1580 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1581 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1582 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1583
1584 android::os::ParcelFileDescriptor out;
1585 auto status = proc.rootIface->concatFiles(files, &out);
1586 if (!supportsFdTransport()) {
1587 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1588 return;
1589 }
1590 ASSERT_TRUE(status.isOk()) << status;
1591
1592 std::string result;
1593 CHECK(android::base::ReadFdToString(out.get(), &result));
1594 EXPECT_EQ(result, "123abcd");
1595}
1596
1597TEST_P(BinderRpc, SendMaxFiles) {
1598 if (!supportsFdTransport()) {
1599 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1600 }
1601
1602 auto proc = createRpcTestSocketServerProcess({
1603 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1604 .serverSupportedFileDescriptorTransportModes =
1605 {RpcSession::FileDescriptorTransportMode::UNIX},
1606 });
1607
1608 std::vector<android::os::ParcelFileDescriptor> files;
1609 for (int i = 0; i < 253; i++) {
1610 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1611 }
1612
1613 android::os::ParcelFileDescriptor out;
1614 auto status = proc.rootIface->concatFiles(files, &out);
1615 ASSERT_TRUE(status.isOk()) << status;
1616
1617 std::string result;
1618 CHECK(android::base::ReadFdToString(out.get(), &result));
1619 EXPECT_EQ(result, std::string(253, 'a'));
1620}
1621
1622TEST_P(BinderRpc, SendTooManyFiles) {
1623 if (!supportsFdTransport()) {
1624 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1625 }
1626
1627 auto proc = createRpcTestSocketServerProcess({
1628 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1629 .serverSupportedFileDescriptorTransportModes =
1630 {RpcSession::FileDescriptorTransportMode::UNIX},
1631 });
1632
1633 std::vector<android::os::ParcelFileDescriptor> files;
1634 for (int i = 0; i < 254; i++) {
1635 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1636 }
1637
1638 android::os::ParcelFileDescriptor out;
1639 auto status = proc.rootIface->concatFiles(files, &out);
1640 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1641}
1642
Steven Moreland37aff182021-03-26 02:04:16 +00001643TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001644 if constexpr (!kEnableSharedLibs) {
1645 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1646 }
1647
Steven Moreland4313d7e2021-07-15 23:41:22 +00001648 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001649
1650 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1651 ASSERT_NE(binder, nullptr);
1652
1653 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1654}
1655
1656TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001657 if constexpr (!kEnableSharedLibs) {
1658 GTEST_SKIP() << "Test disabled because Binder was built as a static library";
1659 }
1660
Steven Moreland4313d7e2021-07-15 23:41:22 +00001661 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001662
1663 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1664 ASSERT_NE(binder, nullptr);
1665
1666 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1667 ASSERT_NE(ndkBinder, nullptr);
1668
1669 std::string out;
1670 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1671 ASSERT_TRUE(status.isOk()) << status.getDescription();
1672 ASSERT_EQ("aoeuaoeu", out);
1673}
1674
Steven Moreland5553ac42020-11-11 02:14:45 +00001675ssize_t countFds() {
1676 DIR* dir = opendir("/proc/self/fd/");
1677 if (dir == nullptr) return -1;
1678 ssize_t ret = 0;
1679 dirent* ent;
1680 while ((ent = readdir(dir)) != nullptr) ret++;
1681 closedir(dir);
1682 return ret;
1683}
1684
Andrei Homescu12106de2022-04-27 04:42:21 +00001685TEST_P(BinderRpcThreads, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001686 ssize_t beforeFds = countFds();
1687 ASSERT_GE(beforeFds, 0);
1688 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001689 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001690 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1691 }
1692 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1693}
1694
Devin Moore800b2252021-10-15 16:22:57 +00001695TEST_P(BinderRpc, AidlDelegatorTest) {
1696 auto proc = createRpcTestSocketServerProcess({});
1697 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1698 ASSERT_NE(nullptr, myDelegator);
1699
1700 std::string doubled;
1701 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1702 EXPECT_EQ("cool cool ", doubled);
1703}
1704
Steven Morelandda573042021-06-12 01:13:45 +00001705static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001706 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001707 unsigned int vsockPort = allocateVsockPort();
Steven Morelandda573042021-06-12 01:13:45 +00001708
Andrei Homescu992a4052022-06-28 21:26:18 +00001709 android::base::unique_fd serverFd(
1710 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1711 LOG_ALWAYS_FATAL_IF(serverFd == -1, "Could not create socket: %s", strerror(errno));
1712
1713 sockaddr_vm serverAddr{
1714 .svm_family = AF_VSOCK,
1715 .svm_port = vsockPort,
1716 .svm_cid = VMADDR_CID_ANY,
1717 };
1718 int ret = TEMP_FAILURE_RETRY(
1719 bind(serverFd.get(), reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)));
1720 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not bind socket to port %u: %s", vsockPort,
1721 strerror(errno));
1722
1723 ret = TEMP_FAILURE_RETRY(listen(serverFd.get(), 1 /*backlog*/));
1724 LOG_ALWAYS_FATAL_IF(0 != ret, "Could not listen socket on port %u: %s", vsockPort,
1725 strerror(errno));
1726
1727 // Try to connect to the server using the VMADDR_CID_LOCAL cid
1728 // to see if the kernel supports it. It's safe to use a blocking
1729 // connect because vsock sockets have a 2 second connection timeout,
1730 // and they return ETIMEDOUT after that.
1731 android::base::unique_fd connectFd(
1732 TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
1733 LOG_ALWAYS_FATAL_IF(connectFd == -1, "Could not create socket for port %u: %s", vsockPort,
1734 strerror(errno));
1735
1736 bool success = false;
1737 sockaddr_vm connectAddr{
1738 .svm_family = AF_VSOCK,
1739 .svm_port = vsockPort,
1740 .svm_cid = VMADDR_CID_LOCAL,
1741 };
1742 ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
1743 sizeof(connectAddr)));
1744 if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
1745 android::base::unique_fd acceptFd;
1746 while (true) {
1747 pollfd pfd[]{
1748 {.fd = serverFd.get(), .events = POLLIN, .revents = 0},
1749 {.fd = connectFd.get(), .events = POLLOUT, .revents = 0},
1750 };
1751 ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
1752 LOG_ALWAYS_FATAL_IF(ret < 0, "Error polling: %s", strerror(errno));
1753
1754 if (pfd[0].revents & POLLIN) {
1755 sockaddr_vm acceptAddr;
1756 socklen_t acceptAddrLen = sizeof(acceptAddr);
1757 ret = TEMP_FAILURE_RETRY(accept4(serverFd.get(),
1758 reinterpret_cast<sockaddr*>(&acceptAddr),
1759 &acceptAddrLen, SOCK_CLOEXEC));
1760 LOG_ALWAYS_FATAL_IF(ret < 0, "Could not accept4 socket: %s", strerror(errno));
1761 LOG_ALWAYS_FATAL_IF(acceptAddrLen != static_cast<socklen_t>(sizeof(acceptAddr)),
1762 "Truncated address");
1763
1764 // Store the fd in acceptFd so we keep the connection alive
1765 // while polling connectFd
1766 acceptFd.reset(ret);
1767 }
1768
1769 if (pfd[1].revents & POLLOUT) {
1770 // Connect either succeeded or timed out
1771 int connectErrno;
1772 socklen_t connectErrnoLen = sizeof(connectErrno);
1773 int ret = getsockopt(connectFd.get(), SOL_SOCKET, SO_ERROR, &connectErrno,
1774 &connectErrnoLen);
1775 LOG_ALWAYS_FATAL_IF(ret == -1,
1776 "Could not getsockopt() after connect() "
1777 "on non-blocking socket: %s.",
1778 strerror(errno));
1779
1780 // We're done, this is all we wanted
1781 success = connectErrno == 0;
1782 break;
1783 }
1784 }
1785 } else {
1786 success = ret == 0;
1787 }
1788
1789 ALOGE("Detected vsock loopback supported: %s", success ? "yes" : "no");
1790
1791 return success;
Steven Morelandda573042021-06-12 01:13:45 +00001792}
1793
Yifan Hong1deca4b2021-09-10 16:16:44 -07001794static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1795 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1796
1797 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001798
1799 static bool hasVsockLoopback = testSupportVsockLoopback();
1800
1801 if (hasVsockLoopback) {
1802 ret.push_back(SocketType::VSOCK);
1803 }
1804
1805 return ret;
1806}
1807
Frederick Mayledc07cf82022-05-26 20:30:12 +00001808static std::vector<uint32_t> testVersions() {
1809 std::vector<uint32_t> versions;
1810 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1811 versions.push_back(i);
1812 }
1813 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1814 return versions;
1815}
1816
Yifan Hong702115c2021-06-24 15:39:18 -07001817INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1818 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001819 ::testing::ValuesIn(RpcSecurityValues()),
1820 ::testing::ValuesIn(testVersions()),
1821 ::testing::ValuesIn(testVersions())),
Yifan Hong702115c2021-06-24 15:39:18 -07001822 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001823
Andrei Homescu12106de2022-04-27 04:42:21 +00001824INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpcThreads,
1825 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1826 ::testing::ValuesIn(RpcSecurityValues()),
1827 ::testing::ValuesIn(testVersions()),
1828 ::testing::ValuesIn(testVersions())),
1829 BinderRpc::PrintParamInfo);
1830
Yifan Hong702115c2021-06-24 15:39:18 -07001831class BinderRpcServerRootObject
1832 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001833
1834TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1835 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1836 auto setRootObject = [](bool isStrong) -> SetFn {
1837 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1838 };
1839
Yifan Hong702115c2021-06-24 15:39:18 -07001840 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1841 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001842 auto binder1 = sp<BBinder>::make();
1843 IBinder* binderRaw1 = binder1.get();
1844 setRootObject(isStrong1)(server.get(), binder1);
1845 EXPECT_EQ(binderRaw1, server->getRootObject());
1846 binder1.clear();
1847 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1848
1849 auto binder2 = sp<BBinder>::make();
1850 IBinder* binderRaw2 = binder2.get();
1851 setRootObject(isStrong2)(server.get(), binder2);
1852 EXPECT_EQ(binderRaw2, server->getRootObject());
1853 binder2.clear();
1854 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1855}
1856
1857INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001858 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1859 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001860
Yifan Hong1a235852021-05-13 16:07:47 -07001861class OneOffSignal {
1862public:
1863 // If notify() was previously called, or is called within |duration|, return true; else false.
1864 template <typename R, typename P>
1865 bool wait(std::chrono::duration<R, P> duration) {
1866 std::unique_lock<std::mutex> lock(mMutex);
1867 return mCv.wait_for(lock, duration, [this] { return mValue; });
1868 }
1869 void notify() {
1870 std::unique_lock<std::mutex> lock(mMutex);
1871 mValue = true;
1872 lock.unlock();
1873 mCv.notify_all();
1874 }
1875
1876private:
1877 std::mutex mMutex;
1878 std::condition_variable mCv;
1879 bool mValue = false;
1880};
1881
Frederick Mayledc07cf82022-05-26 20:30:12 +00001882TEST_P(BinderRpcServerOnly, Shutdown) {
Andrei Homescu12106de2022-04-27 04:42:21 +00001883 if constexpr (!kEnableRpcThreads) {
1884 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
1885 }
1886
Yifan Hong1a235852021-05-13 16:07:47 -07001887 auto addr = allocateSocketAddress();
Frederick Mayledc07cf82022-05-26 20:30:12 +00001888 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1889 server->setProtocolVersion(std::get<1>(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001890 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001891 auto joinEnds = std::make_shared<OneOffSignal>();
1892
1893 // If things are broken and the thread never stops, don't block other tests. Because the thread
1894 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1895 // shared pointers are passed.
1896 std::thread([server, joinEnds] {
1897 server->join();
1898 joinEnds->notify();
1899 }).detach();
1900
1901 bool shutdown = false;
1902 for (int i = 0; i < 10 && !shutdown; i++) {
1903 usleep(300 * 1000); // 300ms; total 3s
1904 if (server->shutdown()) shutdown = true;
1905 }
1906 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1907
1908 ASSERT_TRUE(joinEnds->wait(2s))
1909 << "After server->shutdown() returns true, join() did not stop after 2s";
1910}
1911
Yifan Hong194acf22021-06-29 18:44:56 -07001912TEST(BinderRpc, Java) {
1913#if !defined(__ANDROID__)
1914 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1915 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1916 "to binderHostDeviceTest. Hence, just disable this test on host.";
1917#endif // !__ANDROID__
Andrei Homescu12106de2022-04-27 04:42:21 +00001918 if constexpr (!kEnableKernelIpc) {
1919 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
1920 "at build time.";
1921 }
1922
Yifan Hong194acf22021-06-29 18:44:56 -07001923 sp<IServiceManager> sm = defaultServiceManager();
1924 ASSERT_NE(nullptr, sm);
1925 // Any Java service with non-empty getInterfaceDescriptor() would do.
1926 // Let's pick batteryproperties.
1927 auto binder = sm->checkService(String16("batteryproperties"));
1928 ASSERT_NE(nullptr, binder);
1929 auto descriptor = binder->getInterfaceDescriptor();
1930 ASSERT_GE(descriptor.size(), 0);
1931 ASSERT_EQ(OK, binder->pingBinder());
1932
1933 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001934 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001935 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001936 auto socket = rpcServer->releaseServer();
1937
1938 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001939 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1940
Yifan Honge3caaf22022-01-12 14:46:56 -08001941 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1942 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001943 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001944 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1945 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001946 << statusToString(setRpcClientDebugStatus);
1947 GTEST_SKIP();
1948 }
1949
1950 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001951
1952 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001953 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001954 auto rpcBinder = rpcSession->getRootObject();
1955 ASSERT_NE(nullptr, rpcBinder);
1956
1957 ASSERT_EQ(OK, rpcBinder->pingBinder());
1958
1959 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1960 << "getInterfaceDescriptor should not crash system_server";
1961 ASSERT_EQ(OK, rpcBinder->pingBinder());
1962}
1963
Frederick Mayledc07cf82022-05-26 20:30:12 +00001964INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1965 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1966 ::testing::ValuesIn(testVersions())),
1967 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001968
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001969class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001970public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001971 // Only parameterized only server version because `RpcSession` is bypassed
1972 // in the client half of the tests.
1973 using Param =
1974 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001975 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001976
1977 // A server that handles client socket connections.
1978 class Server {
1979 public:
1980 explicit Server() {}
1981 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001982 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001983 [[nodiscard]] AssertionResult setUp(
1984 const Param& param,
1985 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001986 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001987 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001988 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001989 switch (socketType) {
1990 case SocketType::PRECONNECTED: {
1991 return AssertionFailure() << "Not supported by this test";
1992 } break;
1993 case SocketType::UNIX: {
1994 auto addr = allocateSocketAddress();
1995 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1996 if (status != OK) {
1997 return AssertionFailure()
1998 << "setupUnixDomainServer: " << statusToString(status);
1999 }
2000 mConnectToServer = [addr] {
2001 return connectTo(UnixSocketAddress(addr.c_str()));
2002 };
2003 } break;
2004 case SocketType::VSOCK: {
2005 auto port = allocateVsockPort();
2006 auto status = rpcServer->setupVsockServer(port);
2007 if (status != OK) {
2008 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
2009 }
2010 mConnectToServer = [port] {
2011 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
2012 };
2013 } break;
2014 case SocketType::INET: {
2015 unsigned int port;
2016 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
2017 if (status != OK) {
2018 return AssertionFailure() << "setupInetServer: " << statusToString(status);
2019 }
2020 mConnectToServer = [port] {
2021 const char* addr = kLocalInetAddress;
2022 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
2023 if (aiStart == nullptr) return base::unique_fd{};
2024 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
2025 auto fd = connectTo(
2026 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
2027 if (fd.ok()) return fd;
2028 }
2029 ALOGE("None of the socket address resolved for %s:%u can be connected",
2030 addr, port);
2031 return base::unique_fd{};
2032 };
2033 }
2034 }
2035 mFd = rpcServer->releaseServer();
2036 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002037 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07002038 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
2039 mSetup = true;
2040 return AssertionSuccess();
2041 }
2042 RpcTransportCtx* getCtx() const { return mCtx.get(); }
2043 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
2044 return mCertVerifier;
2045 }
2046 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
2047 void start() {
2048 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
2049 mThread = std::make_unique<std::thread>(&Server::run, this);
2050 }
2051 void run() {
2052 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
2053
2054 std::vector<std::thread> threads;
2055 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
2056 base::unique_fd acceptedFd(
2057 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
2058 SOCK_CLOEXEC | SOCK_NONBLOCK)));
2059 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
2060 }
2061
2062 for (auto& thread : threads) thread.join();
2063 }
2064 void handleOne(android::base::unique_fd acceptedFd) {
2065 ASSERT_TRUE(acceptedFd.ok());
2066 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
2067 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07002068 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002069 }
Yifan Honge07d2732021-09-13 21:59:14 -07002070 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07002071 shutdown();
2072 join();
2073 }
2074 void shutdown() { mFdTrigger->trigger(); }
2075
2076 void setPostConnect(
2077 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
2078 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002079 }
2080
2081 private:
2082 std::unique_ptr<std::thread> mThread;
2083 ConnectToServer mConnectToServer;
2084 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
2085 base::unique_fd mFd;
2086 std::unique_ptr<RpcTransportCtx> mCtx;
2087 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
2088 std::make_shared<RpcCertificateVerifierSimple>();
2089 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07002090 // The function invoked after connection and handshake. By default, it is
2091 // |defaultPostConnect| that sends |kMessage| to the client.
2092 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
2093 Server::defaultPostConnect;
2094
2095 void join() {
2096 if (mThread != nullptr) {
2097 mThread->join();
2098 mThread = nullptr;
2099 }
2100 }
2101
2102 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
2103 FdTrigger* fdTrigger) {
2104 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002105 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00002106 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00002107 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002108 if (status != OK) return AssertionFailure() << statusToString(status);
2109 return AssertionSuccess();
2110 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002111 };
2112
2113 class Client {
2114 public:
2115 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
2116 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002117 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002118 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
2119 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002120 mFdTrigger = FdTrigger::make();
2121 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
2122 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
2123 return AssertionSuccess();
2124 }
2125 RpcTransportCtx* getCtx() const { return mCtx.get(); }
2126 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
2127 return mCertVerifier;
2128 }
Yifan Hong67519322021-09-13 18:51:16 -07002129 // connect() and do handshake
2130 bool setUpTransport() {
2131 mFd = mConnectToServer();
2132 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
2133 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
2134 return mClientTransport != nullptr;
2135 }
2136 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
2137 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
2138 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002139 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00002140 status_t readStatus =
2141 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayleffe9ac22022-06-30 02:07:36 +00002142 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002143 if (readStatus != OK) {
2144 return AssertionFailure() << statusToString(readStatus);
2145 }
2146 if (readMessage != expectedMessage) {
2147 return AssertionFailure()
2148 << "Expected " << expectedMessage << ", actual " << readMessage;
2149 }
2150 return AssertionSuccess();
2151 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002152 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07002153 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07002154 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
2155 return;
2156 }
2157 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07002158 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07002159 }
2160
2161 private:
2162 ConnectToServer mConnectToServer;
2163 base::unique_fd mFd;
2164 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
2165 std::unique_ptr<RpcTransportCtx> mCtx;
2166 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
2167 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07002168 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002169 };
2170
2171 // Make A trust B.
2172 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002173 static status_t trust(RpcSecurity rpcSecurity,
2174 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
2175 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07002176 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07002177 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
2178 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
2179 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002180 }
2181
2182 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002183};
2184
2185class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
2186public:
2187 using Server = RpcTransportTestUtils::Server;
2188 using Client = RpcTransportTestUtils::Client;
2189 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002190 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002191 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
2192 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00002193 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002194 return ret;
2195 }
2196 static std::vector<ParamType> getRpcTranportTestParams() {
2197 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00002198 for (auto serverVersion : testVersions()) {
2199 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
2200 for (auto rpcSecurity : RpcSecurityValues()) {
2201 switch (rpcSecurity) {
2202 case RpcSecurity::RAW: {
2203 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
2204 } break;
2205 case RpcSecurity::TLS: {
2206 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
2207 serverVersion);
2208 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
2209 serverVersion);
2210 } break;
2211 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002212 }
2213 }
2214 }
2215 return ret;
2216 }
2217 template <typename A, typename B>
2218 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002219 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2220 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002221 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
2222 }
Andrei Homescu12106de2022-04-27 04:42:21 +00002223 void SetUp() override {
2224 if constexpr (!kEnableRpcThreads) {
2225 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2226 }
2227 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002228};
2229
2230TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002231 auto server = std::make_unique<Server>();
2232 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002233
2234 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002235 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002236
2237 ASSERT_EQ(OK, trust(&client, server));
2238 ASSERT_EQ(OK, trust(server, &client));
2239
2240 server->start();
2241 client.run();
2242}
2243
2244TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002245 auto server = std::make_unique<Server>();
2246 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002247
2248 std::vector<Client> clients;
2249 for (int i = 0; i < 2; i++) {
2250 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002251 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002252 ASSERT_EQ(OK, trust(&client, server));
2253 ASSERT_EQ(OK, trust(server, &client));
2254 }
2255
2256 server->start();
2257 for (auto& client : clients) client.run();
2258}
2259
2260TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002261 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2262 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002263
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002264 auto untrustedServer = std::make_unique<Server>();
2265 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002266
2267 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002268 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002269
2270 ASSERT_EQ(OK, trust(untrustedServer, &client));
2271
2272 untrustedServer->start();
2273
2274 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2275 // the client can't verify the server's identity.
2276 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2277 client.run(handshakeOk);
2278}
2279TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002280 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2281 (void)serverVersion;
2282
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002283 auto validServer = std::make_unique<Server>();
2284 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002285
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002286 auto maliciousServer = std::make_unique<Server>();
2287 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002288
2289 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002290 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002291
2292 ASSERT_EQ(OK, trust(&client, validServer));
2293 ASSERT_EQ(OK, trust(validServer, &client));
2294 ASSERT_EQ(OK, trust(maliciousServer, &client));
2295
2296 maliciousServer->start();
2297
2298 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2299 // the client can't verify the server's identity.
2300 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2301 client.run(handshakeOk);
2302}
2303
2304TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002305 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2306 (void)serverVersion;
2307
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002308 auto server = std::make_unique<Server>();
2309 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002310
2311 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002312 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002313
2314 ASSERT_EQ(OK, trust(&client, server));
2315
2316 server->start();
2317
2318 // For TLS, Client should be able to verify server's identity, so client should see
2319 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2320 // identity and should drop the connection, so client shouldn't be able to read anything.
2321 bool readOk = rpcSecurity != RpcSecurity::TLS;
2322 client.run(true, readOk);
2323}
2324
2325TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002326 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2327 (void)serverVersion;
2328
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002329 auto server = std::make_unique<Server>();
2330 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002331
2332 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002333 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002334 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002335 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002336
2337 ASSERT_EQ(OK, trust(&validClient, server));
2338 ASSERT_EQ(OK, trust(&maliciousClient, server));
2339
2340 server->start();
2341
2342 // See UntrustedClient.
2343 bool readOk = rpcSecurity != RpcSecurity::TLS;
2344 maliciousClient.run(true, readOk);
2345}
2346
Yifan Hong67519322021-09-13 18:51:16 -07002347TEST_P(RpcTransportTest, Trigger) {
2348 std::string msg2 = ", world!";
2349 std::mutex writeMutex;
2350 std::condition_variable writeCv;
2351 bool shouldContinueWriting = false;
2352 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002353 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002354 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002355 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2356 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002357 if (status != OK) return AssertionFailure() << statusToString(status);
2358
2359 {
2360 std::unique_lock<std::mutex> lock(writeMutex);
2361 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2362 return AssertionFailure() << "write barrier not cleared in time!";
2363 }
2364 }
2365
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002366 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002367 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2368 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002369 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002370 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002371 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002372 << statusToString(status);
2373 return AssertionSuccess();
2374 };
2375
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002376 auto server = std::make_unique<Server>();
2377 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002378
2379 // Set up client
2380 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002381 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002382
2383 // Exchange keys
2384 ASSERT_EQ(OK, trust(&client, server));
2385 ASSERT_EQ(OK, trust(server, &client));
2386
2387 server->setPostConnect(serverPostConnect);
2388
Yifan Hong67519322021-09-13 18:51:16 -07002389 server->start();
2390 // connect() to server and do handshake
2391 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002392 // read the first message. This ensures that server has finished handshake and start handling
2393 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002394 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002395 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2396 // write is on an FdTrigger that has been shut down.
2397 server->shutdown();
2398 // Continues server thread to write the second message.
2399 {
Yifan Hong22211f82021-09-14 12:32:25 -07002400 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002401 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002402 }
Yifan Hong22211f82021-09-14 12:32:25 -07002403 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002404 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002405 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002406 // On the client side, second read fails with DEAD_OBJECT
2407 ASSERT_FALSE(client.readMessage(msg2));
2408}
2409
Yifan Hong1deca4b2021-09-10 16:16:44 -07002410INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002411 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002412 RpcTransportTest::PrintParamInfo);
2413
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002414class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002415 : public testing::TestWithParam<
2416 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002417public:
2418 template <typename A, typename B>
2419 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002420 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2421 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002422 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2423 }
2424 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002425 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2426 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2427 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002428 };
2429};
2430
2431TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Andrei Homescu12106de2022-04-27 04:42:21 +00002432 if constexpr (!kEnableRpcThreads) {
2433 GTEST_SKIP() << "Test skipped because threads were disabled at build time";
2434 }
2435
Frederick Mayledc07cf82022-05-26 20:30:12 +00002436 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002437
2438 std::vector<uint8_t> pkeyData, certData;
2439 {
2440 auto pkey = makeKeyPairForSelfSignedCert();
2441 ASSERT_NE(nullptr, pkey);
2442 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2443 ASSERT_NE(nullptr, cert);
2444 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2445 certData = serializeCertificate(cert.get(), certificateFormat);
2446 }
2447
2448 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2449 auto desCert = deserializeCertificate(certData, certificateFormat);
2450 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002451 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2452 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002453
2454 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2455 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2456
2457 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2458 ASSERT_TRUE(client.setUp(utilsParam));
2459
2460 ASSERT_EQ(OK, trust(&client, server));
2461 ASSERT_EQ(OK, trust(server, &client));
2462
2463 server->start();
2464 client.run();
2465}
2466
2467INSTANTIATE_TEST_CASE_P(
2468 BinderRpc, RpcTransportTlsKeyTest,
2469 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2470 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002471 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2472 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002473 RpcTransportTlsKeyTest::PrintParamInfo);
2474
Steven Morelandc1635952021-04-01 16:20:47 +00002475} // namespace android
2476
2477int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002478 ::testing::InitGoogleTest(&argc, argv);
2479 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002480
Steven Moreland5553ac42020-11-11 02:14:45 +00002481 return RUN_ALL_TESTS();
2482}