blob: 3b1fc82226a05a0c88dad0abf4c4d094d8c594ea [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>
Yifan Honge0e53282021-09-23 18:37:21 -070036#include <binder/RpcTlsTestUtils.h>
Yifan Hongb1ce80c2021-09-17 22:10:58 -070037#include <binder/RpcTlsUtils.h>
Yifan Hong702115c2021-06-24 15:39:18 -070038#include <binder/RpcTransport.h>
39#include <binder/RpcTransportRaw.h>
Yifan Hong92409752021-07-30 21:25:32 -070040#include <binder/RpcTransportTls.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000041#include <gtest/gtest.h>
42
Steven Morelandc1635952021-04-01 16:20:47 +000043#include <chrono>
44#include <cstdlib>
45#include <iostream>
46#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000047#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000048
Yifan Hong1deca4b2021-09-10 16:16:44 -070049#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000050#include <sys/prctl.h>
51#include <unistd.h>
52
Yifan Hong1deca4b2021-09-10 16:16:44 -070053#include "../FdTrigger.h"
Steven Moreland4198a122021-08-03 17:37:58 -070054#include "../RpcSocketAddress.h" // for testing preconnected clients
Yifan Hongffdaf952021-09-17 18:08:38 -070055#include "../RpcState.h" // for debugging
56#include "../vm_sockets.h" // for VMADDR_*
Frederick Mayle69a0c992022-05-26 20:38:39 +000057#include "utils/Errors.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000058
Yifan Hong1a235852021-05-13 16:07:47 -070059using namespace std::chrono_literals;
Yifan Hong67519322021-09-13 18:51:16 -070060using namespace std::placeholders;
Yifan Hong1deca4b2021-09-10 16:16:44 -070061using testing::AssertionFailure;
62using testing::AssertionResult;
63using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070064
Steven Moreland5553ac42020-11-11 02:14:45 +000065namespace android {
66
Steven Morelandbf57bce2021-07-26 15:26:12 -070067static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
68 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Devin Mooref3b9c4f2021-08-03 15:50:13 +000069const char* kLocalInetAddress = "127.0.0.1";
Steven Morelandbf57bce2021-07-26 15:26:12 -070070
Yifan Hong92409752021-07-30 21:25:32 -070071enum class RpcSecurity { RAW, TLS };
Yifan Hong702115c2021-06-24 15:39:18 -070072
73static inline std::vector<RpcSecurity> RpcSecurityValues() {
Yifan Hong92409752021-07-30 21:25:32 -070074 return {RpcSecurity::RAW, RpcSecurity::TLS};
Yifan Hong702115c2021-06-24 15:39:18 -070075}
76
Yifan Hong13c90062021-09-09 14:59:53 -070077static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(
Yifan Hongffdaf952021-09-17 18:08:38 -070078 RpcSecurity rpcSecurity, std::shared_ptr<RpcCertificateVerifier> verifier = nullptr,
79 std::unique_ptr<RpcAuth> auth = nullptr) {
Yifan Hong702115c2021-06-24 15:39:18 -070080 switch (rpcSecurity) {
81 case RpcSecurity::RAW:
82 return RpcTransportCtxFactoryRaw::make();
Yifan Hong13c90062021-09-09 14:59:53 -070083 case RpcSecurity::TLS: {
Yifan Hong13c90062021-09-09 14:59:53 -070084 if (verifier == nullptr) {
85 verifier = std::make_shared<RpcCertificateVerifierSimple>();
86 }
Yifan Hongffdaf952021-09-17 18:08:38 -070087 if (auth == nullptr) {
88 auth = std::make_unique<RpcAuthSelfSigned>();
89 }
90 return RpcTransportCtxFactoryTls::make(std::move(verifier), std::move(auth));
Yifan Hong13c90062021-09-09 14:59:53 -070091 }
Yifan Hong702115c2021-06-24 15:39:18 -070092 default:
93 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
94 }
95}
96
Frederick Mayle69a0c992022-05-26 20:38:39 +000097// Create an FD that returns `contents` when read.
98static base::unique_fd mockFileDescriptor(std::string contents) {
99 android::base::unique_fd readFd, writeFd;
100 CHECK(android::base::Pipe(&readFd, &writeFd)) << strerror(errno);
101 std::thread([writeFd = std::move(writeFd), contents = std::move(contents)]() {
102 signal(SIGPIPE, SIG_IGN); // ignore possible SIGPIPE from the write
103 if (!WriteStringToFd(contents, writeFd)) {
104 int savedErrno = errno;
105 EXPECT_EQ(EPIPE, savedErrno)
106 << "mockFileDescriptor write failed: " << strerror(savedErrno);
107 }
108 }).detach();
109 return readFd;
110}
111
Steven Moreland1fda67b2021-04-02 18:35:50 +0000112TEST(BinderRpcParcel, EntireParcelFormatted) {
113 Parcel p;
114 p.writeInt32(3);
115
116 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
117}
118
Frederick Mayledc07cf82022-05-26 20:30:12 +0000119class BinderRpcServerOnly : public ::testing::TestWithParam<std::tuple<RpcSecurity, uint32_t>> {
Yifan Hong702115c2021-06-24 15:39:18 -0700120public:
121 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000122 return std::string(newFactory(std::get<0>(info.param))->toCString()) + "_serverV" +
123 std::to_string(std::get<1>(info.param));
Yifan Hong702115c2021-06-24 15:39:18 -0700124 }
125};
126
Frederick Mayledc07cf82022-05-26 20:30:12 +0000127TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700128 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
129 int sinkFd = sink.get();
Frederick Mayledc07cf82022-05-26 20:30:12 +0000130 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
131 server->setProtocolVersion(std::get<1>(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -0700132 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700133 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -0700134 ASSERT_TRUE(server->hasServer());
135 base::unique_fd retrieved = server->releaseServer();
136 ASSERT_FALSE(server->hasServer());
137 ASSERT_EQ(sinkFd, retrieved.get());
138}
139
Steven Morelandbf57bce2021-07-26 15:26:12 -0700140TEST(BinderRpc, CannotUseNextWireVersion) {
141 auto session = RpcSession::make();
142 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
143 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
144 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
145 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
146}
147
148TEST(BinderRpc, CanUseExperimentalWireVersion) {
149 auto session = RpcSession::make();
150 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
151}
152
Steven Moreland5553ac42020-11-11 02:14:45 +0000153using android::binder::Status;
154
155#define EXPECT_OK(status) \
156 do { \
157 Status stat = (status); \
158 EXPECT_TRUE(stat.isOk()) << stat; \
159 } while (false)
160
161class MyBinderRpcSession : public BnBinderRpcSession {
162public:
163 static std::atomic<int32_t> gNum;
164
165 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
166 Status getName(std::string* name) override {
167 *name = mName;
168 return Status::ok();
169 }
170 ~MyBinderRpcSession() { gNum--; }
171
172private:
173 std::string mName;
174};
175std::atomic<int32_t> MyBinderRpcSession::gNum;
176
Steven Moreland659416d2021-05-11 00:47:50 +0000177class MyBinderRpcCallback : public BnBinderRpcCallback {
178 Status sendCallback(const std::string& value) {
179 std::unique_lock _l(mMutex);
180 mValues.push_back(value);
181 _l.unlock();
182 mCv.notify_one();
183 return Status::ok();
184 }
185 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
186
187public:
188 std::mutex mMutex;
189 std::condition_variable mCv;
190 std::vector<std::string> mValues;
191};
192
Steven Moreland5553ac42020-11-11 02:14:45 +0000193class MyBinderRpcTest : public BnBinderRpcTest {
194public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000195 wp<RpcServer> server;
Steven Moreland51c44a92021-10-14 16:50:35 -0700196 int port = 0;
Steven Moreland5553ac42020-11-11 02:14:45 +0000197
198 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000199 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000200 return Status::ok();
201 }
202 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000203 *strstr = str + str;
204 return Status::ok();
205 }
Steven Moreland51c44a92021-10-14 16:50:35 -0700206 Status getClientPort(int* out) override {
207 *out = port;
208 return Status::ok();
209 }
Steven Moreland736664b2021-05-01 04:27:25 +0000210 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000211 sp<RpcServer> spServer = server.promote();
212 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000213 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
214 }
Steven Moreland736664b2021-05-01 04:27:25 +0000215 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000216 for (auto session : spServer->listSessions()) {
217 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000218 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000219 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000220 return Status::ok();
221 }
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000222 Status getNullBinder(sp<IBinder>* out) override {
223 out->clear();
224 return Status::ok();
225 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000226 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
227 if (binder == nullptr) {
228 std::cout << "Received null binder!" << std::endl;
229 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
230 }
231 *out = binder->pingBinder();
232 return Status::ok();
233 }
234 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
235 *out = binder;
236 return Status::ok();
237 }
238 static sp<IBinder> mHeldBinder;
239 Status holdBinder(const sp<IBinder>& binder) override {
240 mHeldBinder = binder;
241 return Status::ok();
242 }
243 Status getHeldBinder(sp<IBinder>* held) override {
244 *held = mHeldBinder;
245 return Status::ok();
246 }
247 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
248 if (count <= 0) return Status::ok();
249 return binder->nestMe(this, count - 1);
250 }
251 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
252 static sp<IBinder> binder = new BBinder;
253 *out = binder;
254 return Status::ok();
255 }
256 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
257 *out = new MyBinderRpcSession(name);
258 return Status::ok();
259 }
260 Status getNumOpenSessions(int32_t* out) override {
261 *out = MyBinderRpcSession::gNum;
262 return Status::ok();
263 }
264
265 std::mutex blockMutex;
266 Status lock() override {
267 blockMutex.lock();
268 return Status::ok();
269 }
270 Status unlockInMsAsync(int32_t ms) override {
271 usleep(ms * 1000);
272 blockMutex.unlock();
273 return Status::ok();
274 }
275 Status lockUnlock() override {
276 std::lock_guard<std::mutex> _l(blockMutex);
277 return Status::ok();
278 }
279
280 Status sleepMs(int32_t ms) override {
281 usleep(ms * 1000);
282 return Status::ok();
283 }
284
285 Status sleepMsAsync(int32_t ms) override {
286 // In-process binder calls are asynchronous, but the call to this method
287 // is synchronous wrt its client. This in/out-process threading model
288 // diffentiation is a classic binder leaky abstraction (for better or
289 // worse) and is preserved here the way binder sockets plugs itself
290 // into BpBinder, as nothing is changed at the higher levels
291 // (IInterface) which result in this behavior.
292 return sleepMs(ms);
293 }
294
Steven Moreland659416d2021-05-11 00:47:50 +0000295 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
296 const std::string& value) override {
297 if (callback == nullptr) {
298 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
299 }
300
301 if (delayed) {
302 std::thread([=]() {
303 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000304 Status status = doCallback(callback, oneway, false, value);
305 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000306 }).detach();
307 return Status::ok();
308 }
309
310 if (oneway) {
311 return callback->sendOnewayCallback(value);
312 }
313
314 return callback->sendCallback(value);
315 }
316
Steven Morelandc7d40132021-06-10 03:42:11 +0000317 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
318 const std::string& value) override {
319 return doCallback(callback, oneway, delayed, value);
320 }
321
Steven Moreland5553ac42020-11-11 02:14:45 +0000322 Status die(bool cleanup) override {
323 if (cleanup) {
324 exit(1);
325 } else {
326 _exit(1);
327 }
328 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000329
330 Status scheduleShutdown() override {
331 sp<RpcServer> strongServer = server.promote();
332 if (strongServer == nullptr) {
333 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
334 }
335 std::thread([=] {
336 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
337 }).detach();
338 return Status::ok();
339 }
340
Steven Morelandd7302072021-05-15 01:32:04 +0000341 Status useKernelBinderCallingId() override {
342 // this is WRONG! It does not make sense when using RPC binder, and
343 // because it is SO wrong, and so much code calls this, it should abort!
344
345 (void)IPCThreadState::self()->getCallingPid();
346 return Status::ok();
347 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000348
349 Status echoAsFile(const std::string& content, android::os::ParcelFileDescriptor* out) override {
350 out->reset(mockFileDescriptor(content));
351 return Status::ok();
352 }
353
354 Status concatFiles(const std::vector<android::os::ParcelFileDescriptor>& files,
355 android::os::ParcelFileDescriptor* out) override {
356 std::string acc;
357 for (const auto& file : files) {
358 std::string result;
359 CHECK(android::base::ReadFdToString(file.get(), &result));
360 acc.append(result);
361 }
362 out->reset(mockFileDescriptor(acc));
363 return Status::ok();
364 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000365};
366sp<IBinder> MyBinderRpcTest::mHeldBinder;
367
Frederick Maylea12b0962022-06-25 01:13:22 +0000368static std::string WaitStatusToString(int wstatus) {
369 if (WIFEXITED(wstatus)) {
370 return base::StringPrintf("exit status %d", WEXITSTATUS(wstatus));
371 }
372 if (WIFSIGNALED(wstatus)) {
373 return base::StringPrintf("term signal %d", WTERMSIG(wstatus));
374 }
375 return base::StringPrintf("unexpected state %d", wstatus);
376}
377
Steven Moreland5553ac42020-11-11 02:14:45 +0000378class Process {
379public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700380 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700381 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
382 android::base::borrowed_fd /* readEnd */)>& f) {
383 android::base::unique_fd childWriteEnd;
384 android::base::unique_fd childReadEnd;
385 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
386 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000387 if (0 == (mPid = fork())) {
388 // racey: assume parent doesn't crash before this is set
389 prctl(PR_SET_PDEATHSIG, SIGHUP);
390
Yifan Hong1deca4b2021-09-10 16:16:44 -0700391 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000392
393 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000394 }
395 }
396 ~Process() {
397 if (mPid != 0) {
Frederick Maylea12b0962022-06-25 01:13:22 +0000398 int wstatus;
399 waitpid(mPid, &wstatus, 0);
400 if (mCustomExitStatusCheck) {
401 mCustomExitStatusCheck(wstatus);
402 } else {
403 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0)
404 << "server process failed: " << WaitStatusToString(wstatus);
405 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000406 }
407 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700408 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700409 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000410
Frederick Maylea12b0962022-06-25 01:13:22 +0000411 void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
412 mCustomExitStatusCheck = std::move(f);
413 }
414
Frederick Mayle69a0c992022-05-26 20:38:39 +0000415 // Kill the process. Avoid if possible. Shutdown gracefully via an RPC instead.
416 void terminate() { kill(mPid, SIGTERM); }
417
Steven Moreland5553ac42020-11-11 02:14:45 +0000418private:
Frederick Maylea12b0962022-06-25 01:13:22 +0000419 std::function<void(int wstatus)> mCustomExitStatusCheck;
Steven Moreland5553ac42020-11-11 02:14:45 +0000420 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700421 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700422 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000423};
424
425static std::string allocateSocketAddress() {
426 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000427 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700428 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
429 unlink(ret.c_str());
430 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000431};
432
Steven Morelandda573042021-06-12 01:13:45 +0000433static unsigned int allocateVsockPort() {
434 static unsigned int vsockPort = 3456;
435 return vsockPort++;
436}
437
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000438struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000439 // reference to process hosting a socket server
440 Process host;
441
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000442 struct SessionInfo {
443 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000444 sp<IBinder> root;
445 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000446
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000447 // client session objects associated with other process
448 // each one represents a separate session
449 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000450
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000451 ProcessSession(ProcessSession&&) = default;
452 ~ProcessSession() {
453 for (auto& session : sessions) {
454 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000455 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000456
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000457 for (auto& info : sessions) {
458 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000459
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000460 EXPECT_NE(nullptr, session);
461 EXPECT_NE(nullptr, session->state());
462 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000463
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000464 wp<RpcSession> weakSession = session;
465 session = nullptr;
466 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000467 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000468 }
469};
470
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000471// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000472// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000473struct BinderRpcTestProcessSession {
474 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000475
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000476 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000477 sp<IBinder> rootBinder;
478
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000479 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000480 sp<IBinderRpcTest> rootIface;
481
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000482 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000483 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000484
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000485 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
486 ~BinderRpcTestProcessSession() {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000487 if (!expectAlreadyShutdown) {
Frederick Mayle69a0c992022-05-26 20:38:39 +0000488 EXPECT_NE(nullptr, rootIface);
489 if (rootIface == nullptr) return;
490
Steven Moreland736664b2021-05-01 04:27:25 +0000491 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000492 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000493 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000494 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000495 for (auto remoteCount : remoteCounts) {
496 EXPECT_EQ(remoteCount, 1);
497 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000498
Steven Moreland798e0d12021-07-14 23:19:25 +0000499 // even though it is on another thread, shutdown races with
500 // the transaction reply being written
501 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
502 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
503 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000504 }
505
506 rootIface = nullptr;
507 rootBinder = nullptr;
508 }
509};
510
Steven Morelandc1635952021-04-01 16:20:47 +0000511enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700512 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000513 UNIX,
514 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700515 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000516};
Yifan Hong702115c2021-06-24 15:39:18 -0700517static inline std::string PrintToString(SocketType socketType) {
518 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700519 case SocketType::PRECONNECTED:
520 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000521 case SocketType::UNIX:
522 return "unix_domain_socket";
523 case SocketType::VSOCK:
524 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700525 case SocketType::INET:
526 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000527 default:
528 LOG_ALWAYS_FATAL("Unknown socket type");
529 return "";
530 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000531}
Steven Morelandda573042021-06-12 01:13:45 +0000532
Yifan Hong1deca4b2021-09-10 16:16:44 -0700533static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700534 base::unique_fd serverFd(
535 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
536 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700537 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
538 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700539
540 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
541 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700542 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
543 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700544 }
545 return serverFd;
546}
547
Frederick Mayledc07cf82022-05-26 20:30:12 +0000548class BinderRpc
549 : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity, uint32_t, uint32_t>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000550public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000551 struct Options {
552 size_t numThreads = 1;
553 size_t numSessions = 1;
554 size_t numIncomingConnections = 0;
Yifan Hong1f44f982021-10-08 17:16:47 -0700555 size_t numOutgoingConnections = SIZE_MAX;
Frederick Mayle69a0c992022-05-26 20:38:39 +0000556 RpcSession::FileDescriptorTransportMode clientFileDescriptorTransportMode =
557 RpcSession::FileDescriptorTransportMode::NONE;
558 std::vector<RpcSession::FileDescriptorTransportMode>
559 serverSupportedFileDescriptorTransportModes = {
560 RpcSession::FileDescriptorTransportMode::NONE};
561
562 // If true, connection failures will result in `ProcessSession::sessions` being empty
563 // instead of a fatal error.
564 bool allowConnectFailure = false;
Steven Moreland4313d7e2021-07-15 23:41:22 +0000565 };
566
Frederick Mayle69a0c992022-05-26 20:38:39 +0000567 SocketType socketType() const { return std::get<0>(GetParam()); }
568 RpcSecurity rpcSecurity() const { return std::get<1>(GetParam()); }
569 uint32_t clientVersion() const { return std::get<2>(GetParam()); }
570 uint32_t serverVersion() const { return std::get<3>(GetParam()); }
571
572 // Whether the test params support sending FDs in parcels.
573 bool supportsFdTransport() const {
574 return clientVersion() >= 1 && serverVersion() >= 1 && rpcSecurity() != RpcSecurity::TLS &&
575 (socketType() == SocketType::PRECONNECTED || socketType() == SocketType::UNIX);
576 }
577
Yifan Hong702115c2021-06-24 15:39:18 -0700578 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000579 auto [type, security, clientVersion, serverVersion] = info.param;
580 return PrintToString(type) + "_" + newFactory(security)->toCString() + "_clientV" +
581 std::to_string(clientVersion) + "_serverV" + std::to_string(serverVersion);
Yifan Hong702115c2021-06-24 15:39:18 -0700582 }
583
Yifan Hong1deca4b2021-09-10 16:16:44 -0700584 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
585 uint64_t length = str.length();
586 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
587 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
588 }
589
590 static inline std::string readString(android::base::borrowed_fd fd) {
591 uint64_t length;
592 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
593 std::string ret(length, '\0');
594 CHECK(android::base::ReadFully(fd, ret.data(), length));
595 return ret;
596 }
597
598 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
599 Parcel parcel;
600 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
601 writeString(fd,
602 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
603 }
604
605 template <typename T>
606 static inline T readFromFd(android::base::borrowed_fd fd) {
607 std::string data = readString(fd);
608 Parcel parcel;
609 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
610 T object;
611 CHECK_EQ(OK, object.readFromParcel(&parcel));
612 return object;
613 }
614
Steven Morelandc1635952021-04-01 16:20:47 +0000615 // This creates a new process serving an interface on a certain number of
616 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000617 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000618 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
619 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000620
Yifan Hong702115c2021-06-24 15:39:18 -0700621 SocketType socketType = std::get<0>(GetParam());
622 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Frederick Mayledc07cf82022-05-26 20:30:12 +0000623 uint32_t clientVersion = std::get<2>(GetParam());
624 uint32_t serverVersion = std::get<3>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000625
Steven Morelandda573042021-06-12 01:13:45 +0000626 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000627 std::string addr = allocateSocketAddress();
Steven Morelandc1635952021-04-01 16:20:47 +0000628
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000629 auto ret = ProcessSession{
Frederick Mayledc07cf82022-05-26 20:30:12 +0000630 .host = Process([=](android::base::borrowed_fd writeEnd,
Yifan Hong1deca4b2021-09-10 16:16:44 -0700631 android::base::borrowed_fd readEnd) {
632 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
633 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
Steven Morelandc1635952021-04-01 16:20:47 +0000634
Frederick Mayledc07cf82022-05-26 20:30:12 +0000635 server->setProtocolVersion(serverVersion);
Steven Moreland4313d7e2021-07-15 23:41:22 +0000636 server->setMaxThreads(options.numThreads);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000637 server->setSupportedFileDescriptorTransportModes(
638 options.serverSupportedFileDescriptorTransportModes);
Steven Morelandc1635952021-04-01 16:20:47 +0000639
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000640 unsigned int outPort = 0;
641
Steven Morelandc1635952021-04-01 16:20:47 +0000642 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700643 case SocketType::PRECONNECTED:
644 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000645 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700646 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000647 break;
648 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700649 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000650 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700651 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700652 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700653 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700654 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700655 }
Steven Morelandc1635952021-04-01 16:20:47 +0000656 default:
657 LOG_ALWAYS_FATAL("Unknown socket type");
658 }
659
Yifan Hong1deca4b2021-09-10 16:16:44 -0700660 BinderRpcTestServerInfo serverInfo;
661 serverInfo.port = static_cast<int64_t>(outPort);
Yifan Hong9734cfc2021-09-13 16:14:09 -0700662 serverInfo.cert.data = server->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700663 writeToFd(writeEnd, serverInfo);
664 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
665
666 if (rpcSecurity == RpcSecurity::TLS) {
667 for (const auto& clientCert : clientInfo.certs) {
668 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700669 certVerifier
670 ->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
671 clientCert.data));
Yifan Hong1deca4b2021-09-10 16:16:44 -0700672 }
673 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000674
Steven Moreland611d15f2021-05-01 01:28:27 +0000675 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000676
Steven Morelandf137de92021-04-24 01:54:26 +0000677 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000678
679 // Another thread calls shutdown. Wait for it to complete.
680 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000681 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000682 };
683
Yifan Hong1deca4b2021-09-10 16:16:44 -0700684 std::vector<sp<RpcSession>> sessions;
685 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
686 for (size_t i = 0; i < options.numSessions; i++) {
687 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
688 }
689
690 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
691 BinderRpcTestClientInfo clientInfo;
692 for (const auto& session : sessions) {
693 auto& parcelableCert = clientInfo.certs.emplace_back();
Yifan Hong9734cfc2021-09-13 16:14:09 -0700694 parcelableCert.data = session->getCertificate(RpcCertificateFormat::PEM);
Yifan Hong1deca4b2021-09-10 16:16:44 -0700695 }
696 writeToFd(ret.host.writeEnd(), clientInfo);
697
698 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700699 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700700 CHECK_NE(0, serverInfo.port);
701 }
702
703 if (rpcSecurity == RpcSecurity::TLS) {
704 const auto& serverCert = serverInfo.cert.data;
705 CHECK_EQ(OK,
Yifan Hong9734cfc2021-09-13 16:14:09 -0700706 certVerifier->addTrustedPeerCertificate(RpcCertificateFormat::PEM,
707 serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700708 }
709
Steven Moreland2372f9d2021-08-05 15:42:01 -0700710 status_t status;
711
Yifan Hong1deca4b2021-09-10 16:16:44 -0700712 for (const auto& session : sessions) {
Frederick Mayledc07cf82022-05-26 20:30:12 +0000713 CHECK(session->setProtocolVersion(clientVersion));
Yifan Hong10423062021-10-08 16:26:32 -0700714 session->setMaxIncomingThreads(options.numIncomingConnections);
Yifan Hong1f44f982021-10-08 17:16:47 -0700715 session->setMaxOutgoingThreads(options.numOutgoingConnections);
Frederick Mayle69a0c992022-05-26 20:38:39 +0000716 session->setFileDescriptorTransportMode(options.clientFileDescriptorTransportMode);
Steven Moreland659416d2021-05-11 00:47:50 +0000717
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000718 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700719 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700720 status = session->setupPreconnectedClient({}, [=]() {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700721 return connectTo(UnixSocketAddress(addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700722 });
Steven Moreland4198a122021-08-03 17:37:58 -0700723 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000724 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700725 status = session->setupUnixDomainClient(addr.c_str());
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000726 break;
727 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700728 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000729 break;
730 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700731 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000732 break;
733 default:
734 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000735 }
Frederick Mayle69a0c992022-05-26 20:38:39 +0000736 if (options.allowConnectFailure && status != OK) {
737 ret.sessions.clear();
738 break;
739 }
Steven Moreland8a1a47d2021-09-14 10:54:04 -0700740 CHECK_EQ(status, OK) << "Could not connect: " << statusToString(status);
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000741 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000742 }
Steven Morelandc1635952021-04-01 16:20:47 +0000743 return ret;
744 }
745
Steven Moreland4313d7e2021-07-15 23:41:22 +0000746 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000747 BinderRpcTestProcessSession ret{
Steven Moreland51c44a92021-10-14 16:50:35 -0700748 .proc = createRpcTestSocketServerProcess(
749 options,
750 [&](const sp<RpcServer>& server) {
Andrei Homescu86124ca2022-04-21 22:22:48 +0000751 server->setPerSessionRootObject([&](const void* addrPtr, size_t len) {
752 // UNIX sockets with abstract addresses return
753 // sizeof(sa_family_t)==2 in addrlen
754 CHECK_GE(len, sizeof(sa_family_t));
755 const sockaddr* addr = reinterpret_cast<const sockaddr*>(addrPtr);
Steven Moreland51c44a92021-10-14 16:50:35 -0700756 sp<MyBinderRpcTest> service = sp<MyBinderRpcTest>::make();
757 switch (addr->sa_family) {
758 case AF_UNIX:
759 // nothing to save
760 break;
761 case AF_VSOCK:
762 CHECK_EQ(len, sizeof(sockaddr_vm));
763 service->port = reinterpret_cast<const sockaddr_vm*>(addr)
764 ->svm_port;
765 break;
766 case AF_INET:
767 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700768 service->port =
769 ntohs(reinterpret_cast<const sockaddr_in*>(addr)
770 ->sin_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700771 break;
772 case AF_INET6:
773 CHECK_EQ(len, sizeof(sockaddr_in));
Steven Moreland6a0dc962021-10-25 15:35:43 -0700774 service->port =
775 ntohs(reinterpret_cast<const sockaddr_in6*>(addr)
776 ->sin6_port);
Steven Moreland51c44a92021-10-14 16:50:35 -0700777 break;
778 default:
779 LOG_ALWAYS_FATAL("Unrecognized address family %d",
780 addr->sa_family);
781 }
782 service->server = server;
783 return service;
784 });
785 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000786 };
787
Frederick Mayle69a0c992022-05-26 20:38:39 +0000788 ret.rootBinder = ret.proc.sessions.empty() ? nullptr : ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000789 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
790
791 return ret;
792 }
Yifan Hong1f44f982021-10-08 17:16:47 -0700793
794 void testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
795 size_t sleepMs = 500);
Steven Morelandc1635952021-04-01 16:20:47 +0000796};
797
Steven Morelandc1635952021-04-01 16:20:47 +0000798TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000799 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000800 ASSERT_NE(proc.rootBinder, nullptr);
801 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
802}
803
Steven Moreland4cf688f2021-03-31 01:48:58 +0000804TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000805 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000806 ASSERT_NE(proc.rootBinder, nullptr);
807 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
808}
809
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000810TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000811 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000812 for (auto session : proc.proc.sessions) {
813 ASSERT_NE(nullptr, session.root);
814 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000815 }
816}
817
Steven Moreland51c44a92021-10-14 16:50:35 -0700818TEST_P(BinderRpc, SeparateRootObject) {
819 SocketType type = std::get<0>(GetParam());
820 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX) {
821 // we can't get port numbers for unix sockets
822 return;
823 }
824
825 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
826
827 int port1 = 0;
828 EXPECT_OK(proc.rootIface->getClientPort(&port1));
829
830 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
831 int port2;
832 EXPECT_OK(rootIface2->getClientPort(&port2));
833
834 // we should have a different IBinderRpcTest object created for each
835 // session, because we use setPerSessionRootObject
836 EXPECT_NE(port1, port2);
837}
838
Steven Morelandc1635952021-04-01 16:20:47 +0000839TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000840 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000841 Parcel data;
842 Parcel reply;
843 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
844}
845
Steven Moreland67753c32021-04-02 18:45:19 +0000846TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland2034eff2021-10-13 11:24:35 -0700847 auto proc1 = createRpcTestSocketServerProcess({});
848 auto proc2 = createRpcTestSocketServerProcess({});
849
850 Parcel pRaw;
Steven Moreland67753c32021-04-02 18:45:19 +0000851
852 Parcel p1;
Steven Moreland2034eff2021-10-13 11:24:35 -0700853 p1.markForBinder(proc1.rootBinder);
Steven Moreland67753c32021-04-02 18:45:19 +0000854 p1.writeInt32(3);
855
Frederick Maylea4ed5672022-06-17 22:03:38 +0000856 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
Steven Moreland2034eff2021-10-13 11:24:35 -0700857 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
858
Steven Moreland67753c32021-04-02 18:45:19 +0000859 Parcel p2;
Steven Moreland2034eff2021-10-13 11:24:35 -0700860 p2.markForBinder(proc2.rootBinder);
861 p2.writeInt32(7);
Steven Moreland67753c32021-04-02 18:45:19 +0000862
863 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
864 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
865}
866
Steven Morelandc1635952021-04-01 16:20:47 +0000867TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000868 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000869 Parcel data;
870 data.markForBinder(proc.rootBinder);
871 Parcel reply;
872 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
873}
874
Steven Morelandc1635952021-04-01 16:20:47 +0000875TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000876 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000877 EXPECT_OK(proc.rootIface->sendString("asdf"));
878}
879
Steven Morelandc1635952021-04-01 16:20:47 +0000880TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000881 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000882 std::string doubled;
883 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
884 EXPECT_EQ("cool cool ", doubled);
885}
886
Steven Morelandc1635952021-04-01 16:20:47 +0000887TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000888 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000889 std::string single = std::string(1024, 'a');
890 std::string doubled;
891 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
892 EXPECT_EQ(single + single, doubled);
893}
894
Frederick Mayleae9deeb2022-06-23 23:42:08 +0000895TEST_P(BinderRpc, InvalidNullBinderReturn) {
896 auto proc = createRpcTestSocketServerProcess({});
897
898 sp<IBinder> outBinder;
899 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
900}
901
Steven Morelandc1635952021-04-01 16:20:47 +0000902TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000903 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000904
905 int32_t pingResult;
906 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
907 EXPECT_EQ(OK, pingResult);
908
909 EXPECT_EQ(0, MyBinderRpcSession::gNum);
910}
911
Steven Morelandc1635952021-04-01 16:20:47 +0000912TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000913 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000914
915 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
916 sp<IBinder> outBinder;
917 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
918 EXPECT_EQ(inBinder, outBinder);
919
920 wp<IBinder> weak = inBinder;
921 inBinder = nullptr;
922 outBinder = nullptr;
923
924 // Force reading a reply, to process any pending dec refs from the other
925 // process (the other process will process dec refs there before processing
926 // the ping here).
927 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
928
929 EXPECT_EQ(nullptr, weak.promote());
930
931 EXPECT_EQ(0, MyBinderRpcSession::gNum);
932}
933
Steven Morelandc1635952021-04-01 16:20:47 +0000934TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000935 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000936
937 sp<IBinderRpcSession> session;
938 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
939
940 sp<IBinder> inBinder = IInterface::asBinder(session);
941 sp<IBinder> outBinder;
942 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
943 EXPECT_EQ(inBinder, outBinder);
944
945 wp<IBinder> weak = inBinder;
946 session = nullptr;
947 inBinder = nullptr;
948 outBinder = nullptr;
949
950 // Force reading a reply, to process any pending dec refs from the other
951 // process (the other process will process dec refs there before processing
952 // the ping here).
953 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
954
955 EXPECT_EQ(nullptr, weak.promote());
956}
957
Steven Morelandc1635952021-04-01 16:20:47 +0000958TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000959 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000960
961 sp<IBinder> outBinder;
962 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
963 EXPECT_EQ(nullptr, outBinder);
964}
965
Steven Morelandc1635952021-04-01 16:20:47 +0000966TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000967 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000968
969 IBinder* ptr = nullptr;
970 {
971 sp<IBinder> binder = new BBinder();
972 ptr = binder.get();
973 EXPECT_OK(proc.rootIface->holdBinder(binder));
974 }
975
976 sp<IBinder> held;
977 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
978
979 EXPECT_EQ(held.get(), ptr);
980
981 // stop holding binder, because we test to make sure references are cleaned
982 // up
983 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
984 // and flush ref counts
985 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
986}
987
988// START TESTS FOR LIMITATIONS OF SOCKET BINDER
989// These are behavioral differences form regular binder, where certain usecases
990// aren't supported.
991
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000992TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000993 auto proc1 = createRpcTestSocketServerProcess({});
994 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000995
996 sp<IBinder> outBinder;
997 EXPECT_EQ(INVALID_OPERATION,
998 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
999}
1000
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001001TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001002 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +00001003
1004 sp<IBinder> outBinder;
1005 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +00001006 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +00001007 .transactionError());
1008}
1009
Steven Morelandc1635952021-04-01 16:20:47 +00001010TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001011 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001012
1013 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
1014 sp<IBinder> outBinder;
1015 EXPECT_EQ(INVALID_OPERATION,
1016 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
1017}
1018
Steven Morelandc1635952021-04-01 16:20:47 +00001019TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001020 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001021
1022 // for historical reasons, IServiceManager interface only returns the
1023 // exception code
1024 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
1025 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
1026}
1027
1028// END TESTS FOR LIMITATIONS OF SOCKET BINDER
1029
Steven Morelandc1635952021-04-01 16:20:47 +00001030TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001031 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001032
1033 sp<IBinder> outBinder;
1034 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
1035 EXPECT_EQ(proc.rootBinder, outBinder);
1036}
1037
Steven Morelandc1635952021-04-01 16:20:47 +00001038TEST_P(BinderRpc, NestedTransactions) {
Frederick Mayle69a0c992022-05-26 20:38:39 +00001039 auto proc = createRpcTestSocketServerProcess({
1040 // Enable FD support because it uses more stack space and so represents
1041 // something closer to a worst case scenario.
1042 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1043 .serverSupportedFileDescriptorTransportModes =
1044 {RpcSession::FileDescriptorTransportMode::UNIX},
1045 });
Steven Moreland5553ac42020-11-11 02:14:45 +00001046
1047 auto nastyNester = sp<MyBinderRpcTest>::make();
1048 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
1049
1050 wp<IBinder> weak = nastyNester;
1051 nastyNester = nullptr;
1052 EXPECT_EQ(nullptr, weak.promote());
1053}
1054
Steven Morelandc1635952021-04-01 16:20:47 +00001055TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001056 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001057
1058 sp<IBinder> a;
1059 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
1060
1061 sp<IBinder> b;
1062 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
1063
1064 EXPECT_EQ(a, b);
1065}
1066
Steven Morelandc1635952021-04-01 16:20:47 +00001067TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001068 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001069
1070 sp<IBinder> a;
1071 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
1072 wp<IBinder> weak = a;
1073 a = nullptr;
1074
1075 sp<IBinder> b;
1076 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
1077
1078 // this is the wrong behavior, since BpBinder
1079 // doesn't implement onIncStrongAttempted
1080 // but make sure there is no crash
1081 EXPECT_EQ(nullptr, weak.promote());
1082
1083 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
1084
1085 // In order to fix this:
1086 // - need to have incStrongAttempted reflected across IPC boundary (wait for
1087 // response to promote - round trip...)
1088 // - sendOnLastWeakRef, to delete entries out of RpcState table
1089 EXPECT_EQ(b, weak.promote());
1090}
1091
1092#define expectSessions(expected, iface) \
1093 do { \
1094 int session; \
1095 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
1096 EXPECT_EQ(expected, session); \
1097 } while (false)
1098
Steven Morelandc1635952021-04-01 16:20:47 +00001099TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001100 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001101
1102 sp<IBinderRpcSession> session;
1103 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
1104 std::string out;
1105 EXPECT_OK(session->getName(&out));
1106 EXPECT_EQ("aoeu", out);
1107
1108 expectSessions(1, proc.rootIface);
1109 session = nullptr;
1110 expectSessions(0, proc.rootIface);
1111}
1112
Steven Morelandc1635952021-04-01 16:20:47 +00001113TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001114 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001115
1116 std::vector<sp<IBinderRpcSession>> sessions;
1117
1118 for (size_t i = 0; i < 15; i++) {
1119 expectSessions(i, proc.rootIface);
1120 sp<IBinderRpcSession> session;
1121 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
1122 sessions.push_back(session);
1123 }
1124 expectSessions(sessions.size(), proc.rootIface);
1125 for (size_t i = 0; i < sessions.size(); i++) {
1126 std::string out;
1127 EXPECT_OK(sessions.at(i)->getName(&out));
1128 EXPECT_EQ(std::to_string(i), out);
1129 }
1130 expectSessions(sessions.size(), proc.rootIface);
1131
1132 while (!sessions.empty()) {
1133 sessions.pop_back();
1134 expectSessions(sessions.size(), proc.rootIface);
1135 }
1136 expectSessions(0, proc.rootIface);
1137}
1138
1139size_t epochMillis() {
1140 using std::chrono::duration_cast;
1141 using std::chrono::milliseconds;
1142 using std::chrono::seconds;
1143 using std::chrono::system_clock;
1144 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1145}
1146
Steven Morelandc1635952021-04-01 16:20:47 +00001147TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001148 constexpr size_t kNumThreads = 10;
1149
Steven Moreland4313d7e2021-07-15 23:41:22 +00001150 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001151
1152 EXPECT_OK(proc.rootIface->lock());
1153
1154 // block all but one thread taking locks
1155 std::vector<std::thread> ts;
1156 for (size_t i = 0; i < kNumThreads - 1; i++) {
1157 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
1158 }
1159
1160 usleep(100000); // give chance for calls on other threads
1161
1162 // other calls still work
1163 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1164
1165 constexpr size_t blockTimeMs = 500;
1166 size_t epochMsBefore = epochMillis();
1167 // after this, we should never see a response within this time
1168 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
1169
1170 // this call should be blocked for blockTimeMs
1171 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
1172
1173 size_t epochMsAfter = epochMillis();
1174 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
1175
1176 for (auto& t : ts) t.join();
1177}
1178
Yifan Hong1f44f982021-10-08 17:16:47 -07001179void BinderRpc::testThreadPoolOverSaturated(sp<IBinderRpcTest> iface, size_t numCalls,
1180 size_t sleepMs) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001181 size_t epochMsBefore = epochMillis();
1182
1183 std::vector<std::thread> ts;
Yifan Hong1f44f982021-10-08 17:16:47 -07001184 for (size_t i = 0; i < numCalls; i++) {
1185 ts.push_back(std::thread([&] { iface->sleepMs(sleepMs); }));
Steven Moreland5553ac42020-11-11 02:14:45 +00001186 }
1187
1188 for (auto& t : ts) t.join();
1189
1190 size_t epochMsAfter = epochMillis();
1191
Yifan Hong1f44f982021-10-08 17:16:47 -07001192 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * sleepMs);
Steven Moreland5553ac42020-11-11 02:14:45 +00001193
1194 // Potential flake, but make sure calls are handled in parallel.
Yifan Hong1f44f982021-10-08 17:16:47 -07001195 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * sleepMs);
1196}
1197
1198TEST_P(BinderRpc, ThreadPoolOverSaturated) {
1199 constexpr size_t kNumThreads = 10;
1200 constexpr size_t kNumCalls = kNumThreads + 3;
1201 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
1202 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
1203}
1204
1205TEST_P(BinderRpc, ThreadPoolLimitOutgoing) {
1206 constexpr size_t kNumThreads = 20;
1207 constexpr size_t kNumOutgoingConnections = 10;
1208 constexpr size_t kNumCalls = kNumOutgoingConnections + 3;
1209 auto proc = createRpcTestSocketServerProcess(
1210 {.numThreads = kNumThreads, .numOutgoingConnections = kNumOutgoingConnections});
1211 testThreadPoolOverSaturated(proc.rootIface, kNumCalls);
Steven Moreland5553ac42020-11-11 02:14:45 +00001212}
1213
Steven Morelandc1635952021-04-01 16:20:47 +00001214TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001215 constexpr size_t kNumClientThreads = 10;
1216 constexpr size_t kNumServerThreads = 10;
1217 constexpr size_t kNumCalls = 100;
1218
Steven Moreland4313d7e2021-07-15 23:41:22 +00001219 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001220
1221 std::vector<std::thread> threads;
1222 for (size_t i = 0; i < kNumClientThreads; i++) {
1223 threads.push_back(std::thread([&] {
1224 for (size_t j = 0; j < kNumCalls; j++) {
1225 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001226 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001227 EXPECT_EQ(proc.rootBinder, out);
1228 }
1229 }));
1230 }
1231
1232 for (auto& t : threads) t.join();
1233}
1234
Steven Moreland925ba0a2021-09-17 18:06:32 -07001235static void saturateThreadPool(size_t threadCount, const sp<IBinderRpcTest>& iface) {
1236 std::vector<std::thread> threads;
1237 for (size_t i = 0; i < threadCount; i++) {
1238 threads.push_back(std::thread([&] { EXPECT_OK(iface->sleepMs(500)); }));
1239 }
1240 for (auto& t : threads) t.join();
1241}
1242
Steven Morelandc6046982021-04-20 00:49:42 +00001243TEST_P(BinderRpc, OnewayStressTest) {
1244 constexpr size_t kNumClientThreads = 10;
1245 constexpr size_t kNumServerThreads = 10;
Steven Moreland3c3ab8d2021-09-23 10:29:50 -07001246 constexpr size_t kNumCalls = 1000;
Steven Morelandc6046982021-04-20 00:49:42 +00001247
Steven Moreland4313d7e2021-07-15 23:41:22 +00001248 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001249
1250 std::vector<std::thread> threads;
1251 for (size_t i = 0; i < kNumClientThreads; i++) {
1252 threads.push_back(std::thread([&] {
1253 for (size_t j = 0; j < kNumCalls; j++) {
1254 EXPECT_OK(proc.rootIface->sendString("a"));
1255 }
Steven Morelandc6046982021-04-20 00:49:42 +00001256 }));
1257 }
1258
1259 for (auto& t : threads) t.join();
Steven Moreland925ba0a2021-09-17 18:06:32 -07001260
1261 saturateThreadPool(kNumServerThreads, proc.rootIface);
Steven Morelandc6046982021-04-20 00:49:42 +00001262}
1263
Steven Morelandc1635952021-04-01 16:20:47 +00001264TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001265 constexpr size_t kReallyLongTimeMs = 100;
1266 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1267
Steven Moreland4313d7e2021-07-15 23:41:22 +00001268 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001269
1270 size_t epochMsBefore = epochMillis();
1271
1272 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1273
1274 size_t epochMsAfter = epochMillis();
1275 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1276}
1277
Steven Morelandc1635952021-04-01 16:20:47 +00001278TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001279 constexpr size_t kNumSleeps = 10;
1280 constexpr size_t kNumExtraServerThreads = 4;
1281 constexpr size_t kSleepMs = 50;
1282
1283 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001284 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001285
1286 EXPECT_OK(proc.rootIface->lock());
1287
Steven Moreland1c678802021-09-17 16:48:47 -07001288 size_t epochMsBefore = epochMillis();
1289
1290 // all these *Async commands should be queued on the server sequentially,
1291 // even though there are multiple threads.
1292 for (size_t i = 0; i + 1 < kNumSleeps; i++) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001293 proc.rootIface->sleepMsAsync(kSleepMs);
1294 }
Steven Moreland5553ac42020-11-11 02:14:45 +00001295 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1296
Steven Moreland1c678802021-09-17 16:48:47 -07001297 // this can only return once the final async call has unlocked
Steven Moreland5553ac42020-11-11 02:14:45 +00001298 EXPECT_OK(proc.rootIface->lockUnlock());
Steven Moreland1c678802021-09-17 16:48:47 -07001299
Steven Moreland5553ac42020-11-11 02:14:45 +00001300 size_t epochMsAfter = epochMillis();
1301
1302 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001303
Steven Moreland925ba0a2021-09-17 18:06:32 -07001304 saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface);
Steven Moreland5553ac42020-11-11 02:14:45 +00001305}
1306
Steven Morelandd45be622021-06-04 02:19:37 +00001307TEST_P(BinderRpc, OnewayCallExhaustion) {
1308 constexpr size_t kNumClients = 2;
1309 constexpr size_t kTooLongMs = 1000;
1310
Steven Moreland4313d7e2021-07-15 23:41:22 +00001311 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001312
1313 // Build up oneway calls on the second session to make sure it terminates
1314 // and shuts down. The first session should be unaffected (proc destructor
1315 // checks the first session).
1316 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1317
1318 std::vector<std::thread> threads;
1319 for (size_t i = 0; i < kNumClients; i++) {
1320 // one of these threads will get stuck queueing a transaction once the
1321 // socket fills up, the other will be able to fill up transactions on
1322 // this object
1323 threads.push_back(std::thread([&] {
1324 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1325 }
1326 }));
1327 }
1328 for (auto& t : threads) t.join();
1329
1330 Status status = iface->sleepMsAsync(kTooLongMs);
1331 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1332
Steven Moreland798e0d12021-07-14 23:19:25 +00001333 // now that it has died, wait for the remote session to shutdown
1334 std::vector<int32_t> remoteCounts;
1335 do {
1336 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1337 } while (remoteCounts.size() == kNumClients);
1338
Steven Morelandd45be622021-06-04 02:19:37 +00001339 // the second session should be shutdown in the other process by the time we
1340 // are able to join above (it'll only be hung up once it finishes processing
1341 // any pending commands). We need to erase this session from the record
1342 // here, so that the destructor for our session won't check that this
1343 // session is valid, but we still want it to test the other session.
1344 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1345}
1346
Steven Moreland659416d2021-05-11 00:47:50 +00001347TEST_P(BinderRpc, Callbacks) {
1348 const static std::string kTestString = "good afternoon!";
1349
Steven Morelandc7d40132021-06-10 03:42:11 +00001350 for (bool callIsOneway : {true, false}) {
1351 for (bool callbackIsOneway : {true, false}) {
1352 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001353 auto proc = createRpcTestSocketServerProcess(
1354 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001355 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001356
Steven Morelandc7d40132021-06-10 03:42:11 +00001357 if (callIsOneway) {
1358 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1359 kTestString));
1360 } else {
1361 EXPECT_OK(
1362 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1363 }
Steven Moreland659416d2021-05-11 00:47:50 +00001364
Steven Moreland03ecce62022-05-13 23:22:05 +00001365 // if both transactions are synchronous and the response is sent back on the
1366 // same thread, everything should have happened in a nested call. Otherwise,
1367 // the callback will be processed on another thread.
1368 if (callIsOneway || callbackIsOneway || delayed) {
1369 using std::literals::chrono_literals::operator""s;
1370 std::unique_lock<std::mutex> _l(cb->mMutex);
1371 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
1372 }
Steven Moreland659416d2021-05-11 00:47:50 +00001373
Steven Morelandc7d40132021-06-10 03:42:11 +00001374 EXPECT_EQ(cb->mValues.size(), 1)
1375 << "callIsOneway: " << callIsOneway
1376 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1377 if (cb->mValues.empty()) continue;
1378 EXPECT_EQ(cb->mValues.at(0), kTestString)
1379 << "callIsOneway: " << callIsOneway
1380 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001381
Steven Morelandc7d40132021-06-10 03:42:11 +00001382 // since we are severing the connection, we need to go ahead and
1383 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001384 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1385 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1386 }
Steven Moreland659416d2021-05-11 00:47:50 +00001387
Steven Moreland1b304292021-07-15 22:59:34 +00001388 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001389 // need to manually shut it down
1390 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001391
Frederick Maylea12b0962022-06-25 01:13:22 +00001392 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1393 // Flaky. Sometimes gets SIGABRT.
1394 EXPECT_TRUE((WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 0) ||
1395 (WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT))
1396 << "server process failed: " << WaitStatusToString(wstatus);
1397 });
Steven Morelandc7d40132021-06-10 03:42:11 +00001398 proc.expectAlreadyShutdown = true;
1399 }
Steven Moreland659416d2021-05-11 00:47:50 +00001400 }
1401 }
1402}
1403
Steven Moreland195edb82021-06-08 02:44:39 +00001404TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001405 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001406 auto cb = sp<MyBinderRpcCallback>::make();
1407
1408 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1409 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1410}
1411
Steven Morelandc1635952021-04-01 16:20:47 +00001412TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001413 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001414 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001415
1416 // make sure there is some state during crash
1417 // 1. we hold their binder
1418 sp<IBinderRpcSession> session;
1419 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1420 // 2. they hold our binder
1421 sp<IBinder> binder = new BBinder();
1422 EXPECT_OK(proc.rootIface->holdBinder(binder));
1423
1424 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1425 << "Do death cleanup: " << doDeathCleanup;
1426
Frederick Maylea12b0962022-06-25 01:13:22 +00001427 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1428 EXPECT_TRUE(WIFEXITED(wstatus) && WEXITSTATUS(wstatus) == 1)
1429 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1430 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001431 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001432 }
1433}
1434
Steven Morelandd7302072021-05-15 01:32:04 +00001435TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Morelanda83191d2021-10-27 10:14:53 -07001436 bool okToFork = ProcessState::selfOrNull() == nullptr;
1437
Steven Moreland4313d7e2021-07-15 23:41:22 +00001438 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001439
Steven Morelanda83191d2021-10-27 10:14:53 -07001440 // If this process has used ProcessState already, then the forked process
1441 // cannot use it at all. If this process hasn't used it (depending on the
1442 // order tests are run), then the forked process can use it, and we'll only
1443 // catch the invalid usage the second time. Such is the burden of global
1444 // state!
1445 if (okToFork) {
1446 // we can't allocate IPCThreadState so actually the first time should
1447 // succeed :(
1448 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1449 }
Steven Morelandd7302072021-05-15 01:32:04 +00001450
1451 // second time! we catch the error :)
1452 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1453
Frederick Maylea12b0962022-06-25 01:13:22 +00001454 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1455 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGABRT)
1456 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1457 });
Steven Morelandaf4ca712021-05-24 23:22:08 +00001458 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001459}
1460
Frederick Mayle69a0c992022-05-26 20:38:39 +00001461TEST_P(BinderRpc, FileDescriptorTransportRejectNone) {
1462 auto proc = createRpcTestSocketServerProcess({
1463 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1464 .serverSupportedFileDescriptorTransportModes =
1465 {RpcSession::FileDescriptorTransportMode::UNIX},
1466 .allowConnectFailure = true,
1467 });
1468 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1469 proc.proc.host.terminate();
1470 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1471 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1472 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1473 });
1474 proc.expectAlreadyShutdown = true;
1475}
1476
1477TEST_P(BinderRpc, FileDescriptorTransportRejectUnix) {
1478 auto proc = createRpcTestSocketServerProcess({
1479 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1480 .serverSupportedFileDescriptorTransportModes =
1481 {RpcSession::FileDescriptorTransportMode::NONE},
1482 .allowConnectFailure = true,
1483 });
1484 EXPECT_TRUE(proc.proc.sessions.empty()) << "session connections should have failed";
1485 proc.proc.host.terminate();
1486 proc.proc.host.setCustomExitStatusCheck([](int wstatus) {
1487 EXPECT_TRUE(WIFSIGNALED(wstatus) && WTERMSIG(wstatus) == SIGTERM)
1488 << "server process failed incorrectly: " << WaitStatusToString(wstatus);
1489 });
1490 proc.expectAlreadyShutdown = true;
1491}
1492
1493TEST_P(BinderRpc, FileDescriptorTransportOptionalUnix) {
1494 auto proc = createRpcTestSocketServerProcess({
1495 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::NONE,
1496 .serverSupportedFileDescriptorTransportModes =
1497 {RpcSession::FileDescriptorTransportMode::NONE,
1498 RpcSession::FileDescriptorTransportMode::UNIX},
1499 });
1500
1501 android::os::ParcelFileDescriptor out;
1502 auto status = proc.rootIface->echoAsFile("hello", &out);
1503 EXPECT_EQ(status.transactionError(), FDS_NOT_ALLOWED) << status;
1504}
1505
1506TEST_P(BinderRpc, ReceiveFile) {
1507 auto proc = createRpcTestSocketServerProcess({
1508 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1509 .serverSupportedFileDescriptorTransportModes =
1510 {RpcSession::FileDescriptorTransportMode::UNIX},
1511 });
1512
1513 android::os::ParcelFileDescriptor out;
1514 auto status = proc.rootIface->echoAsFile("hello", &out);
1515 if (!supportsFdTransport()) {
1516 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1517 return;
1518 }
1519 ASSERT_TRUE(status.isOk()) << status;
1520
1521 std::string result;
1522 CHECK(android::base::ReadFdToString(out.get(), &result));
1523 EXPECT_EQ(result, "hello");
1524}
1525
1526TEST_P(BinderRpc, SendFiles) {
1527 auto proc = createRpcTestSocketServerProcess({
1528 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1529 .serverSupportedFileDescriptorTransportModes =
1530 {RpcSession::FileDescriptorTransportMode::UNIX},
1531 });
1532
1533 std::vector<android::os::ParcelFileDescriptor> files;
1534 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("123")));
1535 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1536 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("b")));
1537 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("cd")));
1538
1539 android::os::ParcelFileDescriptor out;
1540 auto status = proc.rootIface->concatFiles(files, &out);
1541 if (!supportsFdTransport()) {
1542 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1543 return;
1544 }
1545 ASSERT_TRUE(status.isOk()) << status;
1546
1547 std::string result;
1548 CHECK(android::base::ReadFdToString(out.get(), &result));
1549 EXPECT_EQ(result, "123abcd");
1550}
1551
1552TEST_P(BinderRpc, SendMaxFiles) {
1553 if (!supportsFdTransport()) {
1554 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1555 }
1556
1557 auto proc = createRpcTestSocketServerProcess({
1558 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1559 .serverSupportedFileDescriptorTransportModes =
1560 {RpcSession::FileDescriptorTransportMode::UNIX},
1561 });
1562
1563 std::vector<android::os::ParcelFileDescriptor> files;
1564 for (int i = 0; i < 253; i++) {
1565 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1566 }
1567
1568 android::os::ParcelFileDescriptor out;
1569 auto status = proc.rootIface->concatFiles(files, &out);
1570 ASSERT_TRUE(status.isOk()) << status;
1571
1572 std::string result;
1573 CHECK(android::base::ReadFdToString(out.get(), &result));
1574 EXPECT_EQ(result, std::string(253, 'a'));
1575}
1576
1577TEST_P(BinderRpc, SendTooManyFiles) {
1578 if (!supportsFdTransport()) {
1579 GTEST_SKIP() << "Would fail trivially (which is tested by BinderRpc::SendFiles)";
1580 }
1581
1582 auto proc = createRpcTestSocketServerProcess({
1583 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
1584 .serverSupportedFileDescriptorTransportModes =
1585 {RpcSession::FileDescriptorTransportMode::UNIX},
1586 });
1587
1588 std::vector<android::os::ParcelFileDescriptor> files;
1589 for (int i = 0; i < 254; i++) {
1590 files.emplace_back(android::os::ParcelFileDescriptor(mockFileDescriptor("a")));
1591 }
1592
1593 android::os::ParcelFileDescriptor out;
1594 auto status = proc.rootIface->concatFiles(files, &out);
1595 EXPECT_EQ(status.transactionError(), BAD_VALUE) << status;
1596}
1597
Steven Moreland37aff182021-03-26 02:04:16 +00001598TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001599 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001600
1601 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1602 ASSERT_NE(binder, nullptr);
1603
1604 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1605}
1606
1607TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001608 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001609
1610 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1611 ASSERT_NE(binder, nullptr);
1612
1613 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1614 ASSERT_NE(ndkBinder, nullptr);
1615
1616 std::string out;
1617 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1618 ASSERT_TRUE(status.isOk()) << status.getDescription();
1619 ASSERT_EQ("aoeuaoeu", out);
1620}
1621
Steven Moreland5553ac42020-11-11 02:14:45 +00001622ssize_t countFds() {
1623 DIR* dir = opendir("/proc/self/fd/");
1624 if (dir == nullptr) return -1;
1625 ssize_t ret = 0;
1626 dirent* ent;
1627 while ((ent = readdir(dir)) != nullptr) ret++;
1628 closedir(dir);
1629 return ret;
1630}
1631
Steven Morelandc1635952021-04-01 16:20:47 +00001632TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001633 ssize_t beforeFds = countFds();
1634 ASSERT_GE(beforeFds, 0);
1635 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001636 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001637 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1638 }
1639 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1640}
1641
Devin Moore800b2252021-10-15 16:22:57 +00001642TEST_P(BinderRpc, AidlDelegatorTest) {
1643 auto proc = createRpcTestSocketServerProcess({});
1644 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
1645 ASSERT_NE(nullptr, myDelegator);
1646
1647 std::string doubled;
1648 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
1649 EXPECT_EQ("cool cool ", doubled);
1650}
1651
Steven Morelandda573042021-06-12 01:13:45 +00001652static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001653 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001654 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001655 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland1eab3452021-08-05 16:56:20 -07001656 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1657 if (status == -EAFNOSUPPORT) {
1658 return false;
1659 }
1660 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1661 }
Steven Morelandda573042021-06-12 01:13:45 +00001662 server->start();
1663
Yifan Hongfdd9f692021-09-09 15:12:52 -07001664 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001665 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001666 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001667 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1668 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001669}
1670
Yifan Hong1deca4b2021-09-10 16:16:44 -07001671static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1672 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1673
1674 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001675
1676 static bool hasVsockLoopback = testSupportVsockLoopback();
1677
1678 if (hasVsockLoopback) {
1679 ret.push_back(SocketType::VSOCK);
1680 }
1681
1682 return ret;
1683}
1684
Frederick Mayledc07cf82022-05-26 20:30:12 +00001685static std::vector<uint32_t> testVersions() {
1686 std::vector<uint32_t> versions;
1687 for (size_t i = 0; i < RPC_WIRE_PROTOCOL_VERSION_NEXT; i++) {
1688 versions.push_back(i);
1689 }
1690 versions.push_back(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
1691 return versions;
1692}
1693
Yifan Hong702115c2021-06-24 15:39:18 -07001694INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1695 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
Frederick Mayledc07cf82022-05-26 20:30:12 +00001696 ::testing::ValuesIn(RpcSecurityValues()),
1697 ::testing::ValuesIn(testVersions()),
1698 ::testing::ValuesIn(testVersions())),
Yifan Hong702115c2021-06-24 15:39:18 -07001699 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001700
Yifan Hong702115c2021-06-24 15:39:18 -07001701class BinderRpcServerRootObject
1702 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001703
1704TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1705 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1706 auto setRootObject = [](bool isStrong) -> SetFn {
1707 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1708 };
1709
Yifan Hong702115c2021-06-24 15:39:18 -07001710 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1711 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001712 auto binder1 = sp<BBinder>::make();
1713 IBinder* binderRaw1 = binder1.get();
1714 setRootObject(isStrong1)(server.get(), binder1);
1715 EXPECT_EQ(binderRaw1, server->getRootObject());
1716 binder1.clear();
1717 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1718
1719 auto binder2 = sp<BBinder>::make();
1720 IBinder* binderRaw2 = binder2.get();
1721 setRootObject(isStrong2)(server.get(), binder2);
1722 EXPECT_EQ(binderRaw2, server->getRootObject());
1723 binder2.clear();
1724 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1725}
1726
1727INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001728 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1729 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001730
Yifan Hong1a235852021-05-13 16:07:47 -07001731class OneOffSignal {
1732public:
1733 // If notify() was previously called, or is called within |duration|, return true; else false.
1734 template <typename R, typename P>
1735 bool wait(std::chrono::duration<R, P> duration) {
1736 std::unique_lock<std::mutex> lock(mMutex);
1737 return mCv.wait_for(lock, duration, [this] { return mValue; });
1738 }
1739 void notify() {
1740 std::unique_lock<std::mutex> lock(mMutex);
1741 mValue = true;
1742 lock.unlock();
1743 mCv.notify_all();
1744 }
1745
1746private:
1747 std::mutex mMutex;
1748 std::condition_variable mCv;
1749 bool mValue = false;
1750};
1751
Frederick Mayledc07cf82022-05-26 20:30:12 +00001752TEST_P(BinderRpcServerOnly, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001753 auto addr = allocateSocketAddress();
Frederick Mayledc07cf82022-05-26 20:30:12 +00001754 auto server = RpcServer::make(newFactory(std::get<0>(GetParam())));
1755 server->setProtocolVersion(std::get<1>(GetParam()));
Steven Moreland2372f9d2021-08-05 15:42:01 -07001756 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001757 auto joinEnds = std::make_shared<OneOffSignal>();
1758
1759 // If things are broken and the thread never stops, don't block other tests. Because the thread
1760 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1761 // shared pointers are passed.
1762 std::thread([server, joinEnds] {
1763 server->join();
1764 joinEnds->notify();
1765 }).detach();
1766
1767 bool shutdown = false;
1768 for (int i = 0; i < 10 && !shutdown; i++) {
1769 usleep(300 * 1000); // 300ms; total 3s
1770 if (server->shutdown()) shutdown = true;
1771 }
1772 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1773
1774 ASSERT_TRUE(joinEnds->wait(2s))
1775 << "After server->shutdown() returns true, join() did not stop after 2s";
1776}
1777
Yifan Hong194acf22021-06-29 18:44:56 -07001778TEST(BinderRpc, Java) {
1779#if !defined(__ANDROID__)
1780 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1781 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1782 "to binderHostDeviceTest. Hence, just disable this test on host.";
1783#endif // !__ANDROID__
1784 sp<IServiceManager> sm = defaultServiceManager();
1785 ASSERT_NE(nullptr, sm);
1786 // Any Java service with non-empty getInterfaceDescriptor() would do.
1787 // Let's pick batteryproperties.
1788 auto binder = sm->checkService(String16("batteryproperties"));
1789 ASSERT_NE(nullptr, binder);
1790 auto descriptor = binder->getInterfaceDescriptor();
1791 ASSERT_GE(descriptor.size(), 0);
1792 ASSERT_EQ(OK, binder->pingBinder());
1793
1794 auto rpcServer = RpcServer::make();
Yifan Hong194acf22021-06-29 18:44:56 -07001795 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001796 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001797 auto socket = rpcServer->releaseServer();
1798
1799 auto keepAlive = sp<BBinder>::make();
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001800 auto setRpcClientDebugStatus = binder->setRpcClientDebug(std::move(socket), keepAlive);
1801
Yifan Honge3caaf22022-01-12 14:46:56 -08001802 if (!android::base::GetBoolProperty("ro.debuggable", false) ||
1803 android::base::GetProperty("ro.build.type", "") == "user") {
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001804 ASSERT_EQ(INVALID_OPERATION, setRpcClientDebugStatus)
Yifan Honge3caaf22022-01-12 14:46:56 -08001805 << "setRpcClientDebug should return INVALID_OPERATION on non-debuggable or user "
1806 "builds, but get "
Yifan Hongfe4b83f2021-11-08 16:29:53 -08001807 << statusToString(setRpcClientDebugStatus);
1808 GTEST_SKIP();
1809 }
1810
1811 ASSERT_EQ(OK, setRpcClientDebugStatus);
Yifan Hong194acf22021-06-29 18:44:56 -07001812
1813 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001814 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001815 auto rpcBinder = rpcSession->getRootObject();
1816 ASSERT_NE(nullptr, rpcBinder);
1817
1818 ASSERT_EQ(OK, rpcBinder->pingBinder());
1819
1820 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1821 << "getInterfaceDescriptor should not crash system_server";
1822 ASSERT_EQ(OK, rpcBinder->pingBinder());
1823}
1824
Frederick Mayledc07cf82022-05-26 20:30:12 +00001825INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly,
1826 ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()),
1827 ::testing::ValuesIn(testVersions())),
1828 BinderRpcServerOnly::PrintTestParam);
Yifan Hong702115c2021-06-24 15:39:18 -07001829
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001830class RpcTransportTestUtils {
Yifan Hong1deca4b2021-09-10 16:16:44 -07001831public:
Frederick Mayledc07cf82022-05-26 20:30:12 +00001832 // Only parameterized only server version because `RpcSession` is bypassed
1833 // in the client half of the tests.
1834 using Param =
1835 std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001836 using ConnectToServer = std::function<base::unique_fd()>;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001837
1838 // A server that handles client socket connections.
1839 class Server {
1840 public:
1841 explicit Server() {}
1842 Server(Server&&) = default;
Yifan Honge07d2732021-09-13 21:59:14 -07001843 ~Server() { shutdownAndWait(); }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001844 [[nodiscard]] AssertionResult setUp(
1845 const Param& param,
1846 std::unique_ptr<RpcAuth> auth = std::make_unique<RpcAuthSelfSigned>()) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001847 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001848 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
Frederick Mayledc07cf82022-05-26 20:30:12 +00001849 rpcServer->setProtocolVersion(serverVersion);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001850 switch (socketType) {
1851 case SocketType::PRECONNECTED: {
1852 return AssertionFailure() << "Not supported by this test";
1853 } break;
1854 case SocketType::UNIX: {
1855 auto addr = allocateSocketAddress();
1856 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1857 if (status != OK) {
1858 return AssertionFailure()
1859 << "setupUnixDomainServer: " << statusToString(status);
1860 }
1861 mConnectToServer = [addr] {
1862 return connectTo(UnixSocketAddress(addr.c_str()));
1863 };
1864 } break;
1865 case SocketType::VSOCK: {
1866 auto port = allocateVsockPort();
1867 auto status = rpcServer->setupVsockServer(port);
1868 if (status != OK) {
1869 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1870 }
1871 mConnectToServer = [port] {
1872 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1873 };
1874 } break;
1875 case SocketType::INET: {
1876 unsigned int port;
1877 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1878 if (status != OK) {
1879 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1880 }
1881 mConnectToServer = [port] {
1882 const char* addr = kLocalInetAddress;
1883 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1884 if (aiStart == nullptr) return base::unique_fd{};
1885 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1886 auto fd = connectTo(
1887 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1888 if (fd.ok()) return fd;
1889 }
1890 ALOGE("None of the socket address resolved for %s:%u can be connected",
1891 addr, port);
1892 return base::unique_fd{};
1893 };
1894 }
1895 }
1896 mFd = rpcServer->releaseServer();
1897 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001898 mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
Yifan Hong1deca4b2021-09-10 16:16:44 -07001899 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1900 mSetup = true;
1901 return AssertionSuccess();
1902 }
1903 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1904 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1905 return mCertVerifier;
1906 }
1907 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1908 void start() {
1909 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1910 mThread = std::make_unique<std::thread>(&Server::run, this);
1911 }
1912 void run() {
1913 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1914
1915 std::vector<std::thread> threads;
1916 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1917 base::unique_fd acceptedFd(
1918 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1919 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1920 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1921 }
1922
1923 for (auto& thread : threads) thread.join();
1924 }
1925 void handleOne(android::base::unique_fd acceptedFd) {
1926 ASSERT_TRUE(acceptedFd.ok());
1927 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1928 if (serverTransport == nullptr) return; // handshake failed
Yifan Hong67519322021-09-13 18:51:16 -07001929 ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07001930 }
Yifan Honge07d2732021-09-13 21:59:14 -07001931 void shutdownAndWait() {
Yifan Hong67519322021-09-13 18:51:16 -07001932 shutdown();
1933 join();
1934 }
1935 void shutdown() { mFdTrigger->trigger(); }
1936
1937 void setPostConnect(
1938 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> fn) {
1939 mPostConnect = std::move(fn);
Yifan Hong1deca4b2021-09-10 16:16:44 -07001940 }
1941
1942 private:
1943 std::unique_ptr<std::thread> mThread;
1944 ConnectToServer mConnectToServer;
1945 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1946 base::unique_fd mFd;
1947 std::unique_ptr<RpcTransportCtx> mCtx;
1948 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1949 std::make_shared<RpcCertificateVerifierSimple>();
1950 bool mSetup = false;
Yifan Hong67519322021-09-13 18:51:16 -07001951 // The function invoked after connection and handshake. By default, it is
1952 // |defaultPostConnect| that sends |kMessage| to the client.
1953 std::function<AssertionResult(RpcTransport*, FdTrigger* fdTrigger)> mPostConnect =
1954 Server::defaultPostConnect;
1955
1956 void join() {
1957 if (mThread != nullptr) {
1958 mThread->join();
1959 mThread = nullptr;
1960 }
1961 }
1962
1963 static AssertionResult defaultPostConnect(RpcTransport* serverTransport,
1964 FdTrigger* fdTrigger) {
1965 std::string message(kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00001966 iovec messageIov{message.data(), message.size()};
Devin Moore695368f2022-06-03 22:29:14 +00001967 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00001968 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07001969 if (status != OK) return AssertionFailure() << statusToString(status);
1970 return AssertionSuccess();
1971 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07001972 };
1973
1974 class Client {
1975 public:
1976 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1977 Client(Client&&) = default;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07001978 [[nodiscard]] AssertionResult setUp(const Param& param) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00001979 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = param;
1980 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07001981 mFdTrigger = FdTrigger::make();
1982 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1983 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1984 return AssertionSuccess();
1985 }
1986 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1987 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1988 return mCertVerifier;
1989 }
Yifan Hong67519322021-09-13 18:51:16 -07001990 // connect() and do handshake
1991 bool setUpTransport() {
1992 mFd = mConnectToServer();
1993 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1994 mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1995 return mClientTransport != nullptr;
1996 }
1997 AssertionResult readMessage(const std::string& expectedMessage = kMessage) {
1998 LOG_ALWAYS_FATAL_IF(mClientTransport == nullptr, "setUpTransport not called or failed");
1999 std::string readMessage(expectedMessage.size(), '\0');
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002000 iovec readMessageIov{readMessage.data(), readMessage.size()};
Devin Moore695368f2022-06-03 22:29:14 +00002001 status_t readStatus =
2002 mClientTransport->interruptableReadFully(mFdTrigger.get(), &readMessageIov, 1,
Frederick Mayle69a0c992022-05-26 20:38:39 +00002003 std::nullopt, false);
Yifan Hong67519322021-09-13 18:51:16 -07002004 if (readStatus != OK) {
2005 return AssertionFailure() << statusToString(readStatus);
2006 }
2007 if (readMessage != expectedMessage) {
2008 return AssertionFailure()
2009 << "Expected " << expectedMessage << ", actual " << readMessage;
2010 }
2011 return AssertionSuccess();
2012 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002013 void run(bool handshakeOk = true, bool readOk = true) {
Yifan Hong67519322021-09-13 18:51:16 -07002014 if (!setUpTransport()) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07002015 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
2016 return;
2017 }
2018 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
Yifan Hong67519322021-09-13 18:51:16 -07002019 ASSERT_EQ(readOk, readMessage());
Yifan Hong1deca4b2021-09-10 16:16:44 -07002020 }
2021
2022 private:
2023 ConnectToServer mConnectToServer;
2024 base::unique_fd mFd;
2025 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
2026 std::unique_ptr<RpcTransportCtx> mCtx;
2027 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
2028 std::make_shared<RpcCertificateVerifierSimple>();
Yifan Hong67519322021-09-13 18:51:16 -07002029 std::unique_ptr<RpcTransport> mClientTransport;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002030 };
2031
2032 // Make A trust B.
2033 template <typename A, typename B>
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002034 static status_t trust(RpcSecurity rpcSecurity,
2035 std::optional<RpcCertificateFormat> certificateFormat, const A& a,
2036 const B& b) {
Yifan Hong1deca4b2021-09-10 16:16:44 -07002037 if (rpcSecurity != RpcSecurity::TLS) return OK;
Yifan Hong22211f82021-09-14 12:32:25 -07002038 LOG_ALWAYS_FATAL_IF(!certificateFormat.has_value());
2039 auto bCert = b->getCtx()->getCertificate(*certificateFormat);
2040 return a->getCertVerifier()->addTrustedPeerCertificate(*certificateFormat, bCert);
Yifan Hong1deca4b2021-09-10 16:16:44 -07002041 }
2042
2043 static constexpr const char* kMessage = "hello";
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002044};
2045
2046class RpcTransportTest : public testing::TestWithParam<RpcTransportTestUtils::Param> {
2047public:
2048 using Server = RpcTransportTestUtils::Server;
2049 using Client = RpcTransportTestUtils::Client;
2050 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002051 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = info.param;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002052 auto ret = PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString();
2053 if (certificateFormat.has_value()) ret += "_" + PrintToString(*certificateFormat);
Frederick Mayledc07cf82022-05-26 20:30:12 +00002054 ret += "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002055 return ret;
2056 }
2057 static std::vector<ParamType> getRpcTranportTestParams() {
2058 std::vector<ParamType> ret;
Frederick Mayledc07cf82022-05-26 20:30:12 +00002059 for (auto serverVersion : testVersions()) {
2060 for (auto socketType : testSocketTypes(false /* hasPreconnected */)) {
2061 for (auto rpcSecurity : RpcSecurityValues()) {
2062 switch (rpcSecurity) {
2063 case RpcSecurity::RAW: {
2064 ret.emplace_back(socketType, rpcSecurity, std::nullopt, serverVersion);
2065 } break;
2066 case RpcSecurity::TLS: {
2067 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::PEM,
2068 serverVersion);
2069 ret.emplace_back(socketType, rpcSecurity, RpcCertificateFormat::DER,
2070 serverVersion);
2071 } break;
2072 }
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002073 }
2074 }
2075 }
2076 return ret;
2077 }
2078 template <typename A, typename B>
2079 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002080 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2081 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002082 return RpcTransportTestUtils::trust(rpcSecurity, certificateFormat, a, b);
2083 }
Yifan Hong1deca4b2021-09-10 16:16:44 -07002084};
2085
2086TEST_P(RpcTransportTest, GoodCertificate) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002087 auto server = std::make_unique<Server>();
2088 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002089
2090 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002091 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002092
2093 ASSERT_EQ(OK, trust(&client, server));
2094 ASSERT_EQ(OK, trust(server, &client));
2095
2096 server->start();
2097 client.run();
2098}
2099
2100TEST_P(RpcTransportTest, MultipleClients) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002101 auto server = std::make_unique<Server>();
2102 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002103
2104 std::vector<Client> clients;
2105 for (int i = 0; i < 2; i++) {
2106 auto& client = clients.emplace_back(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002107 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002108 ASSERT_EQ(OK, trust(&client, server));
2109 ASSERT_EQ(OK, trust(server, &client));
2110 }
2111
2112 server->start();
2113 for (auto& client : clients) client.run();
2114}
2115
2116TEST_P(RpcTransportTest, UntrustedServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002117 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2118 (void)serverVersion;
Yifan Hong1deca4b2021-09-10 16:16:44 -07002119
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002120 auto untrustedServer = std::make_unique<Server>();
2121 ASSERT_TRUE(untrustedServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002122
2123 Client client(untrustedServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002124 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002125
2126 ASSERT_EQ(OK, trust(untrustedServer, &client));
2127
2128 untrustedServer->start();
2129
2130 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2131 // the client can't verify the server's identity.
2132 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2133 client.run(handshakeOk);
2134}
2135TEST_P(RpcTransportTest, MaliciousServer) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002136 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2137 (void)serverVersion;
2138
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002139 auto validServer = std::make_unique<Server>();
2140 ASSERT_TRUE(validServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002141
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002142 auto maliciousServer = std::make_unique<Server>();
2143 ASSERT_TRUE(maliciousServer->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002144
2145 Client client(maliciousServer->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002146 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002147
2148 ASSERT_EQ(OK, trust(&client, validServer));
2149 ASSERT_EQ(OK, trust(validServer, &client));
2150 ASSERT_EQ(OK, trust(maliciousServer, &client));
2151
2152 maliciousServer->start();
2153
2154 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
2155 // the client can't verify the server's identity.
2156 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
2157 client.run(handshakeOk);
2158}
2159
2160TEST_P(RpcTransportTest, UntrustedClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002161 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2162 (void)serverVersion;
2163
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002164 auto server = std::make_unique<Server>();
2165 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002166
2167 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002168 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002169
2170 ASSERT_EQ(OK, trust(&client, server));
2171
2172 server->start();
2173
2174 // For TLS, Client should be able to verify server's identity, so client should see
2175 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
2176 // identity and should drop the connection, so client shouldn't be able to read anything.
2177 bool readOk = rpcSecurity != RpcSecurity::TLS;
2178 client.run(true, readOk);
2179}
2180
2181TEST_P(RpcTransportTest, MaliciousClient) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002182 auto [socketType, rpcSecurity, certificateFormat, serverVersion] = GetParam();
2183 (void)serverVersion;
2184
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002185 auto server = std::make_unique<Server>();
2186 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002187
2188 Client validClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002189 ASSERT_TRUE(validClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002190 Client maliciousClient(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002191 ASSERT_TRUE(maliciousClient.setUp(GetParam()));
Yifan Hong1deca4b2021-09-10 16:16:44 -07002192
2193 ASSERT_EQ(OK, trust(&validClient, server));
2194 ASSERT_EQ(OK, trust(&maliciousClient, server));
2195
2196 server->start();
2197
2198 // See UntrustedClient.
2199 bool readOk = rpcSecurity != RpcSecurity::TLS;
2200 maliciousClient.run(true, readOk);
2201}
2202
Yifan Hong67519322021-09-13 18:51:16 -07002203TEST_P(RpcTransportTest, Trigger) {
2204 std::string msg2 = ", world!";
2205 std::mutex writeMutex;
2206 std::condition_variable writeCv;
2207 bool shouldContinueWriting = false;
2208 auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002209 std::string message(RpcTransportTestUtils::kMessage);
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002210 iovec messageIov{message.data(), message.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002211 auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
2212 std::nullopt, nullptr);
Yifan Hong67519322021-09-13 18:51:16 -07002213 if (status != OK) return AssertionFailure() << statusToString(status);
2214
2215 {
2216 std::unique_lock<std::mutex> lock(writeMutex);
2217 if (!writeCv.wait_for(lock, 3s, [&] { return shouldContinueWriting; })) {
2218 return AssertionFailure() << "write barrier not cleared in time!";
2219 }
2220 }
2221
Andrei Homescua39e4ed2021-12-10 08:41:54 +00002222 iovec msg2Iov{msg2.data(), msg2.size()};
Frederick Mayle69a0c992022-05-26 20:38:39 +00002223 status = serverTransport->interruptableWriteFully(fdTrigger, &msg2Iov, 1, std::nullopt,
2224 nullptr);
Steven Morelandc591b472021-09-16 13:56:11 -07002225 if (status != DEAD_OBJECT)
Yifan Hong67519322021-09-13 18:51:16 -07002226 return AssertionFailure() << "When FdTrigger is shut down, interruptableWriteFully "
Steven Morelandc591b472021-09-16 13:56:11 -07002227 "should return DEAD_OBJECT, but it is "
Yifan Hong67519322021-09-13 18:51:16 -07002228 << statusToString(status);
2229 return AssertionSuccess();
2230 };
2231
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002232 auto server = std::make_unique<Server>();
2233 ASSERT_TRUE(server->setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002234
2235 // Set up client
2236 Client client(server->getConnectToServerFn());
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002237 ASSERT_TRUE(client.setUp(GetParam()));
Yifan Hong67519322021-09-13 18:51:16 -07002238
2239 // Exchange keys
2240 ASSERT_EQ(OK, trust(&client, server));
2241 ASSERT_EQ(OK, trust(server, &client));
2242
2243 server->setPostConnect(serverPostConnect);
2244
Yifan Hong67519322021-09-13 18:51:16 -07002245 server->start();
2246 // connect() to server and do handshake
2247 ASSERT_TRUE(client.setUpTransport());
Yifan Hong22211f82021-09-14 12:32:25 -07002248 // read the first message. This ensures that server has finished handshake and start handling
2249 // client fd. Server thread should pause at writeCv.wait_for().
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002250 ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
Yifan Hong67519322021-09-13 18:51:16 -07002251 // Trigger server shutdown after server starts handling client FD. This ensures that the second
2252 // write is on an FdTrigger that has been shut down.
2253 server->shutdown();
2254 // Continues server thread to write the second message.
2255 {
Yifan Hong22211f82021-09-14 12:32:25 -07002256 std::lock_guard<std::mutex> lock(writeMutex);
Yifan Hong67519322021-09-13 18:51:16 -07002257 shouldContinueWriting = true;
Yifan Hong67519322021-09-13 18:51:16 -07002258 }
Yifan Hong22211f82021-09-14 12:32:25 -07002259 writeCv.notify_all();
Yifan Hong67519322021-09-13 18:51:16 -07002260 // After this line, server thread unblocks and attempts to write the second message, but
Steven Morelandc591b472021-09-16 13:56:11 -07002261 // shutdown is triggered, so write should failed with DEAD_OBJECT. See |serverPostConnect|.
Yifan Hong67519322021-09-13 18:51:16 -07002262 // On the client side, second read fails with DEAD_OBJECT
2263 ASSERT_FALSE(client.readMessage(msg2));
2264}
2265
Yifan Hong1deca4b2021-09-10 16:16:44 -07002266INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
Yifan Hong22211f82021-09-14 12:32:25 -07002267 ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
Yifan Hong1deca4b2021-09-10 16:16:44 -07002268 RpcTransportTest::PrintParamInfo);
2269
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002270class RpcTransportTlsKeyTest
Frederick Mayledc07cf82022-05-26 20:30:12 +00002271 : public testing::TestWithParam<
2272 std::tuple<SocketType, RpcCertificateFormat, RpcKeyFormat, uint32_t>> {
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002273public:
2274 template <typename A, typename B>
2275 status_t trust(const A& a, const B& b) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002276 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
2277 (void)serverVersion;
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002278 return RpcTransportTestUtils::trust(RpcSecurity::TLS, certificateFormat, a, b);
2279 }
2280 static std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002281 auto [socketType, certificateFormat, keyFormat, serverVersion] = info.param;
2282 return PrintToString(socketType) + "_certificate_" + PrintToString(certificateFormat) +
2283 "_key_" + PrintToString(keyFormat) + "_serverV" + std::to_string(serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002284 };
2285};
2286
2287TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) {
Frederick Mayledc07cf82022-05-26 20:30:12 +00002288 auto [socketType, certificateFormat, keyFormat, serverVersion] = GetParam();
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002289
2290 std::vector<uint8_t> pkeyData, certData;
2291 {
2292 auto pkey = makeKeyPairForSelfSignedCert();
2293 ASSERT_NE(nullptr, pkey);
2294 auto cert = makeSelfSignedCert(pkey.get(), kCertValidSeconds);
2295 ASSERT_NE(nullptr, cert);
2296 pkeyData = serializeUnencryptedPrivatekey(pkey.get(), keyFormat);
2297 certData = serializeCertificate(cert.get(), certificateFormat);
2298 }
2299
2300 auto desPkey = deserializeUnencryptedPrivatekey(pkeyData, keyFormat);
2301 auto desCert = deserializeCertificate(certData, certificateFormat);
2302 auto auth = std::make_unique<RpcAuthPreSigned>(std::move(desPkey), std::move(desCert));
Frederick Mayledc07cf82022-05-26 20:30:12 +00002303 auto utilsParam = std::make_tuple(socketType, RpcSecurity::TLS,
2304 std::make_optional(certificateFormat), serverVersion);
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002305
2306 auto server = std::make_unique<RpcTransportTestUtils::Server>();
2307 ASSERT_TRUE(server->setUp(utilsParam, std::move(auth)));
2308
2309 RpcTransportTestUtils::Client client(server->getConnectToServerFn());
2310 ASSERT_TRUE(client.setUp(utilsParam));
2311
2312 ASSERT_EQ(OK, trust(&client, server));
2313 ASSERT_EQ(OK, trust(server, &client));
2314
2315 server->start();
2316 client.run();
2317}
2318
2319INSTANTIATE_TEST_CASE_P(
2320 BinderRpc, RpcTransportTlsKeyTest,
2321 testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)),
2322 testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER),
Frederick Mayledc07cf82022-05-26 20:30:12 +00002323 testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER),
2324 testing::ValuesIn(testVersions())),
Yifan Hongb1ce80c2021-09-17 22:10:58 -07002325 RpcTransportTlsKeyTest::PrintParamInfo);
2326
Steven Morelandc1635952021-04-01 16:20:47 +00002327} // namespace android
2328
2329int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00002330 ::testing::InitGoogleTest(&argc, argv);
2331 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
Steven Morelanda83191d2021-10-27 10:14:53 -07002332
Steven Moreland5553ac42020-11-11 02:14:45 +00002333 return RUN_ALL_TESTS();
2334}