blob: dbf8899904eea0df9eb874811e8d44596af1639c [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 Hongfdd9f692021-09-09 15:12:52 -0700532 sp<RpcSession> session = RpcSession::make(newFactory(rpcSecurity));
Steven Moreland4313d7e2021-07-15 23:41:22 +0000533 session->setMaxThreads(options.numIncomingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000534
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000535 switch (socketType) {
Steven Moreland4198a122021-08-03 17:37:58 -0700536 case SocketType::PRECONNECTED:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700537 status = session->setupPreconnectedClient({}, [=]() {
538 return connectToUds(addr.c_str());
539 });
540 if (status == OK) goto success;
Steven Moreland4198a122021-08-03 17:37:58 -0700541 break;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000542 case SocketType::UNIX:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700543 status = session->setupUnixDomainClient(addr.c_str());
544 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000545 break;
546 case SocketType::VSOCK:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700547 status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
548 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000549 break;
550 case SocketType::INET:
Steven Moreland2372f9d2021-08-05 15:42:01 -0700551 status = session->setupInetClient("127.0.0.1", outPort);
552 if (status == OK) goto success;
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000553 break;
554 default:
555 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000556 }
Steven Moreland2372f9d2021-08-05 15:42:01 -0700557 LOG_ALWAYS_FATAL("Could not connect %s", statusToString(status).c_str());
Steven Moreland736664b2021-05-01 04:27:25 +0000558 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000559 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000560 }
Steven Morelandc1635952021-04-01 16:20:47 +0000561 return ret;
562 }
563
Steven Moreland4313d7e2021-07-15 23:41:22 +0000564 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000565 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000566 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000567 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000568 sp<MyBinderRpcTest> service =
569 new MyBinderRpcTest;
570 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000571 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000572 }),
573 };
574
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000575 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000576 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
577
578 return ret;
579 }
580};
581
Steven Morelandc1635952021-04-01 16:20:47 +0000582TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000583 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000584 ASSERT_NE(proc.rootBinder, nullptr);
585 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
586}
587
Steven Moreland4cf688f2021-03-31 01:48:58 +0000588TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000589 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000590 ASSERT_NE(proc.rootBinder, nullptr);
591 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
592}
593
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000594TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000595 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000596 for (auto session : proc.proc.sessions) {
597 ASSERT_NE(nullptr, session.root);
598 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000599 }
600}
601
Steven Morelandc1635952021-04-01 16:20:47 +0000602TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000603 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000604 Parcel data;
605 Parcel reply;
606 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
607}
608
Steven Moreland67753c32021-04-02 18:45:19 +0000609TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000610 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000611
612 Parcel p1;
613 p1.markForBinder(proc.rootBinder);
614 p1.writeInt32(3);
615
616 Parcel p2;
617
618 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
619 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
620}
621
Steven Morelandc1635952021-04-01 16:20:47 +0000622TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000623 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000624 Parcel data;
625 data.markForBinder(proc.rootBinder);
626 Parcel reply;
627 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
628}
629
Steven Morelandc1635952021-04-01 16:20:47 +0000630TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000631 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000632 EXPECT_OK(proc.rootIface->sendString("asdf"));
633}
634
Steven Morelandc1635952021-04-01 16:20:47 +0000635TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000636 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000637 std::string doubled;
638 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
639 EXPECT_EQ("cool cool ", doubled);
640}
641
Steven Morelandc1635952021-04-01 16:20:47 +0000642TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000643 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000644 std::string single = std::string(1024, 'a');
645 std::string doubled;
646 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
647 EXPECT_EQ(single + single, doubled);
648}
649
Steven Morelandc1635952021-04-01 16:20:47 +0000650TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000651 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000652
653 int32_t pingResult;
654 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
655 EXPECT_EQ(OK, pingResult);
656
657 EXPECT_EQ(0, MyBinderRpcSession::gNum);
658}
659
Steven Morelandc1635952021-04-01 16:20:47 +0000660TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000661 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000662
663 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
664 sp<IBinder> outBinder;
665 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
666 EXPECT_EQ(inBinder, outBinder);
667
668 wp<IBinder> weak = inBinder;
669 inBinder = nullptr;
670 outBinder = nullptr;
671
672 // Force reading a reply, to process any pending dec refs from the other
673 // process (the other process will process dec refs there before processing
674 // the ping here).
675 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
676
677 EXPECT_EQ(nullptr, weak.promote());
678
679 EXPECT_EQ(0, MyBinderRpcSession::gNum);
680}
681
Steven Morelandc1635952021-04-01 16:20:47 +0000682TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000683 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000684
685 sp<IBinderRpcSession> session;
686 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
687
688 sp<IBinder> inBinder = IInterface::asBinder(session);
689 sp<IBinder> outBinder;
690 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
691 EXPECT_EQ(inBinder, outBinder);
692
693 wp<IBinder> weak = inBinder;
694 session = nullptr;
695 inBinder = nullptr;
696 outBinder = nullptr;
697
698 // Force reading a reply, to process any pending dec refs from the other
699 // process (the other process will process dec refs there before processing
700 // the ping here).
701 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
702
703 EXPECT_EQ(nullptr, weak.promote());
704}
705
Steven Morelandc1635952021-04-01 16:20:47 +0000706TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000707 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000708
709 sp<IBinder> outBinder;
710 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
711 EXPECT_EQ(nullptr, outBinder);
712}
713
Steven Morelandc1635952021-04-01 16:20:47 +0000714TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000715 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000716
717 IBinder* ptr = nullptr;
718 {
719 sp<IBinder> binder = new BBinder();
720 ptr = binder.get();
721 EXPECT_OK(proc.rootIface->holdBinder(binder));
722 }
723
724 sp<IBinder> held;
725 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
726
727 EXPECT_EQ(held.get(), ptr);
728
729 // stop holding binder, because we test to make sure references are cleaned
730 // up
731 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
732 // and flush ref counts
733 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
734}
735
736// START TESTS FOR LIMITATIONS OF SOCKET BINDER
737// These are behavioral differences form regular binder, where certain usecases
738// aren't supported.
739
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000740TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000741 auto proc1 = createRpcTestSocketServerProcess({});
742 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000743
744 sp<IBinder> outBinder;
745 EXPECT_EQ(INVALID_OPERATION,
746 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
747}
748
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000749TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000750 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000751
752 sp<IBinder> outBinder;
753 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000754 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000755 .transactionError());
756}
757
Steven Morelandc1635952021-04-01 16:20:47 +0000758TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000759 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000760
761 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
762 sp<IBinder> outBinder;
763 EXPECT_EQ(INVALID_OPERATION,
764 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
765}
766
Steven Morelandc1635952021-04-01 16:20:47 +0000767TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000768 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000769
770 // for historical reasons, IServiceManager interface only returns the
771 // exception code
772 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
773 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
774}
775
776// END TESTS FOR LIMITATIONS OF SOCKET BINDER
777
Steven Morelandc1635952021-04-01 16:20:47 +0000778TEST_P(BinderRpc, RepeatRootObject) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000779 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000780
781 sp<IBinder> outBinder;
782 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
783 EXPECT_EQ(proc.rootBinder, outBinder);
784}
785
Steven Morelandc1635952021-04-01 16:20:47 +0000786TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000787 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000788
789 auto nastyNester = sp<MyBinderRpcTest>::make();
790 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
791
792 wp<IBinder> weak = nastyNester;
793 nastyNester = nullptr;
794 EXPECT_EQ(nullptr, weak.promote());
795}
796
Steven Morelandc1635952021-04-01 16:20:47 +0000797TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000798 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000799
800 sp<IBinder> a;
801 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
802
803 sp<IBinder> b;
804 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
805
806 EXPECT_EQ(a, b);
807}
808
Steven Morelandc1635952021-04-01 16:20:47 +0000809TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000810 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000811
812 sp<IBinder> a;
813 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
814 wp<IBinder> weak = a;
815 a = nullptr;
816
817 sp<IBinder> b;
818 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
819
820 // this is the wrong behavior, since BpBinder
821 // doesn't implement onIncStrongAttempted
822 // but make sure there is no crash
823 EXPECT_EQ(nullptr, weak.promote());
824
825 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
826
827 // In order to fix this:
828 // - need to have incStrongAttempted reflected across IPC boundary (wait for
829 // response to promote - round trip...)
830 // - sendOnLastWeakRef, to delete entries out of RpcState table
831 EXPECT_EQ(b, weak.promote());
832}
833
834#define expectSessions(expected, iface) \
835 do { \
836 int session; \
837 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
838 EXPECT_EQ(expected, session); \
839 } while (false)
840
Steven Morelandc1635952021-04-01 16:20:47 +0000841TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000842 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000843
844 sp<IBinderRpcSession> session;
845 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
846 std::string out;
847 EXPECT_OK(session->getName(&out));
848 EXPECT_EQ("aoeu", out);
849
850 expectSessions(1, proc.rootIface);
851 session = nullptr;
852 expectSessions(0, proc.rootIface);
853}
854
Steven Morelandc1635952021-04-01 16:20:47 +0000855TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000856 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000857
858 std::vector<sp<IBinderRpcSession>> sessions;
859
860 for (size_t i = 0; i < 15; i++) {
861 expectSessions(i, proc.rootIface);
862 sp<IBinderRpcSession> session;
863 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
864 sessions.push_back(session);
865 }
866 expectSessions(sessions.size(), proc.rootIface);
867 for (size_t i = 0; i < sessions.size(); i++) {
868 std::string out;
869 EXPECT_OK(sessions.at(i)->getName(&out));
870 EXPECT_EQ(std::to_string(i), out);
871 }
872 expectSessions(sessions.size(), proc.rootIface);
873
874 while (!sessions.empty()) {
875 sessions.pop_back();
876 expectSessions(sessions.size(), proc.rootIface);
877 }
878 expectSessions(0, proc.rootIface);
879}
880
881size_t epochMillis() {
882 using std::chrono::duration_cast;
883 using std::chrono::milliseconds;
884 using std::chrono::seconds;
885 using std::chrono::system_clock;
886 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
887}
888
Steven Morelandc1635952021-04-01 16:20:47 +0000889TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000890 constexpr size_t kNumThreads = 10;
891
Steven Moreland4313d7e2021-07-15 23:41:22 +0000892 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000893
894 EXPECT_OK(proc.rootIface->lock());
895
896 // block all but one thread taking locks
897 std::vector<std::thread> ts;
898 for (size_t i = 0; i < kNumThreads - 1; i++) {
899 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
900 }
901
902 usleep(100000); // give chance for calls on other threads
903
904 // other calls still work
905 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
906
907 constexpr size_t blockTimeMs = 500;
908 size_t epochMsBefore = epochMillis();
909 // after this, we should never see a response within this time
910 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
911
912 // this call should be blocked for blockTimeMs
913 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
914
915 size_t epochMsAfter = epochMillis();
916 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
917
918 for (auto& t : ts) t.join();
919}
920
Steven Morelandc1635952021-04-01 16:20:47 +0000921TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000922 constexpr size_t kNumThreads = 10;
923 constexpr size_t kNumCalls = kNumThreads + 3;
924 constexpr size_t kSleepMs = 500;
925
Steven Moreland4313d7e2021-07-15 23:41:22 +0000926 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000927
928 size_t epochMsBefore = epochMillis();
929
930 std::vector<std::thread> ts;
931 for (size_t i = 0; i < kNumCalls; i++) {
932 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
933 }
934
935 for (auto& t : ts) t.join();
936
937 size_t epochMsAfter = epochMillis();
938
939 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
940
941 // Potential flake, but make sure calls are handled in parallel.
942 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
943}
944
Steven Morelandc1635952021-04-01 16:20:47 +0000945TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000946 constexpr size_t kNumClientThreads = 10;
947 constexpr size_t kNumServerThreads = 10;
948 constexpr size_t kNumCalls = 100;
949
Steven Moreland4313d7e2021-07-15 23:41:22 +0000950 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000951
952 std::vector<std::thread> threads;
953 for (size_t i = 0; i < kNumClientThreads; i++) {
954 threads.push_back(std::thread([&] {
955 for (size_t j = 0; j < kNumCalls; j++) {
956 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000957 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000958 EXPECT_EQ(proc.rootBinder, out);
959 }
960 }));
961 }
962
963 for (auto& t : threads) t.join();
964}
965
Steven Morelandc6046982021-04-20 00:49:42 +0000966TEST_P(BinderRpc, OnewayStressTest) {
967 constexpr size_t kNumClientThreads = 10;
968 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000969 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000970
Steven Moreland4313d7e2021-07-15 23:41:22 +0000971 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000972
973 std::vector<std::thread> threads;
974 for (size_t i = 0; i < kNumClientThreads; i++) {
975 threads.push_back(std::thread([&] {
976 for (size_t j = 0; j < kNumCalls; j++) {
977 EXPECT_OK(proc.rootIface->sendString("a"));
978 }
979
980 // check threads are not stuck
981 EXPECT_OK(proc.rootIface->sleepMs(250));
982 }));
983 }
984
985 for (auto& t : threads) t.join();
986}
987
Steven Morelandc1635952021-04-01 16:20:47 +0000988TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000989 constexpr size_t kReallyLongTimeMs = 100;
990 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
991
Steven Moreland4313d7e2021-07-15 23:41:22 +0000992 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000993
994 size_t epochMsBefore = epochMillis();
995
996 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
997
998 size_t epochMsAfter = epochMillis();
999 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
1000}
1001
Steven Morelandc1635952021-04-01 16:20:47 +00001002TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001003 constexpr size_t kNumSleeps = 10;
1004 constexpr size_t kNumExtraServerThreads = 4;
1005 constexpr size_t kSleepMs = 50;
1006
1007 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +00001008 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +00001009
1010 EXPECT_OK(proc.rootIface->lock());
1011
1012 for (size_t i = 0; i < kNumSleeps; i++) {
1013 // these should be processed serially
1014 proc.rootIface->sleepMsAsync(kSleepMs);
1015 }
1016 // should also be processesed serially
1017 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
1018
1019 size_t epochMsBefore = epochMillis();
1020 EXPECT_OK(proc.rootIface->lockUnlock());
1021 size_t epochMsAfter = epochMillis();
1022
1023 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +00001024
1025 // pending oneway transactions hold ref, make sure we read data on all
1026 // sockets
1027 std::vector<std::thread> threads;
1028 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
1029 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
1030 }
1031 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +00001032}
1033
Steven Morelandd45be622021-06-04 02:19:37 +00001034TEST_P(BinderRpc, OnewayCallExhaustion) {
1035 constexpr size_t kNumClients = 2;
1036 constexpr size_t kTooLongMs = 1000;
1037
Steven Moreland4313d7e2021-07-15 23:41:22 +00001038 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +00001039
1040 // Build up oneway calls on the second session to make sure it terminates
1041 // and shuts down. The first session should be unaffected (proc destructor
1042 // checks the first session).
1043 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
1044
1045 std::vector<std::thread> threads;
1046 for (size_t i = 0; i < kNumClients; i++) {
1047 // one of these threads will get stuck queueing a transaction once the
1048 // socket fills up, the other will be able to fill up transactions on
1049 // this object
1050 threads.push_back(std::thread([&] {
1051 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
1052 }
1053 }));
1054 }
1055 for (auto& t : threads) t.join();
1056
1057 Status status = iface->sleepMsAsync(kTooLongMs);
1058 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1059
Steven Moreland798e0d12021-07-14 23:19:25 +00001060 // now that it has died, wait for the remote session to shutdown
1061 std::vector<int32_t> remoteCounts;
1062 do {
1063 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
1064 } while (remoteCounts.size() == kNumClients);
1065
Steven Morelandd45be622021-06-04 02:19:37 +00001066 // the second session should be shutdown in the other process by the time we
1067 // are able to join above (it'll only be hung up once it finishes processing
1068 // any pending commands). We need to erase this session from the record
1069 // here, so that the destructor for our session won't check that this
1070 // session is valid, but we still want it to test the other session.
1071 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1072}
1073
Steven Moreland659416d2021-05-11 00:47:50 +00001074TEST_P(BinderRpc, Callbacks) {
1075 const static std::string kTestString = "good afternoon!";
1076
Steven Morelandc7d40132021-06-10 03:42:11 +00001077 for (bool callIsOneway : {true, false}) {
1078 for (bool callbackIsOneway : {true, false}) {
1079 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001080 auto proc = createRpcTestSocketServerProcess(
1081 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001082 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001083
Steven Morelandc7d40132021-06-10 03:42:11 +00001084 if (callIsOneway) {
1085 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1086 kTestString));
1087 } else {
1088 EXPECT_OK(
1089 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1090 }
Steven Moreland659416d2021-05-11 00:47:50 +00001091
Steven Morelandc7d40132021-06-10 03:42:11 +00001092 using std::literals::chrono_literals::operator""s;
1093 std::unique_lock<std::mutex> _l(cb->mMutex);
1094 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001095
Steven Morelandc7d40132021-06-10 03:42:11 +00001096 EXPECT_EQ(cb->mValues.size(), 1)
1097 << "callIsOneway: " << callIsOneway
1098 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1099 if (cb->mValues.empty()) continue;
1100 EXPECT_EQ(cb->mValues.at(0), kTestString)
1101 << "callIsOneway: " << callIsOneway
1102 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001103
Steven Morelandc7d40132021-06-10 03:42:11 +00001104 // since we are severing the connection, we need to go ahead and
1105 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001106 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1107 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1108 }
Steven Moreland659416d2021-05-11 00:47:50 +00001109
Steven Moreland1b304292021-07-15 22:59:34 +00001110 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001111 // need to manually shut it down
1112 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001113
Steven Morelandc7d40132021-06-10 03:42:11 +00001114 proc.expectAlreadyShutdown = true;
1115 }
Steven Moreland659416d2021-05-11 00:47:50 +00001116 }
1117 }
1118}
1119
Steven Moreland195edb82021-06-08 02:44:39 +00001120TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001121 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001122 auto cb = sp<MyBinderRpcCallback>::make();
1123
1124 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1125 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1126}
1127
Steven Morelandc1635952021-04-01 16:20:47 +00001128TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001129 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001130 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001131
1132 // make sure there is some state during crash
1133 // 1. we hold their binder
1134 sp<IBinderRpcSession> session;
1135 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1136 // 2. they hold our binder
1137 sp<IBinder> binder = new BBinder();
1138 EXPECT_OK(proc.rootIface->holdBinder(binder));
1139
1140 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1141 << "Do death cleanup: " << doDeathCleanup;
1142
Steven Morelandaf4ca712021-05-24 23:22:08 +00001143 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001144 }
1145}
1146
Steven Morelandd7302072021-05-15 01:32:04 +00001147TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001148 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001149
1150 // we can't allocate IPCThreadState so actually the first time should
1151 // succeed :(
1152 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1153
1154 // second time! we catch the error :)
1155 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1156
Steven Morelandaf4ca712021-05-24 23:22:08 +00001157 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001158}
1159
Steven Moreland37aff182021-03-26 02:04:16 +00001160TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001161 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001162
1163 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1164 ASSERT_NE(binder, nullptr);
1165
1166 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1167}
1168
1169TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001170 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001171
1172 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1173 ASSERT_NE(binder, nullptr);
1174
1175 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1176 ASSERT_NE(ndkBinder, nullptr);
1177
1178 std::string out;
1179 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1180 ASSERT_TRUE(status.isOk()) << status.getDescription();
1181 ASSERT_EQ("aoeuaoeu", out);
1182}
1183
Steven Moreland5553ac42020-11-11 02:14:45 +00001184ssize_t countFds() {
1185 DIR* dir = opendir("/proc/self/fd/");
1186 if (dir == nullptr) return -1;
1187 ssize_t ret = 0;
1188 dirent* ent;
1189 while ((ent = readdir(dir)) != nullptr) ret++;
1190 closedir(dir);
1191 return ret;
1192}
1193
Steven Morelandc1635952021-04-01 16:20:47 +00001194TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001195 ssize_t beforeFds = countFds();
1196 ASSERT_GE(beforeFds, 0);
1197 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001198 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001199 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1200 }
1201 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1202}
1203
Steven Morelandda573042021-06-12 01:13:45 +00001204static bool testSupportVsockLoopback() {
Yifan Hong702115c2021-06-24 15:39:18 -07001205 // We don't need to enable TLS to know if vsock is supported.
Steven Morelandda573042021-06-12 01:13:45 +00001206 unsigned int vsockPort = allocateVsockPort();
Yifan Hong702115c2021-06-24 15:39:18 -07001207 sp<RpcServer> server = RpcServer::make(RpcTransportCtxFactoryRaw::make());
Steven Morelandda573042021-06-12 01:13:45 +00001208 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland1eab3452021-08-05 16:56:20 -07001209 if (status_t status = server->setupVsockServer(vsockPort); status != OK) {
1210 if (status == -EAFNOSUPPORT) {
1211 return false;
1212 }
1213 LOG_ALWAYS_FATAL("Could not setup vsock server: %s", statusToString(status).c_str());
1214 }
Steven Morelandda573042021-06-12 01:13:45 +00001215 server->start();
1216
Yifan Hongfdd9f692021-09-09 15:12:52 -07001217 sp<RpcSession> session = RpcSession::make(RpcTransportCtxFactoryRaw::make());
Steven Moreland2372f9d2021-08-05 15:42:01 -07001218 status_t status = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001219 while (!server->shutdown()) usleep(10000);
Steven Moreland2372f9d2021-08-05 15:42:01 -07001220 ALOGE("Detected vsock loopback supported: %s", statusToString(status).c_str());
1221 return status == OK;
Steven Morelandda573042021-06-12 01:13:45 +00001222}
1223
1224static std::vector<SocketType> testSocketTypes() {
Steven Moreland4198a122021-08-03 17:37:58 -07001225 std::vector<SocketType> ret = {SocketType::PRECONNECTED, SocketType::UNIX, SocketType::INET};
Steven Morelandda573042021-06-12 01:13:45 +00001226
1227 static bool hasVsockLoopback = testSupportVsockLoopback();
1228
1229 if (hasVsockLoopback) {
1230 ret.push_back(SocketType::VSOCK);
1231 }
1232
1233 return ret;
1234}
1235
Yifan Hong702115c2021-06-24 15:39:18 -07001236INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
1237 ::testing::Combine(::testing::ValuesIn(testSocketTypes()),
1238 ::testing::ValuesIn(RpcSecurityValues())),
1239 BinderRpc::PrintParamInfo);
Steven Morelandc1635952021-04-01 16:20:47 +00001240
Yifan Hong702115c2021-06-24 15:39:18 -07001241class BinderRpcServerRootObject
1242 : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {};
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001243
1244TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1245 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1246 auto setRootObject = [](bool isStrong) -> SetFn {
1247 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1248 };
1249
Yifan Hong702115c2021-06-24 15:39:18 -07001250 auto [isStrong1, isStrong2, rpcSecurity] = GetParam();
1251 auto server = RpcServer::make(newFactory(rpcSecurity));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001252 auto binder1 = sp<BBinder>::make();
1253 IBinder* binderRaw1 = binder1.get();
1254 setRootObject(isStrong1)(server.get(), binder1);
1255 EXPECT_EQ(binderRaw1, server->getRootObject());
1256 binder1.clear();
1257 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1258
1259 auto binder2 = sp<BBinder>::make();
1260 IBinder* binderRaw2 = binder2.get();
1261 setRootObject(isStrong2)(server.get(), binder2);
1262 EXPECT_EQ(binderRaw2, server->getRootObject());
1263 binder2.clear();
1264 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1265}
1266
1267INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
Yifan Hong702115c2021-06-24 15:39:18 -07001268 ::testing::Combine(::testing::Bool(), ::testing::Bool(),
1269 ::testing::ValuesIn(RpcSecurityValues())));
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001270
Yifan Hong1a235852021-05-13 16:07:47 -07001271class OneOffSignal {
1272public:
1273 // If notify() was previously called, or is called within |duration|, return true; else false.
1274 template <typename R, typename P>
1275 bool wait(std::chrono::duration<R, P> duration) {
1276 std::unique_lock<std::mutex> lock(mMutex);
1277 return mCv.wait_for(lock, duration, [this] { return mValue; });
1278 }
1279 void notify() {
1280 std::unique_lock<std::mutex> lock(mMutex);
1281 mValue = true;
1282 lock.unlock();
1283 mCv.notify_all();
1284 }
1285
1286private:
1287 std::mutex mMutex;
1288 std::condition_variable mCv;
1289 bool mValue = false;
1290};
1291
Yifan Hong702115c2021-06-24 15:39:18 -07001292TEST_P(BinderRpcSimple, Shutdown) {
Yifan Hong1a235852021-05-13 16:07:47 -07001293 auto addr = allocateSocketAddress();
1294 unlink(addr.c_str());
Yifan Hong702115c2021-06-24 15:39:18 -07001295 auto server = RpcServer::make(newFactory(GetParam()));
Yifan Hong1a235852021-05-13 16:07:47 -07001296 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001297 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Yifan Hong1a235852021-05-13 16:07:47 -07001298 auto joinEnds = std::make_shared<OneOffSignal>();
1299
1300 // If things are broken and the thread never stops, don't block other tests. Because the thread
1301 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1302 // shared pointers are passed.
1303 std::thread([server, joinEnds] {
1304 server->join();
1305 joinEnds->notify();
1306 }).detach();
1307
1308 bool shutdown = false;
1309 for (int i = 0; i < 10 && !shutdown; i++) {
1310 usleep(300 * 1000); // 300ms; total 3s
1311 if (server->shutdown()) shutdown = true;
1312 }
1313 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1314
1315 ASSERT_TRUE(joinEnds->wait(2s))
1316 << "After server->shutdown() returns true, join() did not stop after 2s";
1317}
1318
Yifan Hong194acf22021-06-29 18:44:56 -07001319TEST(BinderRpc, Java) {
1320#if !defined(__ANDROID__)
1321 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1322 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1323 "to binderHostDeviceTest. Hence, just disable this test on host.";
1324#endif // !__ANDROID__
1325 sp<IServiceManager> sm = defaultServiceManager();
1326 ASSERT_NE(nullptr, sm);
1327 // Any Java service with non-empty getInterfaceDescriptor() would do.
1328 // Let's pick batteryproperties.
1329 auto binder = sm->checkService(String16("batteryproperties"));
1330 ASSERT_NE(nullptr, binder);
1331 auto descriptor = binder->getInterfaceDescriptor();
1332 ASSERT_GE(descriptor.size(), 0);
1333 ASSERT_EQ(OK, binder->pingBinder());
1334
1335 auto rpcServer = RpcServer::make();
1336 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1337 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001338 ASSERT_EQ(OK, rpcServer->setupInetServer(kLocalInetAddress, 0, &port));
Yifan Hong194acf22021-06-29 18:44:56 -07001339 auto socket = rpcServer->releaseServer();
1340
1341 auto keepAlive = sp<BBinder>::make();
1342 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1343
1344 auto rpcSession = RpcSession::make();
Steven Moreland2372f9d2021-08-05 15:42:01 -07001345 ASSERT_EQ(OK, rpcSession->setupInetClient("127.0.0.1", port));
Yifan Hong194acf22021-06-29 18:44:56 -07001346 auto rpcBinder = rpcSession->getRootObject();
1347 ASSERT_NE(nullptr, rpcBinder);
1348
1349 ASSERT_EQ(OK, rpcBinder->pingBinder());
1350
1351 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1352 << "getInterfaceDescriptor should not crash system_server";
1353 ASSERT_EQ(OK, rpcBinder->pingBinder());
1354}
1355
Yifan Hong702115c2021-06-24 15:39:18 -07001356INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcSimple, ::testing::ValuesIn(RpcSecurityValues()),
1357 BinderRpcSimple::PrintTestParam);
1358
Steven Morelandc1635952021-04-01 16:20:47 +00001359} // namespace android
1360
1361int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001362 ::testing::InitGoogleTest(&argc, argv);
1363 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1364 return RUN_ALL_TESTS();
1365}