blob: 8c805bb6cc43847ce8289b729befedb8a85421b5 [file] [log] [blame]
Steven Moreland5553ac42020-11-11 02:14:45 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yifan Hong1deca4b2021-09-10 16:16:44 -070017#include <BinderRpcTestClientInfo.h>
18#include <BinderRpcTestServerInfo.h>
Steven Moreland659416d2021-05-11 00:47:50 +000019#include <BnBinderRpcCallback.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000020#include <BnBinderRpcSession.h>
21#include <BnBinderRpcTest.h>
Steven Moreland37aff182021-03-26 02:04:16 +000022#include <aidl/IBinderRpcTest.h>
Yifan Hong6d82c8a2021-04-26 20:26:45 -070023#include <android-base/file.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000024#include <android-base/logging.h>
Steven Moreland37aff182021-03-26 02:04:16 +000025#include <android/binder_auto_utils.h>
26#include <android/binder_libbinder.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000027#include <binder/Binder.h>
28#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000029#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000030#include <binder/IServiceManager.h>
31#include <binder/ProcessState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000032#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000033#include <binder/RpcSession.h>
Yifan Hong702115c2021-06-24 15:39:18 -070034#include <binder/RpcTransport.h>
35#include <binder/RpcTransportRaw.h>
Yifan Hong92409752021-07-30 21:25:32 -070036#include <binder/RpcTransportTls.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000037#include <gtest/gtest.h>
38
Steven Morelandc1635952021-04-01 16:20:47 +000039#include <chrono>
40#include <cstdlib>
41#include <iostream>
42#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000043#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000044
Yifan Hong1deca4b2021-09-10 16:16:44 -070045#include <poll.h>
Steven Morelandc1635952021-04-01 16:20:47 +000046#include <sys/prctl.h>
47#include <unistd.h>
48
Yifan Hong1deca4b2021-09-10 16:16:44 -070049#include "../FdTrigger.h"
Steven Moreland4198a122021-08-03 17:37:58 -070050#include "../RpcSocketAddress.h" // for testing preconnected clients
Steven Morelandbd5002b2021-05-04 23:12:56 +000051#include "../RpcState.h" // for debugging
52#include "../vm_sockets.h" // for VMADDR_*
Yifan Hong13c90062021-09-09 14:59:53 -070053#include "RpcCertificateVerifierSimple.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000054
Yifan Hong1a235852021-05-13 16:07:47 -070055using namespace std::chrono_literals;
Yifan Hong1deca4b2021-09-10 16:16:44 -070056using testing::AssertionFailure;
57using testing::AssertionResult;
58using testing::AssertionSuccess;
Yifan Hong1a235852021-05-13 16:07:47 -070059
Steven Moreland5553ac42020-11-11 02:14:45 +000060namespace android {
61
Steven Morelandbf57bce2021-07-26 15:26:12 -070062static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
63 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Devin Mooref3b9c4f2021-08-03 15:50:13 +000064const char* kLocalInetAddress = "127.0.0.1";
Steven Morelandbf57bce2021-07-26 15:26:12 -070065
Yifan Hong92409752021-07-30 21:25:32 -070066enum class RpcSecurity { RAW, TLS };
Yifan Hong702115c2021-06-24 15:39:18 -070067
68static inline std::vector<RpcSecurity> RpcSecurityValues() {
Yifan Hong92409752021-07-30 21:25:32 -070069 return {RpcSecurity::RAW, RpcSecurity::TLS};
Yifan Hong702115c2021-06-24 15:39:18 -070070}
71
Yifan Hong13c90062021-09-09 14:59:53 -070072static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(
73 RpcSecurity rpcSecurity, std::shared_ptr<RpcCertificateVerifier> verifier = nullptr) {
Yifan Hong702115c2021-06-24 15:39:18 -070074 switch (rpcSecurity) {
75 case RpcSecurity::RAW:
76 return RpcTransportCtxFactoryRaw::make();
Yifan Hong13c90062021-09-09 14:59:53 -070077 case RpcSecurity::TLS: {
Yifan Hong13c90062021-09-09 14:59:53 -070078 if (verifier == nullptr) {
79 verifier = std::make_shared<RpcCertificateVerifierSimple>();
80 }
81 return RpcTransportCtxFactoryTls::make(std::move(verifier));
82 }
Yifan Hong702115c2021-06-24 15:39:18 -070083 default:
84 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
85 }
86}
87
Steven Moreland1fda67b2021-04-02 18:35:50 +000088TEST(BinderRpcParcel, EntireParcelFormatted) {
89 Parcel p;
90 p.writeInt32(3);
91
92 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
93}
94
Yifan Hong702115c2021-06-24 15:39:18 -070095class BinderRpcSimple : public ::testing::TestWithParam<RpcSecurity> {
96public:
97 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
98 return newFactory(info.param)->toCString();
99 }
100};
101
102TEST_P(BinderRpcSimple, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -0700103 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
104 int sinkFd = sink.get();
Yifan Hong702115c2021-06-24 15:39:18 -0700105 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -0700106 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
107 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700108 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -0700109 ASSERT_TRUE(server->hasServer());
110 base::unique_fd retrieved = server->releaseServer();
111 ASSERT_FALSE(server->hasServer());
112 ASSERT_EQ(sinkFd, retrieved.get());
113}
114
Steven Morelandbf57bce2021-07-26 15:26:12 -0700115TEST(BinderRpc, CannotUseNextWireVersion) {
116 auto session = RpcSession::make();
117 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
118 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
119 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
120 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
121}
122
123TEST(BinderRpc, CanUseExperimentalWireVersion) {
124 auto session = RpcSession::make();
125 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
126}
127
Steven Moreland5553ac42020-11-11 02:14:45 +0000128using android::binder::Status;
129
130#define EXPECT_OK(status) \
131 do { \
132 Status stat = (status); \
133 EXPECT_TRUE(stat.isOk()) << stat; \
134 } while (false)
135
136class MyBinderRpcSession : public BnBinderRpcSession {
137public:
138 static std::atomic<int32_t> gNum;
139
140 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
141 Status getName(std::string* name) override {
142 *name = mName;
143 return Status::ok();
144 }
145 ~MyBinderRpcSession() { gNum--; }
146
147private:
148 std::string mName;
149};
150std::atomic<int32_t> MyBinderRpcSession::gNum;
151
Steven Moreland659416d2021-05-11 00:47:50 +0000152class MyBinderRpcCallback : public BnBinderRpcCallback {
153 Status sendCallback(const std::string& value) {
154 std::unique_lock _l(mMutex);
155 mValues.push_back(value);
156 _l.unlock();
157 mCv.notify_one();
158 return Status::ok();
159 }
160 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
161
162public:
163 std::mutex mMutex;
164 std::condition_variable mCv;
165 std::vector<std::string> mValues;
166};
167
Steven Moreland5553ac42020-11-11 02:14:45 +0000168class MyBinderRpcTest : public BnBinderRpcTest {
169public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000170 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +0000171
172 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000173 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000174 return Status::ok();
175 }
176 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000177 *strstr = str + str;
178 return Status::ok();
179 }
Steven Moreland736664b2021-05-01 04:27:25 +0000180 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000181 sp<RpcServer> spServer = server.promote();
182 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000183 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
184 }
Steven Moreland736664b2021-05-01 04:27:25 +0000185 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000186 for (auto session : spServer->listSessions()) {
187 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000188 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000189 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000190 return Status::ok();
191 }
192 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
193 if (binder == nullptr) {
194 std::cout << "Received null binder!" << std::endl;
195 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
196 }
197 *out = binder->pingBinder();
198 return Status::ok();
199 }
200 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
201 *out = binder;
202 return Status::ok();
203 }
204 static sp<IBinder> mHeldBinder;
205 Status holdBinder(const sp<IBinder>& binder) override {
206 mHeldBinder = binder;
207 return Status::ok();
208 }
209 Status getHeldBinder(sp<IBinder>* held) override {
210 *held = mHeldBinder;
211 return Status::ok();
212 }
213 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
214 if (count <= 0) return Status::ok();
215 return binder->nestMe(this, count - 1);
216 }
217 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
218 static sp<IBinder> binder = new BBinder;
219 *out = binder;
220 return Status::ok();
221 }
222 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
223 *out = new MyBinderRpcSession(name);
224 return Status::ok();
225 }
226 Status getNumOpenSessions(int32_t* out) override {
227 *out = MyBinderRpcSession::gNum;
228 return Status::ok();
229 }
230
231 std::mutex blockMutex;
232 Status lock() override {
233 blockMutex.lock();
234 return Status::ok();
235 }
236 Status unlockInMsAsync(int32_t ms) override {
237 usleep(ms * 1000);
238 blockMutex.unlock();
239 return Status::ok();
240 }
241 Status lockUnlock() override {
242 std::lock_guard<std::mutex> _l(blockMutex);
243 return Status::ok();
244 }
245
246 Status sleepMs(int32_t ms) override {
247 usleep(ms * 1000);
248 return Status::ok();
249 }
250
251 Status sleepMsAsync(int32_t ms) override {
252 // In-process binder calls are asynchronous, but the call to this method
253 // is synchronous wrt its client. This in/out-process threading model
254 // diffentiation is a classic binder leaky abstraction (for better or
255 // worse) and is preserved here the way binder sockets plugs itself
256 // into BpBinder, as nothing is changed at the higher levels
257 // (IInterface) which result in this behavior.
258 return sleepMs(ms);
259 }
260
Steven Moreland659416d2021-05-11 00:47:50 +0000261 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
262 const std::string& value) override {
263 if (callback == nullptr) {
264 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
265 }
266
267 if (delayed) {
268 std::thread([=]() {
269 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000270 Status status = doCallback(callback, oneway, false, value);
271 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000272 }).detach();
273 return Status::ok();
274 }
275
276 if (oneway) {
277 return callback->sendOnewayCallback(value);
278 }
279
280 return callback->sendCallback(value);
281 }
282
Steven Morelandc7d40132021-06-10 03:42:11 +0000283 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
284 const std::string& value) override {
285 return doCallback(callback, oneway, delayed, value);
286 }
287
Steven Moreland5553ac42020-11-11 02:14:45 +0000288 Status die(bool cleanup) override {
289 if (cleanup) {
290 exit(1);
291 } else {
292 _exit(1);
293 }
294 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000295
296 Status scheduleShutdown() override {
297 sp<RpcServer> strongServer = server.promote();
298 if (strongServer == nullptr) {
299 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
300 }
301 std::thread([=] {
302 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
303 }).detach();
304 return Status::ok();
305 }
306
Steven Morelandd7302072021-05-15 01:32:04 +0000307 Status useKernelBinderCallingId() override {
308 // this is WRONG! It does not make sense when using RPC binder, and
309 // because it is SO wrong, and so much code calls this, it should abort!
310
311 (void)IPCThreadState::self()->getCallingPid();
312 return Status::ok();
313 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000314};
315sp<IBinder> MyBinderRpcTest::mHeldBinder;
316
317class Process {
318public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700319 Process(Process&&) = default;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700320 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
321 android::base::borrowed_fd /* readEnd */)>& f) {
322 android::base::unique_fd childWriteEnd;
323 android::base::unique_fd childReadEnd;
324 CHECK(android::base::Pipe(&mReadEnd, &childWriteEnd)) << strerror(errno);
325 CHECK(android::base::Pipe(&childReadEnd, &mWriteEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000326 if (0 == (mPid = fork())) {
327 // racey: assume parent doesn't crash before this is set
328 prctl(PR_SET_PDEATHSIG, SIGHUP);
329
Yifan Hong1deca4b2021-09-10 16:16:44 -0700330 f(childWriteEnd, childReadEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000331
332 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000333 }
334 }
335 ~Process() {
336 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000337 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000338 }
339 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700340 android::base::borrowed_fd readEnd() { return mReadEnd; }
Yifan Hong1deca4b2021-09-10 16:16:44 -0700341 android::base::borrowed_fd writeEnd() { return mWriteEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000342
343private:
344 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700345 android::base::unique_fd mReadEnd;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700346 android::base::unique_fd mWriteEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000347};
348
349static std::string allocateSocketAddress() {
350 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000351 std::string temp = getenv("TMPDIR") ?: "/tmp";
Yifan Hong1deca4b2021-09-10 16:16:44 -0700352 auto ret = temp + "/binderRpcTest_" + std::to_string(id++);
353 unlink(ret.c_str());
354 return ret;
Steven Moreland5553ac42020-11-11 02:14:45 +0000355};
356
Steven Morelandda573042021-06-12 01:13:45 +0000357static unsigned int allocateVsockPort() {
358 static unsigned int vsockPort = 3456;
359 return vsockPort++;
360}
361
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000362struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000363 // reference to process hosting a socket server
364 Process host;
365
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000366 struct SessionInfo {
367 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000368 sp<IBinder> root;
369 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000370
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000371 // client session objects associated with other process
372 // each one represents a separate session
373 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000374
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000375 ProcessSession(ProcessSession&&) = default;
376 ~ProcessSession() {
377 for (auto& session : sessions) {
378 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000379 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000380
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000381 for (auto& info : sessions) {
382 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000383
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000384 EXPECT_NE(nullptr, session);
385 EXPECT_NE(nullptr, session->state());
386 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000387
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000388 wp<RpcSession> weakSession = session;
389 session = nullptr;
390 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000391 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000392 }
393};
394
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000395// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000396// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000397struct BinderRpcTestProcessSession {
398 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000399
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000400 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000401 sp<IBinder> rootBinder;
402
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000403 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000404 sp<IBinderRpcTest> rootIface;
405
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000406 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000407 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000408
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000409 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
410 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000411 EXPECT_NE(nullptr, rootIface);
412 if (rootIface == nullptr) return;
413
Steven Morelandaf4ca712021-05-24 23:22:08 +0000414 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000415 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000416 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000417 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000418 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000419 for (auto remoteCount : remoteCounts) {
420 EXPECT_EQ(remoteCount, 1);
421 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000422
Steven Moreland798e0d12021-07-14 23:19:25 +0000423 // even though it is on another thread, shutdown races with
424 // the transaction reply being written
425 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
426 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
427 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000428 }
429
430 rootIface = nullptr;
431 rootBinder = nullptr;
432 }
433};
434
Steven Morelandc1635952021-04-01 16:20:47 +0000435enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700436 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000437 UNIX,
438 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700439 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000440};
Yifan Hong702115c2021-06-24 15:39:18 -0700441static inline std::string PrintToString(SocketType socketType) {
442 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700443 case SocketType::PRECONNECTED:
444 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000445 case SocketType::UNIX:
446 return "unix_domain_socket";
447 case SocketType::VSOCK:
448 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700449 case SocketType::INET:
450 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000451 default:
452 LOG_ALWAYS_FATAL("Unknown socket type");
453 return "";
454 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000455}
Steven Morelandda573042021-06-12 01:13:45 +0000456
Yifan Hong1deca4b2021-09-10 16:16:44 -0700457static base::unique_fd connectTo(const RpcSocketAddress& addr) {
Steven Moreland4198a122021-08-03 17:37:58 -0700458 base::unique_fd serverFd(
459 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
460 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700461 CHECK(serverFd.ok()) << "Could not create socket " << addr.toString() << ": "
462 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700463
464 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
465 int savedErrno = errno;
Yifan Hong1deca4b2021-09-10 16:16:44 -0700466 LOG(FATAL) << "Could not connect to socket " << addr.toString() << ": "
467 << strerror(savedErrno);
Steven Moreland4198a122021-08-03 17:37:58 -0700468 }
469 return serverFd;
470}
471
Yifan Hong702115c2021-06-24 15:39:18 -0700472class BinderRpc : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000473public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000474 struct Options {
475 size_t numThreads = 1;
476 size_t numSessions = 1;
477 size_t numIncomingConnections = 0;
478 };
479
Yifan Hong702115c2021-06-24 15:39:18 -0700480 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
481 auto [type, security] = info.param;
482 return PrintToString(type) + "_" + newFactory(security)->toCString();
483 }
484
Yifan Hong1deca4b2021-09-10 16:16:44 -0700485 static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
486 uint64_t length = str.length();
487 CHECK(android::base::WriteFully(fd, &length, sizeof(length)));
488 CHECK(android::base::WriteFully(fd, str.data(), str.length()));
489 }
490
491 static inline std::string readString(android::base::borrowed_fd fd) {
492 uint64_t length;
493 CHECK(android::base::ReadFully(fd, &length, sizeof(length)));
494 std::string ret(length, '\0');
495 CHECK(android::base::ReadFully(fd, ret.data(), length));
496 return ret;
497 }
498
499 static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
500 Parcel parcel;
501 CHECK_EQ(OK, parcelable.writeToParcel(&parcel));
502 writeString(fd,
503 std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
504 }
505
506 template <typename T>
507 static inline T readFromFd(android::base::borrowed_fd fd) {
508 std::string data = readString(fd);
509 Parcel parcel;
510 CHECK_EQ(OK, parcel.setData(reinterpret_cast<const uint8_t*>(data.data()), data.size()));
511 T object;
512 CHECK_EQ(OK, object.readFromParcel(&parcel));
513 return object;
514 }
515
Steven Morelandc1635952021-04-01 16:20:47 +0000516 // This creates a new process serving an interface on a certain number of
517 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000518 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000519 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
520 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000521
Yifan Hong702115c2021-06-24 15:39:18 -0700522 SocketType socketType = std::get<0>(GetParam());
523 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000524
Steven Morelandda573042021-06-12 01:13:45 +0000525 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000526 std::string addr = allocateSocketAddress();
Steven Morelandc1635952021-04-01 16:20:47 +0000527
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000528 auto ret = ProcessSession{
Yifan Hong1deca4b2021-09-10 16:16:44 -0700529 .host = Process([&](android::base::borrowed_fd writeEnd,
530 android::base::borrowed_fd readEnd) {
531 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
532 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity, certVerifier));
Steven Morelandc1635952021-04-01 16:20:47 +0000533
534 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000535 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000536
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000537 unsigned int outPort = 0;
538
Steven Morelandc1635952021-04-01 16:20:47 +0000539 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700540 case SocketType::PRECONNECTED:
541 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000542 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700543 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000544 break;
545 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700546 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000547 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700548 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700549 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700550 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700551 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700552 }
Steven Morelandc1635952021-04-01 16:20:47 +0000553 default:
554 LOG_ALWAYS_FATAL("Unknown socket type");
555 }
556
Yifan Hong1deca4b2021-09-10 16:16:44 -0700557 BinderRpcTestServerInfo serverInfo;
558 serverInfo.port = static_cast<int64_t>(outPort);
559 serverInfo.cert.data = server->getCertificate(CertificateFormat::PEM);
560 writeToFd(writeEnd, serverInfo);
561 auto clientInfo = readFromFd<BinderRpcTestClientInfo>(readEnd);
562
563 if (rpcSecurity == RpcSecurity::TLS) {
564 for (const auto& clientCert : clientInfo.certs) {
565 CHECK_EQ(OK,
566 certVerifier->addTrustedPeerCertificate(CertificateFormat::PEM,
567 clientCert.data));
568 }
569 }
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000570
Steven Moreland611d15f2021-05-01 01:28:27 +0000571 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000572
Steven Morelandf137de92021-04-24 01:54:26 +0000573 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000574
575 // Another thread calls shutdown. Wait for it to complete.
576 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000577 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000578 };
579
Yifan Hong1deca4b2021-09-10 16:16:44 -0700580 std::vector<sp<RpcSession>> sessions;
581 auto certVerifier = std::make_shared<RpcCertificateVerifierSimple>();
582 for (size_t i = 0; i < options.numSessions; i++) {
583 sessions.emplace_back(RpcSession::make(newFactory(rpcSecurity, certVerifier)));
584 }
585
586 auto serverInfo = readFromFd<BinderRpcTestServerInfo>(ret.host.readEnd());
587 BinderRpcTestClientInfo clientInfo;
588 for (const auto& session : sessions) {
589 auto& parcelableCert = clientInfo.certs.emplace_back();
590 parcelableCert.data = session->getCertificate(CertificateFormat::PEM);
591 }
592 writeToFd(ret.host.writeEnd(), clientInfo);
593
594 CHECK_LE(serverInfo.port, std::numeric_limits<unsigned int>::max());
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700595 if (socketType == SocketType::INET) {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700596 CHECK_NE(0, serverInfo.port);
597 }
598
599 if (rpcSecurity == RpcSecurity::TLS) {
600 const auto& serverCert = serverInfo.cert.data;
601 CHECK_EQ(OK,
602 certVerifier->addTrustedPeerCertificate(CertificateFormat::PEM, serverCert));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700603 }
604
Steven Moreland2372f9d2021-08-05 15:42:01 -0700605 status_t status;
606
Yifan Hong1deca4b2021-09-10 16:16:44 -0700607 for (const auto& session : sessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000608 session->setMaxThreads(options.numIncomingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000609
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000610 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700611 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700612 status = session->setupPreconnectedClient({}, [=]() {
Yifan Hong1deca4b2021-09-10 16:16:44 -0700613 return connectTo(UnixSocketAddress(addr.c_str()));
Steven Moreland2372f9d2021-08-05 15:42:01 -0700614 });
615 if (status == OK) goto success;
Steven Moreland4198a122021-08-03 17:37:58 -0700616 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000617 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700618 status = session->setupUnixDomainClient(addr.c_str());
619 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000620 break;
621 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700622 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
623 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000624 break;
625 case SocketType::INET:
Yifan Hong1deca4b2021-09-10 16:16:44 -0700626 status = session->setupInetClient("127.0.0.1", serverInfo.port);
Steven Moreland2372f9d2021-08-05 15:42:01 -0700627 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000628 break;
629 default:
630 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000631 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700632 LOG_ALWAYS_FATAL("Could not connect %s", statusToString(status).c_str());
Steven Moreland736664b2021-05-01 04:27:25 +0000633 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000634 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000635 }
Steven Morelandc1635952021-04-01 16:20:47 +0000636 return ret;
637 }
638
Steven Moreland4313d7e2021-07-15 23:41:22 +0000639 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000640 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000641 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000642 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000643 sp<MyBinderRpcTest> service =
644 new MyBinderRpcTest;
645 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000646 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000647 }),
648 };
649
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000650 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000651 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
652
653 return ret;
654 }
655};
656
Steven Morelandc1635952021-04-01 16:20:47 +0000657TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000658 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000659 ASSERT_NE(proc.rootBinder, nullptr);
660 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
661}
662
Steven Moreland4cf688f2021-03-31 01:48:58 +0000663TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000664 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000665 ASSERT_NE(proc.rootBinder, nullptr);
666 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
667}
668
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000669TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000670 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000671 for (auto session : proc.proc.sessions) {
672 ASSERT_NE(nullptr, session.root);
673 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000674 }
675}
676
Steven Morelandc1635952021-04-01 16:20:47 +0000677TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000678 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000679 Parcel data;
680 Parcel reply;
681 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
682}
683
Steven Moreland67753c32021-04-02 18:45:19 +0000684TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000685 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000686
687 Parcel p1;
688 p1.markForBinder(proc.rootBinder);
689 p1.writeInt32(3);
690
691 Parcel p2;
692
693 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
694 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
695}
696
Steven Morelandc1635952021-04-01 16:20:47 +0000697TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000698 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000699 Parcel data;
700 data.markForBinder(proc.rootBinder);
701 Parcel reply;
702 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
703}
704
Steven Morelandc1635952021-04-01 16:20:47 +0000705TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000706 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000707 EXPECT_OK(proc.rootIface->sendString("asdf"));
708}
709
Steven Morelandc1635952021-04-01 16:20:47 +0000710TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000711 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000712 std::string doubled;
713 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
714 EXPECT_EQ("cool cool ", doubled);
715}
716
Steven Morelandc1635952021-04-01 16:20:47 +0000717TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000718 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000719 std::string single = std::string(1024, 'a');
720 std::string doubled;
721 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
722 EXPECT_EQ(single + single, doubled);
723}
724
Steven Morelandc1635952021-04-01 16:20:47 +0000725TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000726 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000727
728 int32_t pingResult;
729 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
730 EXPECT_EQ(OK, pingResult);
731
732 EXPECT_EQ(0, MyBinderRpcSession::gNum);
733}
734
Steven Morelandc1635952021-04-01 16:20:47 +0000735TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000736 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000737
738 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
739 sp<IBinder> outBinder;
740 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
741 EXPECT_EQ(inBinder, outBinder);
742
743 wp<IBinder> weak = inBinder;
744 inBinder = nullptr;
745 outBinder = nullptr;
746
747 // Force reading a reply, to process any pending dec refs from the other
748 // process (the other process will process dec refs there before processing
749 // the ping here).
750 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
751
752 EXPECT_EQ(nullptr, weak.promote());
753
754 EXPECT_EQ(0, MyBinderRpcSession::gNum);
755}
756
Steven Morelandc1635952021-04-01 16:20:47 +0000757TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000758 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000759
760 sp<IBinderRpcSession> session;
761 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
762
763 sp<IBinder> inBinder = IInterface::asBinder(session);
764 sp<IBinder> outBinder;
765 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
766 EXPECT_EQ(inBinder, outBinder);
767
768 wp<IBinder> weak = inBinder;
769 session = nullptr;
770 inBinder = nullptr;
771 outBinder = nullptr;
772
773 // Force reading a reply, to process any pending dec refs from the other
774 // process (the other process will process dec refs there before processing
775 // the ping here).
776 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
777
778 EXPECT_EQ(nullptr, weak.promote());
779}
780
Steven Morelandc1635952021-04-01 16:20:47 +0000781TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000782 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000783
784 sp<IBinder> outBinder;
785 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
786 EXPECT_EQ(nullptr, outBinder);
787}
788
Steven Morelandc1635952021-04-01 16:20:47 +0000789TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000790 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000791
792 IBinder* ptr = nullptr;
793 {
794 sp<IBinder> binder = new BBinder();
795 ptr = binder.get();
796 EXPECT_OK(proc.rootIface->holdBinder(binder));
797 }
798
799 sp<IBinder> held;
800 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
801
802 EXPECT_EQ(held.get(), ptr);
803
804 // stop holding binder, because we test to make sure references are cleaned
805 // up
806 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
807 // and flush ref counts
808 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
809}
810
811// START TESTS FOR LIMITATIONS OF SOCKET BINDER
812// These are behavioral differences form regular binder, where certain usecases
813// aren't supported.
814
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000815TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000816 auto proc1 = createRpcTestSocketServerProcess({});
817 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000818
819 sp<IBinder> outBinder;
820 EXPECT_EQ(INVALID_OPERATION,
821 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
822}
823
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000824TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000825 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000826
827 sp<IBinder> outBinder;
828 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000829 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000830 .transactionError());
831}
832
Steven Morelandc1635952021-04-01 16:20:47 +0000833TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000834 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000835
836 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
837 sp<IBinder> outBinder;
838 EXPECT_EQ(INVALID_OPERATION,
839 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
840}
841
Steven Morelandc1635952021-04-01 16:20:47 +0000842TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000843 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000844
845 // for historical reasons, IServiceManager interface only returns the
846 // exception code
847 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
848 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
849}
850
851// END TESTS FOR LIMITATIONS OF SOCKET BINDER
852
Steven Morelandc1635952021-04-01 16:20:47 +0000853TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000854 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000855
856 sp<IBinder> outBinder;
857 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
858 EXPECT_EQ(proc.rootBinder, outBinder);
859}
860
Steven Morelandc1635952021-04-01 16:20:47 +0000861TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000862 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000863
864 auto nastyNester = sp<MyBinderRpcTest>::make();
865 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
866
867 wp<IBinder> weak = nastyNester;
868 nastyNester = nullptr;
869 EXPECT_EQ(nullptr, weak.promote());
870}
871
Steven Morelandc1635952021-04-01 16:20:47 +0000872TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000873 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000874
875 sp<IBinder> a;
876 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
877
878 sp<IBinder> b;
879 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
880
881 EXPECT_EQ(a, b);
882}
883
Steven Morelandc1635952021-04-01 16:20:47 +0000884TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000885 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000886
887 sp<IBinder> a;
888 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
889 wp<IBinder> weak = a;
890 a = nullptr;
891
892 sp<IBinder> b;
893 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
894
895 // this is the wrong behavior, since BpBinder
896 // doesn't implement onIncStrongAttempted
897 // but make sure there is no crash
898 EXPECT_EQ(nullptr, weak.promote());
899
900 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
901
902 // In order to fix this:
903 // - need to have incStrongAttempted reflected across IPC boundary (wait for
904 // response to promote - round trip...)
905 // - sendOnLastWeakRef, to delete entries out of RpcState table
906 EXPECT_EQ(b, weak.promote());
907}
908
909#define expectSessions(expected, iface) \
910 do { \
911 int session; \
912 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
913 EXPECT_EQ(expected, session); \
914 } while (false)
915
Steven Morelandc1635952021-04-01 16:20:47 +0000916TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000917 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000918
919 sp<IBinderRpcSession> session;
920 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
921 std::string out;
922 EXPECT_OK(session->getName(&out));
923 EXPECT_EQ("aoeu", out);
924
925 expectSessions(1, proc.rootIface);
926 session = nullptr;
927 expectSessions(0, proc.rootIface);
928}
929
Steven Morelandc1635952021-04-01 16:20:47 +0000930TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000931 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000932
933 std::vector<sp<IBinderRpcSession>> sessions;
934
935 for (size_t i = 0; i < 15; i++) {
936 expectSessions(i, proc.rootIface);
937 sp<IBinderRpcSession> session;
938 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
939 sessions.push_back(session);
940 }
941 expectSessions(sessions.size(), proc.rootIface);
942 for (size_t i = 0; i < sessions.size(); i++) {
943 std::string out;
944 EXPECT_OK(sessions.at(i)->getName(&out));
945 EXPECT_EQ(std::to_string(i), out);
946 }
947 expectSessions(sessions.size(), proc.rootIface);
948
949 while (!sessions.empty()) {
950 sessions.pop_back();
951 expectSessions(sessions.size(), proc.rootIface);
952 }
953 expectSessions(0, proc.rootIface);
954}
955
956size_t epochMillis() {
957 using std::chrono::duration_cast;
958 using std::chrono::milliseconds;
959 using std::chrono::seconds;
960 using std::chrono::system_clock;
961 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
962}
963
Steven Morelandc1635952021-04-01 16:20:47 +0000964TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000965 constexpr size_t kNumThreads = 10;
966
Steven Moreland4313d7e2021-07-15 23:41:22 +0000967 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000968
969 EXPECT_OK(proc.rootIface->lock());
970
971 // block all but one thread taking locks
972 std::vector<std::thread> ts;
973 for (size_t i = 0; i < kNumThreads - 1; i++) {
974 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
975 }
976
977 usleep(100000); // give chance for calls on other threads
978
979 // other calls still work
980 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
981
982 constexpr size_t blockTimeMs = 500;
983 size_t epochMsBefore = epochMillis();
984 // after this, we should never see a response within this time
985 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
986
987 // this call should be blocked for blockTimeMs
988 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
989
990 size_t epochMsAfter = epochMillis();
991 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
992
993 for (auto& t : ts) t.join();
994}
995
Steven Morelandc1635952021-04-01 16:20:47 +0000996TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000997 constexpr size_t kNumThreads = 10;
998 constexpr size_t kNumCalls = kNumThreads + 3;
999 constexpr size_t kSleepMs = 500;
1000
Steven Moreland4313d7e2021-07-15 23:41:22 +00001001 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001002
1003 size_t epochMsBefore = epochMillis();
1004
1005 std::vector<std::thread> ts;
1006 for (size_t i = 0; i < kNumCalls; i++) {
1007 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
1008 }
1009
1010 for (auto& t : ts) t.join();
1011
1012 size_t epochMsAfter = epochMillis();
1013
1014 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
1015
1016 // Potential flake, but make sure calls are handled in parallel.
1017 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
1018}
1019
Steven Morelandc1635952021-04-01 16:20:47 +00001020TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001021 constexpr size_t kNumClientThreads = 10;
1022 constexpr size_t kNumServerThreads = 10;
1023 constexpr size_t kNumCalls = 100;
1024
Steven Moreland4313d7e2021-07-15 23:41:22 +00001025 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001026
1027 std::vector<std::thread> threads;
1028 for (size_t i = 0; i < kNumClientThreads; i++) {
1029 threads.push_back(std::thread([&] {
1030 for (size_t j = 0; j < kNumCalls; j++) {
1031 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +00001032 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +00001033 EXPECT_EQ(proc.rootBinder, out);
1034 }
1035 }));
1036 }
1037
1038 for (auto& t : threads) t.join();
1039}
1040
Steven Morelandc6046982021-04-20 00:49:42 +00001041TEST_P(BinderRpc, OnewayStressTest) {
1042 constexpr size_t kNumClientThreads = 10;
1043 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +00001044 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +00001045
Steven Moreland4313d7e2021-07-15 23:41:22 +00001046 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +00001047
1048 std::vector<std::thread> threads;
1049 for (size_t i = 0; i < kNumClientThreads; i++) {
1050 threads.push_back(std::thread([&] {
1051 for (size_t j = 0; j < kNumCalls; j++) {
1052 EXPECT_OK(proc.rootIface->sendString("a"));
1053 }
1054
1055 // check threads are not stuck
1056 EXPECT_OK(proc.rootIface->sleepMs(250));
1057 }));
1058 }
1059
1060 for (auto& t : threads) t.join();
1061}
1062
Steven Morelandc1635952021-04-01 16:20:47 +00001063TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001064 constexpr size_t kReallyLongTimeMs = 100;
1065 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
1066
Steven Moreland4313d7e2021-07-15 23:41:22 +00001067 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001068
1069 size_t epochMsBefore = epochMillis();
1070
1071 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
1072
1073 size_t epochMsAfter = epochMillis();
1074 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1075}
1076
Steven Morelandc1635952021-04-01 16:20:47 +00001077TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001078 constexpr size_t kNumSleeps = 10;
1079 constexpr size_t kNumExtraServerThreads = 4;
1080 constexpr size_t kSleepMs = 50;
1081
1082 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001083 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001084
1085 EXPECT_OK(proc.rootIface->lock());
1086
1087 for (size_t i = 0; i < kNumSleeps; i++) {
1088 // these should be processed serially
1089 proc.rootIface->sleepMsAsync(kSleepMs);
1090 }
1091 // should also be processesed serially
1092 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1093
1094 size_t epochMsBefore = epochMillis();
1095 EXPECT_OK(proc.rootIface->lockUnlock());
1096 size_t epochMsAfter = epochMillis();
1097
1098 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001099
1100 // pending oneway transactions hold ref, make sure we read data on all
1101 // sockets
1102 std::vector<std::thread> threads;
1103 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
1104 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
1105 }
1106 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +00001107}
1108
Steven Morelandd45be622021-06-04 02:19:37 +00001109TEST_P(BinderRpc, OnewayCallExhaustion) {
1110 constexpr size_t kNumClients = 2;
1111 constexpr size_t kTooLongMs = 1000;
1112
Steven Moreland4313d7e2021-07-15 23:41:22 +00001113 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001114
1115 // Build up oneway calls on the second session to make sure it terminates
1116 // and shuts down. The first session should be unaffected (proc destructor
1117 // checks the first session).
1118 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1119
1120 std::vector<std::thread> threads;
1121 for (size_t i = 0; i < kNumClients; i++) {
1122 // one of these threads will get stuck queueing a transaction once the
1123 // socket fills up, the other will be able to fill up transactions on
1124 // this object
1125 threads.push_back(std::thread([&] {
1126 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1127 }
1128 }));
1129 }
1130 for (auto& t : threads) t.join();
1131
1132 Status status = iface->sleepMsAsync(kTooLongMs);
1133 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1134
Steven Moreland798e0d12021-07-14 23:19:25 +00001135 // now that it has died, wait for the remote session to shutdown
1136 std::vector<int32_t> remoteCounts;
1137 do {
1138 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1139 } while (remoteCounts.size() == kNumClients);
1140
Steven Morelandd45be622021-06-04 02:19:37 +00001141 // the second session should be shutdown in the other process by the time we
1142 // are able to join above (it'll only be hung up once it finishes processing
1143 // any pending commands). We need to erase this session from the record
1144 // here, so that the destructor for our session won't check that this
1145 // session is valid, but we still want it to test the other session.
1146 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1147}
1148
Steven Moreland659416d2021-05-11 00:47:50 +00001149TEST_P(BinderRpc, Callbacks) {
1150 const static std::string kTestString = "good afternoon!";
1151
Steven Morelandc7d40132021-06-10 03:42:11 +00001152 for (bool callIsOneway : {true, false}) {
1153 for (bool callbackIsOneway : {true, false}) {
1154 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001155 auto proc = createRpcTestSocketServerProcess(
1156 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001157 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001158
Steven Morelandc7d40132021-06-10 03:42:11 +00001159 if (callIsOneway) {
1160 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1161 kTestString));
1162 } else {
1163 EXPECT_OK(
1164 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1165 }
Steven Moreland659416d2021-05-11 00:47:50 +00001166
Steven Morelandc7d40132021-06-10 03:42:11 +00001167 using std::literals::chrono_literals::operator""s;
1168 std::unique_lock<std::mutex> _l(cb->mMutex);
1169 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001170
Steven Morelandc7d40132021-06-10 03:42:11 +00001171 EXPECT_EQ(cb->mValues.size(), 1)
1172 << "callIsOneway: " << callIsOneway
1173 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1174 if (cb->mValues.empty()) continue;
1175 EXPECT_EQ(cb->mValues.at(0), kTestString)
1176 << "callIsOneway: " << callIsOneway
1177 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001178
Steven Morelandc7d40132021-06-10 03:42:11 +00001179 // since we are severing the connection, we need to go ahead and
1180 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001181 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1182 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1183 }
Steven Moreland659416d2021-05-11 00:47:50 +00001184
Steven Moreland1b304292021-07-15 22:59:34 +00001185 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001186 // need to manually shut it down
1187 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001188
Steven Morelandc7d40132021-06-10 03:42:11 +00001189 proc.expectAlreadyShutdown = true;
1190 }
Steven Moreland659416d2021-05-11 00:47:50 +00001191 }
1192 }
1193}
1194
Steven Moreland195edb82021-06-08 02:44:39 +00001195TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001196 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001197 auto cb = sp<MyBinderRpcCallback>::make();
1198
1199 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1200 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1201}
1202
Steven Morelandc1635952021-04-01 16:20:47 +00001203TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001204 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001205 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001206
1207 // make sure there is some state during crash
1208 // 1. we hold their binder
1209 sp<IBinderRpcSession> session;
1210 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1211 // 2. they hold our binder
1212 sp<IBinder> binder = new BBinder();
1213 EXPECT_OK(proc.rootIface->holdBinder(binder));
1214
1215 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1216 << "Do death cleanup: " << doDeathCleanup;
1217
Steven Morelandaf4ca712021-05-24 23:22:08 +00001218 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001219 }
1220}
1221
Steven Morelandd7302072021-05-15 01:32:04 +00001222TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001223 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001224
1225 // we can't allocate IPCThreadState so actually the first time should
1226 // succeed :(
1227 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1228
1229 // second time! we catch the error :)
1230 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1231
Steven Morelandaf4ca712021-05-24 23:22:08 +00001232 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001233}
1234
Steven Moreland37aff182021-03-26 02:04:16 +00001235TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001236 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001237
1238 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1239 ASSERT_NE(binder, nullptr);
1240
1241 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1242}
1243
1244TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001245 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001246
1247 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1248 ASSERT_NE(binder, nullptr);
1249
1250 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1251 ASSERT_NE(ndkBinder, nullptr);
1252
1253 std::string out;
1254 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1255 ASSERT_TRUE(status.isOk()) << status.getDescription();
1256 ASSERT_EQ("aoeuaoeu", out);
1257}
1258
Steven Moreland5553ac42020-11-11 02:14:45 +00001259ssize_t countFds() {
1260 DIR* dir = opendir("/proc/self/fd/");
1261 if (dir == nullptr) return -1;
1262 ssize_t ret = 0;
1263 dirent* ent;
1264 while ((ent = readdir(dir)) != nullptr) ret++;
1265 closedir(dir);
1266 return ret;
1267}
1268
Steven Morelandc1635952021-04-01 16:20:47 +00001269TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001270 ssize_t beforeFds = countFds();
1271 ASSERT_GE(beforeFds, 0);
1272 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001273 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001274 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1275 }
1276 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1277}
1278
Steven Morelandda573042021-06-12 01:13:45 +00001279static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001280 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001281 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001282 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001283 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland1eab3452021-08-05 16:56:20 -07001284 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1285 if (status == -EAFNOSUPPORT) {
1286 return false;
1287 }
1288 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1289 }
Steven Morelandda573042021-06-12 01:13:45 +00001290 server->start();
1291
Yifan Hongfdd9f692021-09-09 15:12:52 -07001292 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001293 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001294 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001295 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1296 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001297}
1298
Yifan Hong1deca4b2021-09-10 16:16:44 -07001299static std::vector<SocketType> testSocketTypes(bool hasPreconnected = true) {
1300 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1301
1302 if (hasPreconnected) ret.push_back(SocketType::PRECONNECTED);
Steven Morelandda573042021-06-12 01:13:45 +00001303
1304 static bool hasVsockLoopback = testSupportVsockLoopback();
1305
1306 if (hasVsockLoopback) {
1307 ret.push_back(SocketType::VSOCK);
1308 }
1309
1310 return ret;
1311}
1312
Yifan Hong702115c2021-06-24 15:39:18 -07001313INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1314 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1315 ::testing::ValuesIn(RpcSecurityValues())),
1316 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001317
Yifan Hong702115c2021-06-24 15:39:18 -07001318class BinderRpcServerRootObject
1319 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001320
1321TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1322 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1323 auto setRootObject = [](bool isStrong) -> SetFn {
1324 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1325 };
1326
Yifan Hong702115c2021-06-24 15:39:18 -07001327 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1328 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001329 auto binder1 = sp<BBinder>::make();
1330 IBinder* binderRaw1 = binder1.get();
1331 setRootObject(isStrong1)(server.get(), binder1);
1332 EXPECT_EQ(binderRaw1, server->getRootObject());
1333 binder1.clear();
1334 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1335
1336 auto binder2 = sp<BBinder>::make();
1337 IBinder* binderRaw2 = binder2.get();
1338 setRootObject(isStrong2)(server.get(), binder2);
1339 EXPECT_EQ(binderRaw2, server->getRootObject());
1340 binder2.clear();
1341 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1342}
1343
1344INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001345 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1346 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001347
Yifan Hong1a235852021-05-13 16:07:47 -07001348class OneOffSignal {
1349public:
1350 // If notify() was previously called, or is called within |duration|, return true; else false.
1351 template <typename R, typename P>
1352 bool wait(std::chrono::duration<R, P> duration) {
1353 std::unique_lock<std::mutex> lock(mMutex);
1354 return mCv.wait_for(lock, duration, [this] { return mValue; });
1355 }
1356 void notify() {
1357 std::unique_lock<std::mutex> lock(mMutex);
1358 mValue = true;
1359 lock.unlock();
1360 mCv.notify_all();
1361 }
1362
1363private:
1364 std::mutex mMutex;
1365 std::condition_variable mCv;
1366 bool mValue = false;
1367};
1368
Yifan Hong702115c2021-06-24 15:39:18 -07001369TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001370 auto addr = allocateSocketAddress();
Yifan Hong702115c2021-06-24 15:39:18 -07001371 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong1a235852021-05-13 16:07:47 -07001372 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001373 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001374 auto joinEnds = std::make_shared<OneOffSignal>();
1375
1376 // If things are broken and the thread never stops, don't block other tests. Because the thread
1377 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1378 // shared pointers are passed.
1379 std::thread([server, joinEnds] {
1380 server->join();
1381 joinEnds->notify();
1382 }).detach();
1383
1384 bool shutdown = false;
1385 for (int i = 0; i < 10 && !shutdown; i++) {
1386 usleep(300 * 1000); // 300ms; total 3s
1387 if (server->shutdown()) shutdown = true;
1388 }
1389 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1390
1391 ASSERT_TRUE(joinEnds->wait(2s))
1392 << "After server->shutdown() returns true, join() did not stop after 2s";
1393}
1394
Yifan Hong194acf22021-06-29 18:44:56 -07001395TEST(BinderRpc, Java) {
1396#if !defined(__ANDROID__)
1397 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1398 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1399 "to binderHostDeviceTest. Hence, just disable this test on host.";
1400#endif // !__ANDROID__
1401 sp<IServiceManager> sm = defaultServiceManager();
1402 ASSERT_NE(nullptr, sm);
1403 // Any Java service with non-empty getInterfaceDescriptor() would do.
1404 // Let's pick batteryproperties.
1405 auto binder = sm->checkService(String16("batteryproperties"));
1406 ASSERT_NE(nullptr, binder);
1407 auto descriptor = binder->getInterfaceDescriptor();
1408 ASSERT_GE(descriptor.size(), 0);
1409 ASSERT_EQ(OK, binder->pingBinder());
1410
1411 auto rpcServer = RpcServer::make();
1412 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1413 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001414 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001415 auto socket = rpcServer->releaseServer();
1416
1417 auto keepAlive = sp<BBinder>::make();
1418 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1419
1420 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001421 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001422 auto rpcBinder = rpcSession->getRootObject();
1423 ASSERT_NE(nullptr, rpcBinder);
1424
1425 ASSERT_EQ(OK, rpcBinder->pingBinder());
1426
1427 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1428 << "getInterfaceDescriptor should not crash system_server";
1429 ASSERT_EQ(OK, rpcBinder->pingBinder());
1430}
1431
Yifan Hong702115c2021-06-24 15:39:18 -07001432INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1433 BinderRpcSimple::PrintTestParam);
1434
Yifan Hong1deca4b2021-09-10 16:16:44 -07001435class RpcTransportTest
1436 : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity, CertificateFormat>> {
1437public:
1438 using ConnectToServer = std::function<base::unique_fd()>;
1439 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
1440 auto [socketType, rpcSecurity, certificateFormat] = info.param;
1441 return PrintToString(socketType) + "_" + newFactory(rpcSecurity)->toCString() + "_" +
1442 PrintToString(certificateFormat);
1443 }
1444 void TearDown() override {
1445 for (auto& server : mServers) server->shutdown();
1446 }
1447
1448 // A server that handles client socket connections.
1449 class Server {
1450 public:
1451 explicit Server() {}
1452 Server(Server&&) = default;
1453 ~Server() { shutdown(); }
1454 [[nodiscard]] AssertionResult setUp() {
1455 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1456 auto rpcServer = RpcServer::make(newFactory(rpcSecurity));
1457 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1458 switch (socketType) {
1459 case SocketType::PRECONNECTED: {
1460 return AssertionFailure() << "Not supported by this test";
1461 } break;
1462 case SocketType::UNIX: {
1463 auto addr = allocateSocketAddress();
1464 auto status = rpcServer->setupUnixDomainServer(addr.c_str());
1465 if (status != OK) {
1466 return AssertionFailure()
1467 << "setupUnixDomainServer: " << statusToString(status);
1468 }
1469 mConnectToServer = [addr] {
1470 return connectTo(UnixSocketAddress(addr.c_str()));
1471 };
1472 } break;
1473 case SocketType::VSOCK: {
1474 auto port = allocateVsockPort();
1475 auto status = rpcServer->setupVsockServer(port);
1476 if (status != OK) {
1477 return AssertionFailure() << "setupVsockServer: " << statusToString(status);
1478 }
1479 mConnectToServer = [port] {
1480 return connectTo(VsockSocketAddress(VMADDR_CID_LOCAL, port));
1481 };
1482 } break;
1483 case SocketType::INET: {
1484 unsigned int port;
1485 auto status = rpcServer->setupInetServer(kLocalInetAddress, 0, &port);
1486 if (status != OK) {
1487 return AssertionFailure() << "setupInetServer: " << statusToString(status);
1488 }
1489 mConnectToServer = [port] {
1490 const char* addr = kLocalInetAddress;
1491 auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
1492 if (aiStart == nullptr) return base::unique_fd{};
1493 for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
1494 auto fd = connectTo(
1495 InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
1496 if (fd.ok()) return fd;
1497 }
1498 ALOGE("None of the socket address resolved for %s:%u can be connected",
1499 addr, port);
1500 return base::unique_fd{};
1501 };
1502 }
1503 }
1504 mFd = rpcServer->releaseServer();
1505 if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
1506 mCtx = newFactory(rpcSecurity, mCertVerifier)->newServerCtx();
1507 if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
1508 mSetup = true;
1509 return AssertionSuccess();
1510 }
1511 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1512 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1513 return mCertVerifier;
1514 }
1515 ConnectToServer getConnectToServerFn() { return mConnectToServer; }
1516 void start() {
1517 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1518 mThread = std::make_unique<std::thread>(&Server::run, this);
1519 }
1520 void run() {
1521 LOG_ALWAYS_FATAL_IF(!mSetup, "Call Server::setup first!");
1522
1523 std::vector<std::thread> threads;
1524 while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
1525 base::unique_fd acceptedFd(
1526 TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
1527 SOCK_CLOEXEC | SOCK_NONBLOCK)));
1528 threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
1529 }
1530
1531 for (auto& thread : threads) thread.join();
1532 }
1533 void handleOne(android::base::unique_fd acceptedFd) {
1534 ASSERT_TRUE(acceptedFd.ok());
1535 auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
1536 if (serverTransport == nullptr) return; // handshake failed
1537 std::string message(kMessage);
1538 ASSERT_EQ(OK,
1539 serverTransport->interruptableWriteFully(mFdTrigger.get(), message.data(),
1540 message.size()));
1541 }
1542 void shutdown() {
1543 mFdTrigger->trigger();
1544 if (mThread != nullptr) {
1545 mThread->join();
1546 mThread = nullptr;
1547 }
1548 }
1549
1550 private:
1551 std::unique_ptr<std::thread> mThread;
1552 ConnectToServer mConnectToServer;
1553 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1554 base::unique_fd mFd;
1555 std::unique_ptr<RpcTransportCtx> mCtx;
1556 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1557 std::make_shared<RpcCertificateVerifierSimple>();
1558 bool mSetup = false;
1559 };
1560
1561 class Client {
1562 public:
1563 explicit Client(ConnectToServer connectToServer) : mConnectToServer(connectToServer) {}
1564 Client(Client&&) = default;
1565 [[nodiscard]] AssertionResult setUp() {
1566 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1567 mFd = mConnectToServer();
1568 if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
1569 mFdTrigger = FdTrigger::make();
1570 mCtx = newFactory(rpcSecurity, mCertVerifier)->newClientCtx();
1571 if (mCtx == nullptr) return AssertionFailure() << "newClientCtx";
1572 return AssertionSuccess();
1573 }
1574 RpcTransportCtx* getCtx() const { return mCtx.get(); }
1575 std::shared_ptr<RpcCertificateVerifierSimple> getCertVerifier() const {
1576 return mCertVerifier;
1577 }
1578 void run(bool handshakeOk = true, bool readOk = true) {
1579 auto clientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
1580 if (clientTransport == nullptr) {
1581 ASSERT_FALSE(handshakeOk) << "newTransport returns nullptr, but it shouldn't";
1582 return;
1583 }
1584 ASSERT_TRUE(handshakeOk) << "newTransport does not return nullptr, but it should";
1585 std::string expectedMessage(kMessage);
1586 std::string readMessage(expectedMessage.size(), '\0');
1587 status_t readStatus =
1588 clientTransport->interruptableReadFully(mFdTrigger.get(), readMessage.data(),
1589 readMessage.size());
1590 if (readOk) {
1591 ASSERT_EQ(OK, readStatus);
1592 ASSERT_EQ(readMessage, expectedMessage);
1593 } else {
1594 ASSERT_NE(OK, readStatus);
1595 }
1596 }
1597
1598 private:
1599 ConnectToServer mConnectToServer;
1600 base::unique_fd mFd;
1601 std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
1602 std::unique_ptr<RpcTransportCtx> mCtx;
1603 std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
1604 std::make_shared<RpcCertificateVerifierSimple>();
1605 };
1606
1607 // Make A trust B.
1608 template <typename A, typename B>
1609 status_t trust(A* a, B* b) {
1610 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1611 if (rpcSecurity != RpcSecurity::TLS) return OK;
1612 auto bCert = b->getCtx()->getCertificate(certificateFormat);
1613 return a->getCertVerifier()->addTrustedPeerCertificate(certificateFormat, bCert);
1614 }
1615
1616 static constexpr const char* kMessage = "hello";
1617 std::vector<std::unique_ptr<Server>> mServers;
1618};
1619
1620TEST_P(RpcTransportTest, GoodCertificate) {
1621 auto server = mServers.emplace_back(std::make_unique<Server>()).get();
1622 ASSERT_TRUE(server->setUp());
1623
1624 Client client(server->getConnectToServerFn());
1625 ASSERT_TRUE(client.setUp());
1626
1627 ASSERT_EQ(OK, trust(&client, server));
1628 ASSERT_EQ(OK, trust(server, &client));
1629
1630 server->start();
1631 client.run();
1632}
1633
1634TEST_P(RpcTransportTest, MultipleClients) {
1635 auto server = mServers.emplace_back(std::make_unique<Server>()).get();
1636 ASSERT_TRUE(server->setUp());
1637
1638 std::vector<Client> clients;
1639 for (int i = 0; i < 2; i++) {
1640 auto& client = clients.emplace_back(server->getConnectToServerFn());
1641 ASSERT_TRUE(client.setUp());
1642 ASSERT_EQ(OK, trust(&client, server));
1643 ASSERT_EQ(OK, trust(server, &client));
1644 }
1645
1646 server->start();
1647 for (auto& client : clients) client.run();
1648}
1649
1650TEST_P(RpcTransportTest, UntrustedServer) {
1651 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1652
1653 auto untrustedServer = mServers.emplace_back(std::make_unique<Server>()).get();
1654 ASSERT_TRUE(untrustedServer->setUp());
1655
1656 Client client(untrustedServer->getConnectToServerFn());
1657 ASSERT_TRUE(client.setUp());
1658
1659 ASSERT_EQ(OK, trust(untrustedServer, &client));
1660
1661 untrustedServer->start();
1662
1663 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1664 // the client can't verify the server's identity.
1665 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1666 client.run(handshakeOk);
1667}
1668TEST_P(RpcTransportTest, MaliciousServer) {
1669 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1670 auto validServer = mServers.emplace_back(std::make_unique<Server>()).get();
1671 ASSERT_TRUE(validServer->setUp());
1672
1673 auto maliciousServer = mServers.emplace_back(std::make_unique<Server>()).get();
1674 ASSERT_TRUE(maliciousServer->setUp());
1675
1676 Client client(maliciousServer->getConnectToServerFn());
1677 ASSERT_TRUE(client.setUp());
1678
1679 ASSERT_EQ(OK, trust(&client, validServer));
1680 ASSERT_EQ(OK, trust(validServer, &client));
1681 ASSERT_EQ(OK, trust(maliciousServer, &client));
1682
1683 maliciousServer->start();
1684
1685 // For TLS, this should reject the certificate. For RAW sockets, it should pass because
1686 // the client can't verify the server's identity.
1687 bool handshakeOk = rpcSecurity != RpcSecurity::TLS;
1688 client.run(handshakeOk);
1689}
1690
1691TEST_P(RpcTransportTest, UntrustedClient) {
1692 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1693 auto server = mServers.emplace_back(std::make_unique<Server>()).get();
1694 ASSERT_TRUE(server->setUp());
1695
1696 Client client(server->getConnectToServerFn());
1697 ASSERT_TRUE(client.setUp());
1698
1699 ASSERT_EQ(OK, trust(&client, server));
1700
1701 server->start();
1702
1703 // For TLS, Client should be able to verify server's identity, so client should see
1704 // do_handshake() successfully executed. However, server shouldn't be able to verify client's
1705 // identity and should drop the connection, so client shouldn't be able to read anything.
1706 bool readOk = rpcSecurity != RpcSecurity::TLS;
1707 client.run(true, readOk);
1708}
1709
1710TEST_P(RpcTransportTest, MaliciousClient) {
1711 auto [socketType, rpcSecurity, certificateFormat] = GetParam();
1712 auto server = mServers.emplace_back(std::make_unique<Server>()).get();
1713 ASSERT_TRUE(server->setUp());
1714
1715 Client validClient(server->getConnectToServerFn());
1716 ASSERT_TRUE(validClient.setUp());
1717 Client maliciousClient(server->getConnectToServerFn());
1718 ASSERT_TRUE(maliciousClient.setUp());
1719
1720 ASSERT_EQ(OK, trust(&validClient, server));
1721 ASSERT_EQ(OK, trust(&maliciousClient, server));
1722
1723 server->start();
1724
1725 // See UntrustedClient.
1726 bool readOk = rpcSecurity != RpcSecurity::TLS;
1727 maliciousClient.run(true, readOk);
1728}
1729
1730std::vector<CertificateFormat> testCertificateFormats() {
1731 return {
1732 CertificateFormat::PEM,
1733 };
1734}
1735
1736INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
1737 ::testing::Combine(::testing::ValuesIn(testSocketTypes(false)),
1738 ::testing::ValuesIn(RpcSecurityValues()),
1739 ::testing::ValuesIn(testCertificateFormats())),
1740 RpcTransportTest::PrintParamInfo);
1741
Steven Morelandc1635952021-04-01 16:20:47 +00001742} // namespace android
1743
1744int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001745 ::testing::InitGoogleTest(&argc, argv);
1746 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1747 return RUN_ALL_TESTS();
1748}