blob: 8a03de22a9887a91d9b4b318a135fa5db35ea64e [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
Steven Moreland659416d2021-05-11 00:47:50 +000017#include <BnBinderRpcCallback.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000018#include <BnBinderRpcSession.h>
19#include <BnBinderRpcTest.h>
Steven Moreland37aff182021-03-26 02:04:16 +000020#include <aidl/IBinderRpcTest.h>
Yifan Hong6d82c8a2021-04-26 20:26:45 -070021#include <android-base/file.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000022#include <android-base/logging.h>
Steven Moreland37aff182021-03-26 02:04:16 +000023#include <android/binder_auto_utils.h>
24#include <android/binder_libbinder.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000025#include <binder/Binder.h>
26#include <binder/BpBinder.h>
Steven Morelandd7302072021-05-15 01:32:04 +000027#include <binder/IPCThreadState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000028#include <binder/IServiceManager.h>
29#include <binder/ProcessState.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000030#include <binder/RpcServer.h>
Steven Morelandbdb53ab2021-05-05 17:57:41 +000031#include <binder/RpcSession.h>
Yifan Hong702115c2021-06-24 15:39:18 -070032#include <binder/RpcTransport.h>
33#include <binder/RpcTransportRaw.h>
Yifan Hong92409752021-07-30 21:25:32 -070034#include <binder/RpcTransportTls.h>
Steven Moreland5553ac42020-11-11 02:14:45 +000035#include <gtest/gtest.h>
36
Steven Morelandc1635952021-04-01 16:20:47 +000037#include <chrono>
38#include <cstdlib>
39#include <iostream>
40#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000041#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000042
Steven Morelandc1635952021-04-01 16:20:47 +000043#include <sys/prctl.h>
44#include <unistd.h>
45
Steven Moreland4198a122021-08-03 17:37:58 -070046#include "../RpcSocketAddress.h" // for testing preconnected clients
Steven Morelandbd5002b2021-05-04 23:12:56 +000047#include "../RpcState.h" // for debugging
48#include "../vm_sockets.h" // for VMADDR_*
Yifan Hong13c90062021-09-09 14:59:53 -070049#include "RpcCertificateVerifierSimple.h"
Steven Moreland5553ac42020-11-11 02:14:45 +000050
Yifan Hong1a235852021-05-13 16:07:47 -070051using namespace std::chrono_literals;
52
Steven Moreland5553ac42020-11-11 02:14:45 +000053namespace android {
54
Steven Morelandbf57bce2021-07-26 15:26:12 -070055static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
56 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
Devin Mooref3b9c4f2021-08-03 15:50:13 +000057const char* kLocalInetAddress = "127.0.0.1";
Steven Morelandbf57bce2021-07-26 15:26:12 -070058
Yifan Hong92409752021-07-30 21:25:32 -070059enum class RpcSecurity { RAW, TLS };
Yifan Hong702115c2021-06-24 15:39:18 -070060
61static inline std::vector<RpcSecurity> RpcSecurityValues() {
Yifan Hong92409752021-07-30 21:25:32 -070062 return {RpcSecurity::RAW, RpcSecurity::TLS};
Yifan Hong702115c2021-06-24 15:39:18 -070063}
64
Yifan Hong13c90062021-09-09 14:59:53 -070065static inline std::unique_ptr<RpcTransportCtxFactory> newFactory(
66 RpcSecurity rpcSecurity, std::shared_ptr<RpcCertificateVerifier> verifier = nullptr) {
Yifan Hong702115c2021-06-24 15:39:18 -070067 switch (rpcSecurity) {
68 case RpcSecurity::RAW:
69 return RpcTransportCtxFactoryRaw::make();
Yifan Hong13c90062021-09-09 14:59:53 -070070 case RpcSecurity::TLS: {
71 // TODO(b/198833574): exchange keys and set proper verifier
72 if (verifier == nullptr) {
73 verifier = std::make_shared<RpcCertificateVerifierSimple>();
74 }
75 return RpcTransportCtxFactoryTls::make(std::move(verifier));
76 }
Yifan Hong702115c2021-06-24 15:39:18 -070077 default:
78 LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity);
79 }
80}
81
Steven Moreland1fda67b2021-04-02 18:35:50 +000082TEST(BinderRpcParcel, EntireParcelFormatted) {
83 Parcel p;
84 p.writeInt32(3);
85
86 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
87}
88
Yifan Hong702115c2021-06-24 15:39:18 -070089class BinderRpcSimple : public ::testing::TestWithParam<RpcSecurity> {
90public:
91 static std::string PrintTestParam(const ::testing::TestParamInfo<ParamType>& info) {
92 return newFactory(info.param)->toCString();
93 }
94};
95
96TEST_P(BinderRpcSimple, SetExternalServerTest) {
Yifan Hong00aeb762021-05-12 17:07:36 -070097 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
98 int sinkFd = sink.get();
Yifan Hong702115c2021-06-24 15:39:18 -070099 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong00aeb762021-05-12 17:07:36 -0700100 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
101 ASSERT_FALSE(server->hasServer());
Steven Moreland2372f9d2021-08-05 15:42:01 -0700102 ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
Yifan Hong00aeb762021-05-12 17:07:36 -0700103 ASSERT_TRUE(server->hasServer());
104 base::unique_fd retrieved = server->releaseServer();
105 ASSERT_FALSE(server->hasServer());
106 ASSERT_EQ(sinkFd, retrieved.get());
107}
108
Steven Morelandbf57bce2021-07-26 15:26:12 -0700109TEST(BinderRpc, CannotUseNextWireVersion) {
110 auto session = RpcSession::make();
111 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
112 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
113 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
114 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
115}
116
117TEST(BinderRpc, CanUseExperimentalWireVersion) {
118 auto session = RpcSession::make();
119 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
120}
121
Steven Moreland5553ac42020-11-11 02:14:45 +0000122using android::binder::Status;
123
124#define EXPECT_OK(status) \
125 do { \
126 Status stat = (status); \
127 EXPECT_TRUE(stat.isOk()) << stat; \
128 } while (false)
129
130class MyBinderRpcSession : public BnBinderRpcSession {
131public:
132 static std::atomic<int32_t> gNum;
133
134 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
135 Status getName(std::string* name) override {
136 *name = mName;
137 return Status::ok();
138 }
139 ~MyBinderRpcSession() { gNum--; }
140
141private:
142 std::string mName;
143};
144std::atomic<int32_t> MyBinderRpcSession::gNum;
145
Steven Moreland659416d2021-05-11 00:47:50 +0000146class MyBinderRpcCallback : public BnBinderRpcCallback {
147 Status sendCallback(const std::string& value) {
148 std::unique_lock _l(mMutex);
149 mValues.push_back(value);
150 _l.unlock();
151 mCv.notify_one();
152 return Status::ok();
153 }
154 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
155
156public:
157 std::mutex mMutex;
158 std::condition_variable mCv;
159 std::vector<std::string> mValues;
160};
161
Steven Moreland5553ac42020-11-11 02:14:45 +0000162class MyBinderRpcTest : public BnBinderRpcTest {
163public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000164 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +0000165
166 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000167 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000168 return Status::ok();
169 }
170 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000171 *strstr = str + str;
172 return Status::ok();
173 }
Steven Moreland736664b2021-05-01 04:27:25 +0000174 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000175 sp<RpcServer> spServer = server.promote();
176 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000177 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
178 }
Steven Moreland736664b2021-05-01 04:27:25 +0000179 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000180 for (auto session : spServer->listSessions()) {
181 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000182 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000183 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000184 return Status::ok();
185 }
186 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
187 if (binder == nullptr) {
188 std::cout << "Received null binder!" << std::endl;
189 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
190 }
191 *out = binder->pingBinder();
192 return Status::ok();
193 }
194 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
195 *out = binder;
196 return Status::ok();
197 }
198 static sp<IBinder> mHeldBinder;
199 Status holdBinder(const sp<IBinder>& binder) override {
200 mHeldBinder = binder;
201 return Status::ok();
202 }
203 Status getHeldBinder(sp<IBinder>* held) override {
204 *held = mHeldBinder;
205 return Status::ok();
206 }
207 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
208 if (count <= 0) return Status::ok();
209 return binder->nestMe(this, count - 1);
210 }
211 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
212 static sp<IBinder> binder = new BBinder;
213 *out = binder;
214 return Status::ok();
215 }
216 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
217 *out = new MyBinderRpcSession(name);
218 return Status::ok();
219 }
220 Status getNumOpenSessions(int32_t* out) override {
221 *out = MyBinderRpcSession::gNum;
222 return Status::ok();
223 }
224
225 std::mutex blockMutex;
226 Status lock() override {
227 blockMutex.lock();
228 return Status::ok();
229 }
230 Status unlockInMsAsync(int32_t ms) override {
231 usleep(ms * 1000);
232 blockMutex.unlock();
233 return Status::ok();
234 }
235 Status lockUnlock() override {
236 std::lock_guard<std::mutex> _l(blockMutex);
237 return Status::ok();
238 }
239
240 Status sleepMs(int32_t ms) override {
241 usleep(ms * 1000);
242 return Status::ok();
243 }
244
245 Status sleepMsAsync(int32_t ms) override {
246 // In-process binder calls are asynchronous, but the call to this method
247 // is synchronous wrt its client. This in/out-process threading model
248 // diffentiation is a classic binder leaky abstraction (for better or
249 // worse) and is preserved here the way binder sockets plugs itself
250 // into BpBinder, as nothing is changed at the higher levels
251 // (IInterface) which result in this behavior.
252 return sleepMs(ms);
253 }
254
Steven Moreland659416d2021-05-11 00:47:50 +0000255 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
256 const std::string& value) override {
257 if (callback == nullptr) {
258 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
259 }
260
261 if (delayed) {
262 std::thread([=]() {
263 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000264 Status status = doCallback(callback, oneway, false, value);
265 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000266 }).detach();
267 return Status::ok();
268 }
269
270 if (oneway) {
271 return callback->sendOnewayCallback(value);
272 }
273
274 return callback->sendCallback(value);
275 }
276
Steven Morelandc7d40132021-06-10 03:42:11 +0000277 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
278 const std::string& value) override {
279 return doCallback(callback, oneway, delayed, value);
280 }
281
Steven Moreland5553ac42020-11-11 02:14:45 +0000282 Status die(bool cleanup) override {
283 if (cleanup) {
284 exit(1);
285 } else {
286 _exit(1);
287 }
288 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000289
290 Status scheduleShutdown() override {
291 sp<RpcServer> strongServer = server.promote();
292 if (strongServer == nullptr) {
293 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
294 }
295 std::thread([=] {
296 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
297 }).detach();
298 return Status::ok();
299 }
300
Steven Morelandd7302072021-05-15 01:32:04 +0000301 Status useKernelBinderCallingId() override {
302 // this is WRONG! It does not make sense when using RPC binder, and
303 // because it is SO wrong, and so much code calls this, it should abort!
304
305 (void)IPCThreadState::self()->getCallingPid();
306 return Status::ok();
307 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000308};
309sp<IBinder> MyBinderRpcTest::mHeldBinder;
310
311class Process {
312public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700313 Process(Process&&) = default;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700314 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */)>& f) {
315 android::base::unique_fd writeEnd;
316 CHECK(android::base::Pipe(&mReadEnd, &writeEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000317 if (0 == (mPid = fork())) {
318 // racey: assume parent doesn't crash before this is set
319 prctl(PR_SET_PDEATHSIG, SIGHUP);
320
Yifan Hong0f58fb92021-06-16 16:09:23 -0700321 f(writeEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000322
323 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000324 }
325 }
326 ~Process() {
327 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000328 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000329 }
330 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700331 android::base::borrowed_fd readEnd() { return mReadEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000332
333private:
334 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700335 android::base::unique_fd mReadEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000336};
337
338static std::string allocateSocketAddress() {
339 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000340 std::string temp = getenv("TMPDIR") ?: "/tmp";
341 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000342};
343
Steven Morelandda573042021-06-12 01:13:45 +0000344static unsigned int allocateVsockPort() {
345 static unsigned int vsockPort = 3456;
346 return vsockPort++;
347}
348
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000349struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000350 // reference to process hosting a socket server
351 Process host;
352
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000353 struct SessionInfo {
354 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000355 sp<IBinder> root;
356 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000357
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000358 // client session objects associated with other process
359 // each one represents a separate session
360 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000361
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000362 ProcessSession(ProcessSession&&) = default;
363 ~ProcessSession() {
364 for (auto& session : sessions) {
365 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000366 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000367
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000368 for (auto& info : sessions) {
369 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000370
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000371 EXPECT_NE(nullptr, session);
372 EXPECT_NE(nullptr, session->state());
373 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000374
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000375 wp<RpcSession> weakSession = session;
376 session = nullptr;
377 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000378 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000379 }
380};
381
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000382// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000383// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000384struct BinderRpcTestProcessSession {
385 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000386
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000387 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000388 sp<IBinder> rootBinder;
389
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000390 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000391 sp<IBinderRpcTest> rootIface;
392
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000393 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000394 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000395
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000396 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
397 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000398 EXPECT_NE(nullptr, rootIface);
399 if (rootIface == nullptr) return;
400
Steven Morelandaf4ca712021-05-24 23:22:08 +0000401 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000402 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000403 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000404 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000405 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000406 for (auto remoteCount : remoteCounts) {
407 EXPECT_EQ(remoteCount, 1);
408 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000409
Steven Moreland798e0d12021-07-14 23:19:25 +0000410 // even though it is on another thread, shutdown races with
411 // the transaction reply being written
412 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
413 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
414 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000415 }
416
417 rootIface = nullptr;
418 rootBinder = nullptr;
419 }
420};
421
Steven Morelandc1635952021-04-01 16:20:47 +0000422enum class SocketType {
Steven Moreland4198a122021-08-03 17:37:58 -0700423 PRECONNECTED,
Steven Morelandc1635952021-04-01 16:20:47 +0000424 UNIX,
425 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700426 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000427};
Yifan Hong702115c2021-06-24 15:39:18 -0700428static inline std::string PrintToString(SocketType socketType) {
429 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700430 case SocketType::PRECONNECTED:
431 return "preconnected_uds";
Steven Morelandc1635952021-04-01 16:20:47 +0000432 case SocketType::UNIX:
433 return "unix_domain_socket";
434 case SocketType::VSOCK:
435 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700436 case SocketType::INET:
437 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000438 default:
439 LOG_ALWAYS_FATAL("Unknown socket type");
440 return "";
441 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000442}
Steven Morelandda573042021-06-12 01:13:45 +0000443
Steven Moreland4198a122021-08-03 17:37:58 -0700444static base::unique_fd connectToUds(const char* addrStr) {
445 UnixSocketAddress addr(addrStr);
446 base::unique_fd serverFd(
447 TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
448 int savedErrno = errno;
449 CHECK(serverFd.ok()) << "Could not create socket " << addrStr << ": " << strerror(savedErrno);
450
451 if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
452 int savedErrno = errno;
453 LOG(FATAL) << "Could not connect to socket " << addrStr << ": " << strerror(savedErrno);
454 }
455 return serverFd;
456}
457
Yifan Hong702115c2021-06-24 15:39:18 -0700458class BinderRpc : public ::testing::TestWithParam<std::tuple<SocketType, RpcSecurity>> {
Steven Morelandc1635952021-04-01 16:20:47 +0000459public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000460 struct Options {
461 size_t numThreads = 1;
462 size_t numSessions = 1;
463 size_t numIncomingConnections = 0;
464 };
465
Yifan Hong702115c2021-06-24 15:39:18 -0700466 static inline std::string PrintParamInfo(const testing::TestParamInfo<ParamType>& info) {
467 auto [type, security] = info.param;
468 return PrintToString(type) + "_" + newFactory(security)->toCString();
469 }
470
Steven Morelandc1635952021-04-01 16:20:47 +0000471 // This creates a new process serving an interface on a certain number of
472 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000473 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000474 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
475 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000476
Yifan Hong702115c2021-06-24 15:39:18 -0700477 SocketType socketType = std::get<0>(GetParam());
478 RpcSecurity rpcSecurity = std::get<1>(GetParam());
Steven Morelandc1635952021-04-01 16:20:47 +0000479
Steven Morelandda573042021-06-12 01:13:45 +0000480 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000481 std::string addr = allocateSocketAddress();
482 unlink(addr.c_str());
Steven Morelandc1635952021-04-01 16:20:47 +0000483
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000484 auto ret = ProcessSession{
Yifan Hong0f58fb92021-06-16 16:09:23 -0700485 .host = Process([&](android::base::borrowed_fd writeEnd) {
Yifan Hong702115c2021-06-24 15:39:18 -0700486 sp<RpcServer> server = RpcServer::make(newFactory(rpcSecurity));
Steven Morelandc1635952021-04-01 16:20:47 +0000487
488 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000489 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000490
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000491 unsigned int outPort = 0;
492
Steven Morelandc1635952021-04-01 16:20:47 +0000493 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700494 case SocketType::PRECONNECTED:
495 [[fallthrough]];
Steven Morelandc1635952021-04-01 16:20:47 +0000496 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700497 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000498 break;
499 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700500 CHECK_EQ(OK, server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000501 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700502 case SocketType::INET: {
Steven Moreland2372f9d2021-08-05 15:42:01 -0700503 CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700504 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700505 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700506 }
Steven Morelandc1635952021-04-01 16:20:47 +0000507 default:
508 LOG_ALWAYS_FATAL("Unknown socket type");
509 }
510
Yifan Hong0f58fb92021-06-16 16:09:23 -0700511 CHECK(android::base::WriteFully(writeEnd, &outPort, sizeof(outPort)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000512
Steven Moreland611d15f2021-05-01 01:28:27 +0000513 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000514
Steven Morelandf137de92021-04-24 01:54:26 +0000515 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000516
517 // Another thread calls shutdown. Wait for it to complete.
518 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000519 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000520 };
521
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000522 // always read socket, so that we have waited for the server to start
523 unsigned int outPort = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700524 CHECK(android::base::ReadFully(ret.host.readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700525 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000526 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700527 }
528
Steven Moreland2372f9d2021-08-05 15:42:01 -0700529 status_t status;
530
Steven Moreland4313d7e2021-07-15 23:41:22 +0000531 for (size_t i = 0; i < options.numSessions; i++) {
Yifan Hongecf937d2021-08-11 17:29:28 -0700532 sp<RpcSession> session =
533 RpcSession::make(newFactory(rpcSecurity), std::nullopt, std::nullopt);
Steven Moreland4313d7e2021-07-15 23:41:22 +0000534 session->setMaxThreads(options.numIncomingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000535
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000536 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700537 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700538 status = session->setupPreconnectedClient({}, [=]() {
539 return connectToUds(addr.c_str());
540 });
541 if (status == OK) goto success;
Steven Moreland4198a122021-08-03 17:37:58 -0700542 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000543 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700544 status = session->setupUnixDomainClient(addr.c_str());
545 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000546 break;
547 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700548 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
549 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000550 break;
551 case SocketType::INET:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700552 status = session->setupInetClient("127.0.0.1", outPort);
553 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000554 break;
555 default:
556 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000557 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700558 LOG_ALWAYS_FATAL("Could not connect %s", statusToString(status).c_str());
Steven Moreland736664b2021-05-01 04:27:25 +0000559 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000560 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000561 }
Steven Morelandc1635952021-04-01 16:20:47 +0000562 return ret;
563 }
564
Steven Moreland4313d7e2021-07-15 23:41:22 +0000565 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000566 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000567 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000568 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000569 sp<MyBinderRpcTest> service =
570 new MyBinderRpcTest;
571 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000572 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000573 }),
574 };
575
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000576 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000577 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
578
579 return ret;
580 }
581};
582
Steven Morelandc1635952021-04-01 16:20:47 +0000583TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000584 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000585 ASSERT_NE(proc.rootBinder, nullptr);
586 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
587}
588
Steven Moreland4cf688f2021-03-31 01:48:58 +0000589TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000590 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000591 ASSERT_NE(proc.rootBinder, nullptr);
592 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
593}
594
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000595TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000596 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000597 for (auto session : proc.proc.sessions) {
598 ASSERT_NE(nullptr, session.root);
599 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000600 }
601}
602
Steven Morelandc1635952021-04-01 16:20:47 +0000603TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000604 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000605 Parcel data;
606 Parcel reply;
607 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
608}
609
Steven Moreland67753c32021-04-02 18:45:19 +0000610TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000611 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000612
613 Parcel p1;
614 p1.markForBinder(proc.rootBinder);
615 p1.writeInt32(3);
616
617 Parcel p2;
618
619 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
620 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
621}
622
Steven Morelandc1635952021-04-01 16:20:47 +0000623TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000624 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000625 Parcel data;
626 data.markForBinder(proc.rootBinder);
627 Parcel reply;
628 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
629}
630
Steven Morelandc1635952021-04-01 16:20:47 +0000631TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000632 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000633 EXPECT_OK(proc.rootIface->sendString("asdf"));
634}
635
Steven Morelandc1635952021-04-01 16:20:47 +0000636TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000637 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000638 std::string doubled;
639 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
640 EXPECT_EQ("cool cool ", doubled);
641}
642
Steven Morelandc1635952021-04-01 16:20:47 +0000643TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000644 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000645 std::string single = std::string(1024, 'a');
646 std::string doubled;
647 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
648 EXPECT_EQ(single + single, doubled);
649}
650
Steven Morelandc1635952021-04-01 16:20:47 +0000651TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000652 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000653
654 int32_t pingResult;
655 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
656 EXPECT_EQ(OK, pingResult);
657
658 EXPECT_EQ(0, MyBinderRpcSession::gNum);
659}
660
Steven Morelandc1635952021-04-01 16:20:47 +0000661TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000662 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000663
664 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
665 sp<IBinder> outBinder;
666 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
667 EXPECT_EQ(inBinder, outBinder);
668
669 wp<IBinder> weak = inBinder;
670 inBinder = nullptr;
671 outBinder = nullptr;
672
673 // Force reading a reply, to process any pending dec refs from the other
674 // process (the other process will process dec refs there before processing
675 // the ping here).
676 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
677
678 EXPECT_EQ(nullptr, weak.promote());
679
680 EXPECT_EQ(0, MyBinderRpcSession::gNum);
681}
682
Steven Morelandc1635952021-04-01 16:20:47 +0000683TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000684 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000685
686 sp<IBinderRpcSession> session;
687 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
688
689 sp<IBinder> inBinder = IInterface::asBinder(session);
690 sp<IBinder> outBinder;
691 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
692 EXPECT_EQ(inBinder, outBinder);
693
694 wp<IBinder> weak = inBinder;
695 session = nullptr;
696 inBinder = nullptr;
697 outBinder = nullptr;
698
699 // Force reading a reply, to process any pending dec refs from the other
700 // process (the other process will process dec refs there before processing
701 // the ping here).
702 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
703
704 EXPECT_EQ(nullptr, weak.promote());
705}
706
Steven Morelandc1635952021-04-01 16:20:47 +0000707TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000708 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000709
710 sp<IBinder> outBinder;
711 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
712 EXPECT_EQ(nullptr, outBinder);
713}
714
Steven Morelandc1635952021-04-01 16:20:47 +0000715TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000716 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000717
718 IBinder* ptr = nullptr;
719 {
720 sp<IBinder> binder = new BBinder();
721 ptr = binder.get();
722 EXPECT_OK(proc.rootIface->holdBinder(binder));
723 }
724
725 sp<IBinder> held;
726 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
727
728 EXPECT_EQ(held.get(), ptr);
729
730 // stop holding binder, because we test to make sure references are cleaned
731 // up
732 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
733 // and flush ref counts
734 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
735}
736
737// START TESTS FOR LIMITATIONS OF SOCKET BINDER
738// These are behavioral differences form regular binder, where certain usecases
739// aren't supported.
740
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000741TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000742 auto proc1 = createRpcTestSocketServerProcess({});
743 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000744
745 sp<IBinder> outBinder;
746 EXPECT_EQ(INVALID_OPERATION,
747 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
748}
749
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000750TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000751 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000752
753 sp<IBinder> outBinder;
754 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000755 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000756 .transactionError());
757}
758
Steven Morelandc1635952021-04-01 16:20:47 +0000759TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000760 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000761
762 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
763 sp<IBinder> outBinder;
764 EXPECT_EQ(INVALID_OPERATION,
765 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
766}
767
Steven Morelandc1635952021-04-01 16:20:47 +0000768TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000769 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000770
771 // for historical reasons, IServiceManager interface only returns the
772 // exception code
773 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
774 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
775}
776
777// END TESTS FOR LIMITATIONS OF SOCKET BINDER
778
Steven Morelandc1635952021-04-01 16:20:47 +0000779TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000780 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000781
782 sp<IBinder> outBinder;
783 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
784 EXPECT_EQ(proc.rootBinder, outBinder);
785}
786
Steven Morelandc1635952021-04-01 16:20:47 +0000787TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000788 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000789
790 auto nastyNester = sp<MyBinderRpcTest>::make();
791 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
792
793 wp<IBinder> weak = nastyNester;
794 nastyNester = nullptr;
795 EXPECT_EQ(nullptr, weak.promote());
796}
797
Steven Morelandc1635952021-04-01 16:20:47 +0000798TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000799 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000800
801 sp<IBinder> a;
802 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
803
804 sp<IBinder> b;
805 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
806
807 EXPECT_EQ(a, b);
808}
809
Steven Morelandc1635952021-04-01 16:20:47 +0000810TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000811 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000812
813 sp<IBinder> a;
814 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
815 wp<IBinder> weak = a;
816 a = nullptr;
817
818 sp<IBinder> b;
819 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
820
821 // this is the wrong behavior, since BpBinder
822 // doesn't implement onIncStrongAttempted
823 // but make sure there is no crash
824 EXPECT_EQ(nullptr, weak.promote());
825
826 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
827
828 // In order to fix this:
829 // - need to have incStrongAttempted reflected across IPC boundary (wait for
830 // response to promote - round trip...)
831 // - sendOnLastWeakRef, to delete entries out of RpcState table
832 EXPECT_EQ(b, weak.promote());
833}
834
835#define expectSessions(expected, iface) \
836 do { \
837 int session; \
838 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
839 EXPECT_EQ(expected, session); \
840 } while (false)
841
Steven Morelandc1635952021-04-01 16:20:47 +0000842TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000843 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000844
845 sp<IBinderRpcSession> session;
846 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
847 std::string out;
848 EXPECT_OK(session->getName(&out));
849 EXPECT_EQ("aoeu", out);
850
851 expectSessions(1, proc.rootIface);
852 session = nullptr;
853 expectSessions(0, proc.rootIface);
854}
855
Steven Morelandc1635952021-04-01 16:20:47 +0000856TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000857 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000858
859 std::vector<sp<IBinderRpcSession>> sessions;
860
861 for (size_t i = 0; i < 15; i++) {
862 expectSessions(i, proc.rootIface);
863 sp<IBinderRpcSession> session;
864 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
865 sessions.push_back(session);
866 }
867 expectSessions(sessions.size(), proc.rootIface);
868 for (size_t i = 0; i < sessions.size(); i++) {
869 std::string out;
870 EXPECT_OK(sessions.at(i)->getName(&out));
871 EXPECT_EQ(std::to_string(i), out);
872 }
873 expectSessions(sessions.size(), proc.rootIface);
874
875 while (!sessions.empty()) {
876 sessions.pop_back();
877 expectSessions(sessions.size(), proc.rootIface);
878 }
879 expectSessions(0, proc.rootIface);
880}
881
882size_t epochMillis() {
883 using std::chrono::duration_cast;
884 using std::chrono::milliseconds;
885 using std::chrono::seconds;
886 using std::chrono::system_clock;
887 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
888}
889
Steven Morelandc1635952021-04-01 16:20:47 +0000890TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000891 constexpr size_t kNumThreads = 10;
892
Steven Moreland4313d7e2021-07-15 23:41:22 +0000893 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000894
895 EXPECT_OK(proc.rootIface->lock());
896
897 // block all but one thread taking locks
898 std::vector<std::thread> ts;
899 for (size_t i = 0; i < kNumThreads - 1; i++) {
900 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
901 }
902
903 usleep(100000); // give chance for calls on other threads
904
905 // other calls still work
906 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
907
908 constexpr size_t blockTimeMs = 500;
909 size_t epochMsBefore = epochMillis();
910 // after this, we should never see a response within this time
911 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
912
913 // this call should be blocked for blockTimeMs
914 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
915
916 size_t epochMsAfter = epochMillis();
917 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
918
919 for (auto& t : ts) t.join();
920}
921
Steven Morelandc1635952021-04-01 16:20:47 +0000922TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000923 constexpr size_t kNumThreads = 10;
924 constexpr size_t kNumCalls = kNumThreads + 3;
925 constexpr size_t kSleepMs = 500;
926
Steven Moreland4313d7e2021-07-15 23:41:22 +0000927 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000928
929 size_t epochMsBefore = epochMillis();
930
931 std::vector<std::thread> ts;
932 for (size_t i = 0; i < kNumCalls; i++) {
933 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
934 }
935
936 for (auto& t : ts) t.join();
937
938 size_t epochMsAfter = epochMillis();
939
940 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
941
942 // Potential flake, but make sure calls are handled in parallel.
943 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
944}
945
Steven Morelandc1635952021-04-01 16:20:47 +0000946TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000947 constexpr size_t kNumClientThreads = 10;
948 constexpr size_t kNumServerThreads = 10;
949 constexpr size_t kNumCalls = 100;
950
Steven Moreland4313d7e2021-07-15 23:41:22 +0000951 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000952
953 std::vector<std::thread> threads;
954 for (size_t i = 0; i < kNumClientThreads; i++) {
955 threads.push_back(std::thread([&] {
956 for (size_t j = 0; j < kNumCalls; j++) {
957 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000958 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000959 EXPECT_EQ(proc.rootBinder, out);
960 }
961 }));
962 }
963
964 for (auto& t : threads) t.join();
965}
966
Steven Morelandc6046982021-04-20 00:49:42 +0000967TEST_P(BinderRpc, OnewayStressTest) {
968 constexpr size_t kNumClientThreads = 10;
969 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000970 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000971
Steven Moreland4313d7e2021-07-15 23:41:22 +0000972 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000973
974 std::vector<std::thread> threads;
975 for (size_t i = 0; i < kNumClientThreads; i++) {
976 threads.push_back(std::thread([&] {
977 for (size_t j = 0; j < kNumCalls; j++) {
978 EXPECT_OK(proc.rootIface->sendString("a"));
979 }
980
981 // check threads are not stuck
982 EXPECT_OK(proc.rootIface->sleepMs(250));
983 }));
984 }
985
986 for (auto& t : threads) t.join();
987}
988
Steven Morelandc1635952021-04-01 16:20:47 +0000989TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000990 constexpr size_t kReallyLongTimeMs = 100;
991 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
992
Steven Moreland4313d7e2021-07-15 23:41:22 +0000993 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000994
995 size_t epochMsBefore = epochMillis();
996
997 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
998
999 size_t epochMsAfter = epochMillis();
1000 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1001}
1002
Steven Morelandc1635952021-04-01 16:20:47 +00001003TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001004 constexpr size_t kNumSleeps = 10;
1005 constexpr size_t kNumExtraServerThreads = 4;
1006 constexpr size_t kSleepMs = 50;
1007
1008 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001009 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001010
1011 EXPECT_OK(proc.rootIface->lock());
1012
1013 for (size_t i = 0; i < kNumSleeps; i++) {
1014 // these should be processed serially
1015 proc.rootIface->sleepMsAsync(kSleepMs);
1016 }
1017 // should also be processesed serially
1018 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1019
1020 size_t epochMsBefore = epochMillis();
1021 EXPECT_OK(proc.rootIface->lockUnlock());
1022 size_t epochMsAfter = epochMillis();
1023
1024 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001025
1026 // pending oneway transactions hold ref, make sure we read data on all
1027 // sockets
1028 std::vector<std::thread> threads;
1029 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
1030 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
1031 }
1032 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +00001033}
1034
Steven Morelandd45be622021-06-04 02:19:37 +00001035TEST_P(BinderRpc, OnewayCallExhaustion) {
1036 constexpr size_t kNumClients = 2;
1037 constexpr size_t kTooLongMs = 1000;
1038
Steven Moreland4313d7e2021-07-15 23:41:22 +00001039 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001040
1041 // Build up oneway calls on the second session to make sure it terminates
1042 // and shuts down. The first session should be unaffected (proc destructor
1043 // checks the first session).
1044 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1045
1046 std::vector<std::thread> threads;
1047 for (size_t i = 0; i < kNumClients; i++) {
1048 // one of these threads will get stuck queueing a transaction once the
1049 // socket fills up, the other will be able to fill up transactions on
1050 // this object
1051 threads.push_back(std::thread([&] {
1052 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1053 }
1054 }));
1055 }
1056 for (auto& t : threads) t.join();
1057
1058 Status status = iface->sleepMsAsync(kTooLongMs);
1059 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1060
Steven Moreland798e0d12021-07-14 23:19:25 +00001061 // now that it has died, wait for the remote session to shutdown
1062 std::vector<int32_t> remoteCounts;
1063 do {
1064 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1065 } while (remoteCounts.size() == kNumClients);
1066
Steven Morelandd45be622021-06-04 02:19:37 +00001067 // the second session should be shutdown in the other process by the time we
1068 // are able to join above (it'll only be hung up once it finishes processing
1069 // any pending commands). We need to erase this session from the record
1070 // here, so that the destructor for our session won't check that this
1071 // session is valid, but we still want it to test the other session.
1072 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1073}
1074
Steven Moreland659416d2021-05-11 00:47:50 +00001075TEST_P(BinderRpc, Callbacks) {
1076 const static std::string kTestString = "good afternoon!";
1077
Steven Morelandc7d40132021-06-10 03:42:11 +00001078 for (bool callIsOneway : {true, false}) {
1079 for (bool callbackIsOneway : {true, false}) {
1080 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001081 auto proc = createRpcTestSocketServerProcess(
1082 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001083 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001084
Steven Morelandc7d40132021-06-10 03:42:11 +00001085 if (callIsOneway) {
1086 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1087 kTestString));
1088 } else {
1089 EXPECT_OK(
1090 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1091 }
Steven Moreland659416d2021-05-11 00:47:50 +00001092
Steven Morelandc7d40132021-06-10 03:42:11 +00001093 using std::literals::chrono_literals::operator""s;
1094 std::unique_lock<std::mutex> _l(cb->mMutex);
1095 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001096
Steven Morelandc7d40132021-06-10 03:42:11 +00001097 EXPECT_EQ(cb->mValues.size(), 1)
1098 << "callIsOneway: " << callIsOneway
1099 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1100 if (cb->mValues.empty()) continue;
1101 EXPECT_EQ(cb->mValues.at(0), kTestString)
1102 << "callIsOneway: " << callIsOneway
1103 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001104
Steven Morelandc7d40132021-06-10 03:42:11 +00001105 // since we are severing the connection, we need to go ahead and
1106 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001107 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1108 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1109 }
Steven Moreland659416d2021-05-11 00:47:50 +00001110
Steven Moreland1b304292021-07-15 22:59:34 +00001111 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001112 // need to manually shut it down
1113 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001114
Steven Morelandc7d40132021-06-10 03:42:11 +00001115 proc.expectAlreadyShutdown = true;
1116 }
Steven Moreland659416d2021-05-11 00:47:50 +00001117 }
1118 }
1119}
1120
Steven Moreland195edb82021-06-08 02:44:39 +00001121TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001122 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001123 auto cb = sp<MyBinderRpcCallback>::make();
1124
1125 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1126 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1127}
1128
Steven Morelandc1635952021-04-01 16:20:47 +00001129TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001130 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001131 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001132
1133 // make sure there is some state during crash
1134 // 1. we hold their binder
1135 sp<IBinderRpcSession> session;
1136 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1137 // 2. they hold our binder
1138 sp<IBinder> binder = new BBinder();
1139 EXPECT_OK(proc.rootIface->holdBinder(binder));
1140
1141 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1142 << "Do death cleanup: " << doDeathCleanup;
1143
Steven Morelandaf4ca712021-05-24 23:22:08 +00001144 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001145 }
1146}
1147
Steven Morelandd7302072021-05-15 01:32:04 +00001148TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001149 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001150
1151 // we can't allocate IPCThreadState so actually the first time should
1152 // succeed :(
1153 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1154
1155 // second time! we catch the error :)
1156 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1157
Steven Morelandaf4ca712021-05-24 23:22:08 +00001158 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001159}
1160
Steven Moreland37aff182021-03-26 02:04:16 +00001161TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001162 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001163
1164 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1165 ASSERT_NE(binder, nullptr);
1166
1167 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1168}
1169
1170TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001171 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001172
1173 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1174 ASSERT_NE(binder, nullptr);
1175
1176 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1177 ASSERT_NE(ndkBinder, nullptr);
1178
1179 std::string out;
1180 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1181 ASSERT_TRUE(status.isOk()) << status.getDescription();
1182 ASSERT_EQ("aoeuaoeu", out);
1183}
1184
Steven Moreland5553ac42020-11-11 02:14:45 +00001185ssize_t countFds() {
1186 DIR* dir = opendir("/proc/self/fd/");
1187 if (dir == nullptr) return -1;
1188 ssize_t ret = 0;
1189 dirent* ent;
1190 while ((ent = readdir(dir)) != nullptr) ret++;
1191 closedir(dir);
1192 return ret;
1193}
1194
Steven Morelandc1635952021-04-01 16:20:47 +00001195TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001196 ssize_t beforeFds = countFds();
1197 ASSERT_GE(beforeFds, 0);
1198 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001199 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001200 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1201 }
1202 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1203}
1204
Steven Morelandda573042021-06-12 01:13:45 +00001205static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001206 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001207 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001208 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001209 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland1eab3452021-08-05 16:56:20 -07001210 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1211 if (status == -EAFNOSUPPORT) {
1212 return false;
1213 }
1214 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1215 }
Steven Morelandda573042021-06-12 01:13:45 +00001216 server->start();
1217
Yifan Hongecf937d2021-08-11 17:29:28 -07001218 sp<RpcSession> session =
1219 RpcSession::make(RpcTransportCtxFactoryRaw::make(), std::nullopt, std::nullopt);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001220 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001221 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001222 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1223 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001224}
1225
1226static std::vector<SocketType> testSocketTypes() {
Steven Moreland4198a122021-08-03 17:37:58 -07001227 std::vector<SocketType> ret = {SocketType::PRECONNECTED, SocketType::UNIX, SocketType::INET};
Steven Morelandda573042021-06-12 01:13:45 +00001228
1229 static bool hasVsockLoopback = testSupportVsockLoopback();
1230
1231 if (hasVsockLoopback) {
1232 ret.push_back(SocketType::VSOCK);
1233 }
1234
1235 return ret;
1236}
1237
Yifan Hong702115c2021-06-24 15:39:18 -07001238INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1239 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1240 ::testing::ValuesIn(RpcSecurityValues())),
1241 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001242
Yifan Hong702115c2021-06-24 15:39:18 -07001243class BinderRpcServerRootObject
1244 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001245
1246TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1247 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1248 auto setRootObject = [](bool isStrong) -> SetFn {
1249 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1250 };
1251
Yifan Hong702115c2021-06-24 15:39:18 -07001252 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1253 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001254 auto binder1 = sp<BBinder>::make();
1255 IBinder* binderRaw1 = binder1.get();
1256 setRootObject(isStrong1)(server.get(), binder1);
1257 EXPECT_EQ(binderRaw1, server->getRootObject());
1258 binder1.clear();
1259 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1260
1261 auto binder2 = sp<BBinder>::make();
1262 IBinder* binderRaw2 = binder2.get();
1263 setRootObject(isStrong2)(server.get(), binder2);
1264 EXPECT_EQ(binderRaw2, server->getRootObject());
1265 binder2.clear();
1266 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1267}
1268
1269INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001270 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1271 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001272
Yifan Hong1a235852021-05-13 16:07:47 -07001273class OneOffSignal {
1274public:
1275 // If notify() was previously called, or is called within |duration|, return true; else false.
1276 template <typename R, typename P>
1277 bool wait(std::chrono::duration<R, P> duration) {
1278 std::unique_lock<std::mutex> lock(mMutex);
1279 return mCv.wait_for(lock, duration, [this] { return mValue; });
1280 }
1281 void notify() {
1282 std::unique_lock<std::mutex> lock(mMutex);
1283 mValue = true;
1284 lock.unlock();
1285 mCv.notify_all();
1286 }
1287
1288private:
1289 std::mutex mMutex;
1290 std::condition_variable mCv;
1291 bool mValue = false;
1292};
1293
Yifan Hong702115c2021-06-24 15:39:18 -07001294TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001295 auto addr = allocateSocketAddress();
1296 unlink(addr.c_str());
Yifan Hong702115c2021-06-24 15:39:18 -07001297 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong1a235852021-05-13 16:07:47 -07001298 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001299 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001300 auto joinEnds = std::make_shared<OneOffSignal>();
1301
1302 // If things are broken and the thread never stops, don't block other tests. Because the thread
1303 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1304 // shared pointers are passed.
1305 std::thread([server, joinEnds] {
1306 server->join();
1307 joinEnds->notify();
1308 }).detach();
1309
1310 bool shutdown = false;
1311 for (int i = 0; i < 10 && !shutdown; i++) {
1312 usleep(300 * 1000); // 300ms; total 3s
1313 if (server->shutdown()) shutdown = true;
1314 }
1315 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1316
1317 ASSERT_TRUE(joinEnds->wait(2s))
1318 << "After server->shutdown() returns true, join() did not stop after 2s";
1319}
1320
Yifan Hong194acf22021-06-29 18:44:56 -07001321TEST(BinderRpc, Java) {
1322#if !defined(__ANDROID__)
1323 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1324 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1325 "to binderHostDeviceTest. Hence, just disable this test on host.";
1326#endif // !__ANDROID__
1327 sp<IServiceManager> sm = defaultServiceManager();
1328 ASSERT_NE(nullptr, sm);
1329 // Any Java service with non-empty getInterfaceDescriptor() would do.
1330 // Let's pick batteryproperties.
1331 auto binder = sm->checkService(String16("batteryproperties"));
1332 ASSERT_NE(nullptr, binder);
1333 auto descriptor = binder->getInterfaceDescriptor();
1334 ASSERT_GE(descriptor.size(), 0);
1335 ASSERT_EQ(OK, binder->pingBinder());
1336
1337 auto rpcServer = RpcServer::make();
1338 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1339 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001340 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001341 auto socket = rpcServer->releaseServer();
1342
1343 auto keepAlive = sp<BBinder>::make();
1344 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1345
1346 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001347 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001348 auto rpcBinder = rpcSession->getRootObject();
1349 ASSERT_NE(nullptr, rpcBinder);
1350
1351 ASSERT_EQ(OK, rpcBinder->pingBinder());
1352
1353 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1354 << "getInterfaceDescriptor should not crash system_server";
1355 ASSERT_EQ(OK, rpcBinder->pingBinder());
1356}
1357
Yifan Hong702115c2021-06-24 15:39:18 -07001358INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1359 BinderRpcSimple::PrintTestParam);
1360
Steven Morelandc1635952021-04-01 16:20:47 +00001361} // namespace android
1362
1363int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001364 ::testing::InitGoogleTest(&argc, argv);
1365 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1366 return RUN_ALL_TESTS();
1367}