blob: d5786bcbe1af26500caaea542989adfad07d9d86 [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>
Steven Moreland5553ac42020-11-11 02:14:45 +000032#include <gtest/gtest.h>
33
Steven Morelandc1635952021-04-01 16:20:47 +000034#include <chrono>
35#include <cstdlib>
36#include <iostream>
37#include <thread>
Steven Moreland659416d2021-05-11 00:47:50 +000038#include <type_traits>
Steven Morelandc1635952021-04-01 16:20:47 +000039
Steven Morelandc1635952021-04-01 16:20:47 +000040#include <sys/prctl.h>
41#include <unistd.h>
42
Steven Morelandbd5002b2021-05-04 23:12:56 +000043#include "../RpcState.h" // for debugging
44#include "../vm_sockets.h" // for VMADDR_*
Steven Moreland5553ac42020-11-11 02:14:45 +000045
Yifan Hong1a235852021-05-13 16:07:47 -070046using namespace std::chrono_literals;
47
Steven Moreland5553ac42020-11-11 02:14:45 +000048namespace android {
49
Steven Morelandbf57bce2021-07-26 15:26:12 -070050static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
51 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
52
Steven Moreland1fda67b2021-04-02 18:35:50 +000053TEST(BinderRpcParcel, EntireParcelFormatted) {
54 Parcel p;
55 p.writeInt32(3);
56
57 EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
58}
59
Yifan Hong00aeb762021-05-12 17:07:36 -070060TEST(BinderRpc, SetExternalServer) {
61 base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
62 int sinkFd = sink.get();
63 auto server = RpcServer::make();
64 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
65 ASSERT_FALSE(server->hasServer());
66 ASSERT_TRUE(server->setupExternalServer(std::move(sink)));
67 ASSERT_TRUE(server->hasServer());
68 base::unique_fd retrieved = server->releaseServer();
69 ASSERT_FALSE(server->hasServer());
70 ASSERT_EQ(sinkFd, retrieved.get());
71}
72
Steven Morelandbf57bce2021-07-26 15:26:12 -070073TEST(BinderRpc, CannotUseNextWireVersion) {
74 auto session = RpcSession::make();
75 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
76 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
77 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
78 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
79}
80
81TEST(BinderRpc, CanUseExperimentalWireVersion) {
82 auto session = RpcSession::make();
83 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
84}
85
Steven Moreland5553ac42020-11-11 02:14:45 +000086using android::binder::Status;
87
88#define EXPECT_OK(status) \
89 do { \
90 Status stat = (status); \
91 EXPECT_TRUE(stat.isOk()) << stat; \
92 } while (false)
93
94class MyBinderRpcSession : public BnBinderRpcSession {
95public:
96 static std::atomic<int32_t> gNum;
97
98 MyBinderRpcSession(const std::string& name) : mName(name) { gNum++; }
99 Status getName(std::string* name) override {
100 *name = mName;
101 return Status::ok();
102 }
103 ~MyBinderRpcSession() { gNum--; }
104
105private:
106 std::string mName;
107};
108std::atomic<int32_t> MyBinderRpcSession::gNum;
109
Steven Moreland659416d2021-05-11 00:47:50 +0000110class MyBinderRpcCallback : public BnBinderRpcCallback {
111 Status sendCallback(const std::string& value) {
112 std::unique_lock _l(mMutex);
113 mValues.push_back(value);
114 _l.unlock();
115 mCv.notify_one();
116 return Status::ok();
117 }
118 Status sendOnewayCallback(const std::string& value) { return sendCallback(value); }
119
120public:
121 std::mutex mMutex;
122 std::condition_variable mCv;
123 std::vector<std::string> mValues;
124};
125
Steven Moreland5553ac42020-11-11 02:14:45 +0000126class MyBinderRpcTest : public BnBinderRpcTest {
127public:
Steven Moreland611d15f2021-05-01 01:28:27 +0000128 wp<RpcServer> server;
Steven Moreland5553ac42020-11-11 02:14:45 +0000129
130 Status sendString(const std::string& str) override {
Steven Morelandc6046982021-04-20 00:49:42 +0000131 (void)str;
Steven Moreland5553ac42020-11-11 02:14:45 +0000132 return Status::ok();
133 }
134 Status doubleString(const std::string& str, std::string* strstr) override {
Steven Moreland5553ac42020-11-11 02:14:45 +0000135 *strstr = str + str;
136 return Status::ok();
137 }
Steven Moreland736664b2021-05-01 04:27:25 +0000138 Status countBinders(std::vector<int32_t>* out) override {
Steven Moreland611d15f2021-05-01 01:28:27 +0000139 sp<RpcServer> spServer = server.promote();
140 if (spServer == nullptr) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000141 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
142 }
Steven Moreland736664b2021-05-01 04:27:25 +0000143 out->clear();
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000144 for (auto session : spServer->listSessions()) {
145 size_t count = session->state()->countBinders();
Steven Moreland736664b2021-05-01 04:27:25 +0000146 out->push_back(count);
Steven Moreland611d15f2021-05-01 01:28:27 +0000147 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000148 return Status::ok();
149 }
150 Status pingMe(const sp<IBinder>& binder, int32_t* out) override {
151 if (binder == nullptr) {
152 std::cout << "Received null binder!" << std::endl;
153 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
154 }
155 *out = binder->pingBinder();
156 return Status::ok();
157 }
158 Status repeatBinder(const sp<IBinder>& binder, sp<IBinder>* out) override {
159 *out = binder;
160 return Status::ok();
161 }
162 static sp<IBinder> mHeldBinder;
163 Status holdBinder(const sp<IBinder>& binder) override {
164 mHeldBinder = binder;
165 return Status::ok();
166 }
167 Status getHeldBinder(sp<IBinder>* held) override {
168 *held = mHeldBinder;
169 return Status::ok();
170 }
171 Status nestMe(const sp<IBinderRpcTest>& binder, int count) override {
172 if (count <= 0) return Status::ok();
173 return binder->nestMe(this, count - 1);
174 }
175 Status alwaysGiveMeTheSameBinder(sp<IBinder>* out) override {
176 static sp<IBinder> binder = new BBinder;
177 *out = binder;
178 return Status::ok();
179 }
180 Status openSession(const std::string& name, sp<IBinderRpcSession>* out) override {
181 *out = new MyBinderRpcSession(name);
182 return Status::ok();
183 }
184 Status getNumOpenSessions(int32_t* out) override {
185 *out = MyBinderRpcSession::gNum;
186 return Status::ok();
187 }
188
189 std::mutex blockMutex;
190 Status lock() override {
191 blockMutex.lock();
192 return Status::ok();
193 }
194 Status unlockInMsAsync(int32_t ms) override {
195 usleep(ms * 1000);
196 blockMutex.unlock();
197 return Status::ok();
198 }
199 Status lockUnlock() override {
200 std::lock_guard<std::mutex> _l(blockMutex);
201 return Status::ok();
202 }
203
204 Status sleepMs(int32_t ms) override {
205 usleep(ms * 1000);
206 return Status::ok();
207 }
208
209 Status sleepMsAsync(int32_t ms) override {
210 // In-process binder calls are asynchronous, but the call to this method
211 // is synchronous wrt its client. This in/out-process threading model
212 // diffentiation is a classic binder leaky abstraction (for better or
213 // worse) and is preserved here the way binder sockets plugs itself
214 // into BpBinder, as nothing is changed at the higher levels
215 // (IInterface) which result in this behavior.
216 return sleepMs(ms);
217 }
218
Steven Moreland659416d2021-05-11 00:47:50 +0000219 Status doCallback(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
220 const std::string& value) override {
221 if (callback == nullptr) {
222 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
223 }
224
225 if (delayed) {
226 std::thread([=]() {
227 ALOGE("Executing delayed callback: '%s'", value.c_str());
Steven Morelandc7d40132021-06-10 03:42:11 +0000228 Status status = doCallback(callback, oneway, false, value);
229 ALOGE("Delayed callback status: '%s'", status.toString8().c_str());
Steven Moreland659416d2021-05-11 00:47:50 +0000230 }).detach();
231 return Status::ok();
232 }
233
234 if (oneway) {
235 return callback->sendOnewayCallback(value);
236 }
237
238 return callback->sendCallback(value);
239 }
240
Steven Morelandc7d40132021-06-10 03:42:11 +0000241 Status doCallbackAsync(const sp<IBinderRpcCallback>& callback, bool oneway, bool delayed,
242 const std::string& value) override {
243 return doCallback(callback, oneway, delayed, value);
244 }
245
Steven Moreland5553ac42020-11-11 02:14:45 +0000246 Status die(bool cleanup) override {
247 if (cleanup) {
248 exit(1);
249 } else {
250 _exit(1);
251 }
252 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000253
254 Status scheduleShutdown() override {
255 sp<RpcServer> strongServer = server.promote();
256 if (strongServer == nullptr) {
257 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
258 }
259 std::thread([=] {
260 LOG_ALWAYS_FATAL_IF(!strongServer->shutdown(), "Could not shutdown");
261 }).detach();
262 return Status::ok();
263 }
264
Steven Morelandd7302072021-05-15 01:32:04 +0000265 Status useKernelBinderCallingId() override {
266 // this is WRONG! It does not make sense when using RPC binder, and
267 // because it is SO wrong, and so much code calls this, it should abort!
268
269 (void)IPCThreadState::self()->getCallingPid();
270 return Status::ok();
271 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000272};
273sp<IBinder> MyBinderRpcTest::mHeldBinder;
274
275class Process {
276public:
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700277 Process(Process&&) = default;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700278 Process(const std::function<void(android::base::borrowed_fd /* writeEnd */)>& f) {
279 android::base::unique_fd writeEnd;
280 CHECK(android::base::Pipe(&mReadEnd, &writeEnd)) << strerror(errno);
Steven Moreland5553ac42020-11-11 02:14:45 +0000281 if (0 == (mPid = fork())) {
282 // racey: assume parent doesn't crash before this is set
283 prctl(PR_SET_PDEATHSIG, SIGHUP);
284
Yifan Hong0f58fb92021-06-16 16:09:23 -0700285 f(writeEnd);
Steven Morelandaf4ca712021-05-24 23:22:08 +0000286
287 exit(0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000288 }
289 }
290 ~Process() {
291 if (mPid != 0) {
Steven Morelandaf4ca712021-05-24 23:22:08 +0000292 waitpid(mPid, nullptr, 0);
Steven Moreland5553ac42020-11-11 02:14:45 +0000293 }
294 }
Yifan Hong0f58fb92021-06-16 16:09:23 -0700295 android::base::borrowed_fd readEnd() { return mReadEnd; }
Steven Moreland5553ac42020-11-11 02:14:45 +0000296
297private:
298 pid_t mPid = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700299 android::base::unique_fd mReadEnd;
Steven Moreland5553ac42020-11-11 02:14:45 +0000300};
301
302static std::string allocateSocketAddress() {
303 static size_t id = 0;
Steven Moreland4bfbf2e2021-04-14 22:15:16 +0000304 std::string temp = getenv("TMPDIR") ?: "/tmp";
305 return temp + "/binderRpcTest_" + std::to_string(id++);
Steven Moreland5553ac42020-11-11 02:14:45 +0000306};
307
Steven Morelandda573042021-06-12 01:13:45 +0000308static unsigned int allocateVsockPort() {
309 static unsigned int vsockPort = 3456;
310 return vsockPort++;
311}
312
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000313struct ProcessSession {
Steven Moreland5553ac42020-11-11 02:14:45 +0000314 // reference to process hosting a socket server
315 Process host;
316
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000317 struct SessionInfo {
318 sp<RpcSession> session;
Steven Moreland736664b2021-05-01 04:27:25 +0000319 sp<IBinder> root;
320 };
Steven Moreland5553ac42020-11-11 02:14:45 +0000321
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000322 // client session objects associated with other process
323 // each one represents a separate session
324 std::vector<SessionInfo> sessions;
Steven Moreland5553ac42020-11-11 02:14:45 +0000325
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000326 ProcessSession(ProcessSession&&) = default;
327 ~ProcessSession() {
328 for (auto& session : sessions) {
329 session.root = nullptr;
Steven Moreland736664b2021-05-01 04:27:25 +0000330 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000331
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000332 for (auto& info : sessions) {
333 sp<RpcSession>& session = info.session;
Steven Moreland736664b2021-05-01 04:27:25 +0000334
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000335 EXPECT_NE(nullptr, session);
336 EXPECT_NE(nullptr, session->state());
337 EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:");
Steven Moreland736664b2021-05-01 04:27:25 +0000338
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000339 wp<RpcSession> weakSession = session;
340 session = nullptr;
341 EXPECT_EQ(nullptr, weakSession.promote()) << "Leaked session";
Steven Moreland736664b2021-05-01 04:27:25 +0000342 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000343 }
344};
345
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000346// Process session where the process hosts IBinderRpcTest, the server used
Steven Moreland5553ac42020-11-11 02:14:45 +0000347// for most testing here
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000348struct BinderRpcTestProcessSession {
349 ProcessSession proc;
Steven Moreland5553ac42020-11-11 02:14:45 +0000350
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000351 // pre-fetched root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000352 sp<IBinder> rootBinder;
353
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000354 // pre-casted root object (for first session)
Steven Moreland5553ac42020-11-11 02:14:45 +0000355 sp<IBinderRpcTest> rootIface;
356
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000357 // whether session should be invalidated by end of run
Steven Morelandaf4ca712021-05-24 23:22:08 +0000358 bool expectAlreadyShutdown = false;
Steven Moreland736664b2021-05-01 04:27:25 +0000359
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000360 BinderRpcTestProcessSession(BinderRpcTestProcessSession&&) = default;
361 ~BinderRpcTestProcessSession() {
Steven Moreland659416d2021-05-11 00:47:50 +0000362 EXPECT_NE(nullptr, rootIface);
363 if (rootIface == nullptr) return;
364
Steven Morelandaf4ca712021-05-24 23:22:08 +0000365 if (!expectAlreadyShutdown) {
Steven Moreland736664b2021-05-01 04:27:25 +0000366 std::vector<int32_t> remoteCounts;
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000367 // calling over any sessions counts across all sessions
Steven Moreland736664b2021-05-01 04:27:25 +0000368 EXPECT_OK(rootIface->countBinders(&remoteCounts));
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000369 EXPECT_EQ(remoteCounts.size(), proc.sessions.size());
Steven Moreland736664b2021-05-01 04:27:25 +0000370 for (auto remoteCount : remoteCounts) {
371 EXPECT_EQ(remoteCount, 1);
372 }
Steven Morelandaf4ca712021-05-24 23:22:08 +0000373
Steven Moreland798e0d12021-07-14 23:19:25 +0000374 // even though it is on another thread, shutdown races with
375 // the transaction reply being written
376 if (auto status = rootIface->scheduleShutdown(); !status.isOk()) {
377 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
378 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000379 }
380
381 rootIface = nullptr;
382 rootBinder = nullptr;
383 }
384};
385
Steven Morelandc1635952021-04-01 16:20:47 +0000386enum class SocketType {
387 UNIX,
388 VSOCK,
Yifan Hong0d2bd112021-04-13 17:38:36 -0700389 INET,
Steven Morelandc1635952021-04-01 16:20:47 +0000390};
391static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
392 switch (info.param) {
393 case SocketType::UNIX:
394 return "unix_domain_socket";
395 case SocketType::VSOCK:
396 return "vm_socket";
Yifan Hong0d2bd112021-04-13 17:38:36 -0700397 case SocketType::INET:
398 return "inet_socket";
Steven Morelandc1635952021-04-01 16:20:47 +0000399 default:
400 LOG_ALWAYS_FATAL("Unknown socket type");
401 return "";
402 }
Steven Moreland5553ac42020-11-11 02:14:45 +0000403}
Steven Morelandda573042021-06-12 01:13:45 +0000404
Steven Morelandc1635952021-04-01 16:20:47 +0000405class BinderRpc : public ::testing::TestWithParam<SocketType> {
406public:
Steven Moreland4313d7e2021-07-15 23:41:22 +0000407 struct Options {
408 size_t numThreads = 1;
409 size_t numSessions = 1;
410 size_t numIncomingConnections = 0;
411 };
412
Steven Morelandc1635952021-04-01 16:20:47 +0000413 // This creates a new process serving an interface on a certain number of
414 // threads.
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000415 ProcessSession createRpcTestSocketServerProcess(
Steven Moreland4313d7e2021-07-15 23:41:22 +0000416 const Options& options, const std::function<void(const sp<RpcServer>&)>& configure) {
417 CHECK_GE(options.numSessions, 1) << "Must have at least one session to a server";
Steven Moreland736664b2021-05-01 04:27:25 +0000418
Steven Morelandc1635952021-04-01 16:20:47 +0000419 SocketType socketType = GetParam();
420
Steven Morelandda573042021-06-12 01:13:45 +0000421 unsigned int vsockPort = allocateVsockPort();
Steven Morelandc1635952021-04-01 16:20:47 +0000422 std::string addr = allocateSocketAddress();
423 unlink(addr.c_str());
Steven Morelandc1635952021-04-01 16:20:47 +0000424
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000425 auto ret = ProcessSession{
Yifan Hong0f58fb92021-06-16 16:09:23 -0700426 .host = Process([&](android::base::borrowed_fd writeEnd) {
Steven Morelandc1635952021-04-01 16:20:47 +0000427 sp<RpcServer> server = RpcServer::make();
428
429 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000430 server->setMaxThreads(options.numThreads);
Steven Morelandc1635952021-04-01 16:20:47 +0000431
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000432 unsigned int outPort = 0;
433
Steven Morelandc1635952021-04-01 16:20:47 +0000434 switch (socketType) {
435 case SocketType::UNIX:
Steven Moreland611d15f2021-05-01 01:28:27 +0000436 CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
Steven Morelandc1635952021-04-01 16:20:47 +0000437 break;
438 case SocketType::VSOCK:
Steven Moreland611d15f2021-05-01 01:28:27 +0000439 CHECK(server->setupVsockServer(vsockPort));
Steven Morelandc1635952021-04-01 16:20:47 +0000440 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700441 case SocketType::INET: {
Steven Moreland611d15f2021-05-01 01:28:27 +0000442 CHECK(server->setupInetServer(0, &outPort));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700443 CHECK_NE(0, outPort);
Yifan Hong0d2bd112021-04-13 17:38:36 -0700444 break;
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700445 }
Steven Morelandc1635952021-04-01 16:20:47 +0000446 default:
447 LOG_ALWAYS_FATAL("Unknown socket type");
448 }
449
Yifan Hong0f58fb92021-06-16 16:09:23 -0700450 CHECK(android::base::WriteFully(writeEnd, &outPort, sizeof(outPort)));
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000451
Steven Moreland611d15f2021-05-01 01:28:27 +0000452 configure(server);
Steven Morelandc1635952021-04-01 16:20:47 +0000453
Steven Morelandf137de92021-04-24 01:54:26 +0000454 server->join();
Steven Morelandaf4ca712021-05-24 23:22:08 +0000455
456 // Another thread calls shutdown. Wait for it to complete.
457 (void)server->shutdown();
Steven Morelandc1635952021-04-01 16:20:47 +0000458 }),
Steven Morelandc1635952021-04-01 16:20:47 +0000459 };
460
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000461 // always read socket, so that we have waited for the server to start
462 unsigned int outPort = 0;
Yifan Hong0f58fb92021-06-16 16:09:23 -0700463 CHECK(android::base::ReadFully(ret.host.readEnd(), &outPort, sizeof(outPort)));
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700464 if (socketType == SocketType::INET) {
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000465 CHECK_NE(0, outPort);
Yifan Hong6d82c8a2021-04-26 20:26:45 -0700466 }
467
Steven Moreland4313d7e2021-07-15 23:41:22 +0000468 for (size_t i = 0; i < options.numSessions; i++) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000469 sp<RpcSession> session = RpcSession::make();
Steven Moreland4313d7e2021-07-15 23:41:22 +0000470 session->setMaxThreads(options.numIncomingConnections);
Steven Moreland659416d2021-05-11 00:47:50 +0000471
Steven Moreland76d2c1f2021-05-05 20:28:58 +0000472 switch (socketType) {
473 case SocketType::UNIX:
474 if (session->setupUnixDomainClient(addr.c_str())) goto success;
475 break;
476 case SocketType::VSOCK:
477 if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
478 break;
479 case SocketType::INET:
480 if (session->setupInetClient("127.0.0.1", outPort)) goto success;
481 break;
482 default:
483 LOG_ALWAYS_FATAL("Unknown socket type");
Steven Morelandc1635952021-04-01 16:20:47 +0000484 }
Steven Moreland736664b2021-05-01 04:27:25 +0000485 LOG_ALWAYS_FATAL("Could not connect");
486 success:
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000487 ret.sessions.push_back({session, session->getRootObject()});
Steven Morelandc1635952021-04-01 16:20:47 +0000488 }
Steven Morelandc1635952021-04-01 16:20:47 +0000489 return ret;
490 }
491
Steven Moreland4313d7e2021-07-15 23:41:22 +0000492 BinderRpcTestProcessSession createRpcTestSocketServerProcess(const Options& options) {
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000493 BinderRpcTestProcessSession ret{
Steven Moreland4313d7e2021-07-15 23:41:22 +0000494 .proc = createRpcTestSocketServerProcess(options,
Steven Moreland611d15f2021-05-01 01:28:27 +0000495 [&](const sp<RpcServer>& server) {
Steven Morelandc1635952021-04-01 16:20:47 +0000496 sp<MyBinderRpcTest> service =
497 new MyBinderRpcTest;
498 server->setRootObject(service);
Steven Moreland611d15f2021-05-01 01:28:27 +0000499 service->server = server;
Steven Morelandc1635952021-04-01 16:20:47 +0000500 }),
501 };
502
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000503 ret.rootBinder = ret.proc.sessions.at(0).root;
Steven Morelandc1635952021-04-01 16:20:47 +0000504 ret.rootIface = interface_cast<IBinderRpcTest>(ret.rootBinder);
505
506 return ret;
507 }
508};
509
Steven Morelandc1635952021-04-01 16:20:47 +0000510TEST_P(BinderRpc, Ping) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000511 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000512 ASSERT_NE(proc.rootBinder, nullptr);
513 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
514}
515
Steven Moreland4cf688f2021-03-31 01:48:58 +0000516TEST_P(BinderRpc, GetInterfaceDescriptor) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000517 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland4cf688f2021-03-31 01:48:58 +0000518 ASSERT_NE(proc.rootBinder, nullptr);
519 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
520}
521
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000522TEST_P(BinderRpc, MultipleSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000523 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000524 for (auto session : proc.proc.sessions) {
525 ASSERT_NE(nullptr, session.root);
526 EXPECT_EQ(OK, session.root->pingBinder());
Steven Moreland736664b2021-05-01 04:27:25 +0000527 }
528}
529
Steven Morelandc1635952021-04-01 16:20:47 +0000530TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000531 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000532 Parcel data;
533 Parcel reply;
534 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
535}
536
Steven Moreland67753c32021-04-02 18:45:19 +0000537TEST_P(BinderRpc, AppendSeparateFormats) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000538 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland67753c32021-04-02 18:45:19 +0000539
540 Parcel p1;
541 p1.markForBinder(proc.rootBinder);
542 p1.writeInt32(3);
543
544 Parcel p2;
545
546 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
547 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
548}
549
Steven Morelandc1635952021-04-01 16:20:47 +0000550TEST_P(BinderRpc, UnknownTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000551 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000552 Parcel data;
553 data.markForBinder(proc.rootBinder);
554 Parcel reply;
555 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
556}
557
Steven Morelandc1635952021-04-01 16:20:47 +0000558TEST_P(BinderRpc, SendSomethingOneway) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000559 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000560 EXPECT_OK(proc.rootIface->sendString("asdf"));
561}
562
Steven Morelandc1635952021-04-01 16:20:47 +0000563TEST_P(BinderRpc, SendAndGetResultBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000564 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000565 std::string doubled;
566 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
567 EXPECT_EQ("cool cool ", doubled);
568}
569
Steven Morelandc1635952021-04-01 16:20:47 +0000570TEST_P(BinderRpc, SendAndGetResultBackBig) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000571 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000572 std::string single = std::string(1024, 'a');
573 std::string doubled;
574 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
575 EXPECT_EQ(single + single, doubled);
576}
577
Steven Morelandc1635952021-04-01 16:20:47 +0000578TEST_P(BinderRpc, CallMeBack) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000579 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000580
581 int32_t pingResult;
582 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
583 EXPECT_EQ(OK, pingResult);
584
585 EXPECT_EQ(0, MyBinderRpcSession::gNum);
586}
587
Steven Morelandc1635952021-04-01 16:20:47 +0000588TEST_P(BinderRpc, RepeatBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000589 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000590
591 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
592 sp<IBinder> outBinder;
593 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
594 EXPECT_EQ(inBinder, outBinder);
595
596 wp<IBinder> weak = inBinder;
597 inBinder = nullptr;
598 outBinder = nullptr;
599
600 // Force reading a reply, to process any pending dec refs from the other
601 // process (the other process will process dec refs there before processing
602 // the ping here).
603 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
604
605 EXPECT_EQ(nullptr, weak.promote());
606
607 EXPECT_EQ(0, MyBinderRpcSession::gNum);
608}
609
Steven Morelandc1635952021-04-01 16:20:47 +0000610TEST_P(BinderRpc, RepeatTheirBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000611 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000612
613 sp<IBinderRpcSession> session;
614 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
615
616 sp<IBinder> inBinder = IInterface::asBinder(session);
617 sp<IBinder> outBinder;
618 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
619 EXPECT_EQ(inBinder, outBinder);
620
621 wp<IBinder> weak = inBinder;
622 session = nullptr;
623 inBinder = nullptr;
624 outBinder = nullptr;
625
626 // Force reading a reply, to process any pending dec refs from the other
627 // process (the other process will process dec refs there before processing
628 // the ping here).
629 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
630
631 EXPECT_EQ(nullptr, weak.promote());
632}
633
Steven Morelandc1635952021-04-01 16:20:47 +0000634TEST_P(BinderRpc, RepeatBinderNull) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000635 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000636
637 sp<IBinder> outBinder;
638 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
639 EXPECT_EQ(nullptr, outBinder);
640}
641
Steven Morelandc1635952021-04-01 16:20:47 +0000642TEST_P(BinderRpc, HoldBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000643 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000644
645 IBinder* ptr = nullptr;
646 {
647 sp<IBinder> binder = new BBinder();
648 ptr = binder.get();
649 EXPECT_OK(proc.rootIface->holdBinder(binder));
650 }
651
652 sp<IBinder> held;
653 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
654
655 EXPECT_EQ(held.get(), ptr);
656
657 // stop holding binder, because we test to make sure references are cleaned
658 // up
659 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
660 // and flush ref counts
661 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
662}
663
664// START TESTS FOR LIMITATIONS OF SOCKET BINDER
665// These are behavioral differences form regular binder, where certain usecases
666// aren't supported.
667
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000668TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000669 auto proc1 = createRpcTestSocketServerProcess({});
670 auto proc2 = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000671
672 sp<IBinder> outBinder;
673 EXPECT_EQ(INVALID_OPERATION,
674 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
675}
676
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000677TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000678 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
Steven Moreland736664b2021-05-01 04:27:25 +0000679
680 sp<IBinder> outBinder;
681 EXPECT_EQ(INVALID_OPERATION,
Steven Morelandbdb53ab2021-05-05 17:57:41 +0000682 proc.rootIface->repeatBinder(proc.proc.sessions.at(1).root, &outBinder)
Steven Moreland736664b2021-05-01 04:27:25 +0000683 .transactionError());
684}
685
Steven Morelandc1635952021-04-01 16:20:47 +0000686TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000687 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000688
689 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
690 sp<IBinder> outBinder;
691 EXPECT_EQ(INVALID_OPERATION,
692 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
693}
694
Steven Morelandc1635952021-04-01 16:20:47 +0000695TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000696 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000697
698 // for historical reasons, IServiceManager interface only returns the
699 // exception code
700 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
701 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
702}
703
704// END TESTS FOR LIMITATIONS OF SOCKET BINDER
705
Steven Morelandc1635952021-04-01 16:20:47 +0000706TEST_P(BinderRpc, RepeatRootObject) {
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(proc.rootBinder, &outBinder));
711 EXPECT_EQ(proc.rootBinder, outBinder);
712}
713
Steven Morelandc1635952021-04-01 16:20:47 +0000714TEST_P(BinderRpc, NestedTransactions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000715 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000716
717 auto nastyNester = sp<MyBinderRpcTest>::make();
718 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
719
720 wp<IBinder> weak = nastyNester;
721 nastyNester = nullptr;
722 EXPECT_EQ(nullptr, weak.promote());
723}
724
Steven Morelandc1635952021-04-01 16:20:47 +0000725TEST_P(BinderRpc, SameBinderEquality) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000726 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000727
728 sp<IBinder> a;
729 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
730
731 sp<IBinder> b;
732 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
733
734 EXPECT_EQ(a, b);
735}
736
Steven Morelandc1635952021-04-01 16:20:47 +0000737TEST_P(BinderRpc, SameBinderEqualityWeak) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000738 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000739
740 sp<IBinder> a;
741 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
742 wp<IBinder> weak = a;
743 a = nullptr;
744
745 sp<IBinder> b;
746 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
747
748 // this is the wrong behavior, since BpBinder
749 // doesn't implement onIncStrongAttempted
750 // but make sure there is no crash
751 EXPECT_EQ(nullptr, weak.promote());
752
753 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
754
755 // In order to fix this:
756 // - need to have incStrongAttempted reflected across IPC boundary (wait for
757 // response to promote - round trip...)
758 // - sendOnLastWeakRef, to delete entries out of RpcState table
759 EXPECT_EQ(b, weak.promote());
760}
761
762#define expectSessions(expected, iface) \
763 do { \
764 int session; \
765 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
766 EXPECT_EQ(expected, session); \
767 } while (false)
768
Steven Morelandc1635952021-04-01 16:20:47 +0000769TEST_P(BinderRpc, SingleSession) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000770 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000771
772 sp<IBinderRpcSession> session;
773 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
774 std::string out;
775 EXPECT_OK(session->getName(&out));
776 EXPECT_EQ("aoeu", out);
777
778 expectSessions(1, proc.rootIface);
779 session = nullptr;
780 expectSessions(0, proc.rootIface);
781}
782
Steven Morelandc1635952021-04-01 16:20:47 +0000783TEST_P(BinderRpc, ManySessions) {
Steven Moreland4313d7e2021-07-15 23:41:22 +0000784 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000785
786 std::vector<sp<IBinderRpcSession>> sessions;
787
788 for (size_t i = 0; i < 15; i++) {
789 expectSessions(i, proc.rootIface);
790 sp<IBinderRpcSession> session;
791 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
792 sessions.push_back(session);
793 }
794 expectSessions(sessions.size(), proc.rootIface);
795 for (size_t i = 0; i < sessions.size(); i++) {
796 std::string out;
797 EXPECT_OK(sessions.at(i)->getName(&out));
798 EXPECT_EQ(std::to_string(i), out);
799 }
800 expectSessions(sessions.size(), proc.rootIface);
801
802 while (!sessions.empty()) {
803 sessions.pop_back();
804 expectSessions(sessions.size(), proc.rootIface);
805 }
806 expectSessions(0, proc.rootIface);
807}
808
809size_t epochMillis() {
810 using std::chrono::duration_cast;
811 using std::chrono::milliseconds;
812 using std::chrono::seconds;
813 using std::chrono::system_clock;
814 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
815}
816
Steven Morelandc1635952021-04-01 16:20:47 +0000817TEST_P(BinderRpc, ThreadPoolGreaterThanEqualRequested) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000818 constexpr size_t kNumThreads = 10;
819
Steven Moreland4313d7e2021-07-15 23:41:22 +0000820 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000821
822 EXPECT_OK(proc.rootIface->lock());
823
824 // block all but one thread taking locks
825 std::vector<std::thread> ts;
826 for (size_t i = 0; i < kNumThreads - 1; i++) {
827 ts.push_back(std::thread([&] { proc.rootIface->lockUnlock(); }));
828 }
829
830 usleep(100000); // give chance for calls on other threads
831
832 // other calls still work
833 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
834
835 constexpr size_t blockTimeMs = 500;
836 size_t epochMsBefore = epochMillis();
837 // after this, we should never see a response within this time
838 EXPECT_OK(proc.rootIface->unlockInMsAsync(blockTimeMs));
839
840 // this call should be blocked for blockTimeMs
841 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
842
843 size_t epochMsAfter = epochMillis();
844 EXPECT_GE(epochMsAfter, epochMsBefore + blockTimeMs) << epochMsBefore;
845
846 for (auto& t : ts) t.join();
847}
848
Steven Morelandc1635952021-04-01 16:20:47 +0000849TEST_P(BinderRpc, ThreadPoolOverSaturated) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000850 constexpr size_t kNumThreads = 10;
851 constexpr size_t kNumCalls = kNumThreads + 3;
852 constexpr size_t kSleepMs = 500;
853
Steven Moreland4313d7e2021-07-15 23:41:22 +0000854 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000855
856 size_t epochMsBefore = epochMillis();
857
858 std::vector<std::thread> ts;
859 for (size_t i = 0; i < kNumCalls; i++) {
860 ts.push_back(std::thread([&] { proc.rootIface->sleepMs(kSleepMs); }));
861 }
862
863 for (auto& t : ts) t.join();
864
865 size_t epochMsAfter = epochMillis();
866
867 EXPECT_GE(epochMsAfter, epochMsBefore + 2 * kSleepMs);
868
869 // Potential flake, but make sure calls are handled in parallel.
870 EXPECT_LE(epochMsAfter, epochMsBefore + 3 * kSleepMs);
871}
872
Steven Morelandc1635952021-04-01 16:20:47 +0000873TEST_P(BinderRpc, ThreadingStressTest) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000874 constexpr size_t kNumClientThreads = 10;
875 constexpr size_t kNumServerThreads = 10;
876 constexpr size_t kNumCalls = 100;
877
Steven Moreland4313d7e2021-07-15 23:41:22 +0000878 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000879
880 std::vector<std::thread> threads;
881 for (size_t i = 0; i < kNumClientThreads; i++) {
882 threads.push_back(std::thread([&] {
883 for (size_t j = 0; j < kNumCalls; j++) {
884 sp<IBinder> out;
Steven Morelandc6046982021-04-20 00:49:42 +0000885 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &out));
Steven Moreland5553ac42020-11-11 02:14:45 +0000886 EXPECT_EQ(proc.rootBinder, out);
887 }
888 }));
889 }
890
891 for (auto& t : threads) t.join();
892}
893
Steven Morelandc6046982021-04-20 00:49:42 +0000894TEST_P(BinderRpc, OnewayStressTest) {
895 constexpr size_t kNumClientThreads = 10;
896 constexpr size_t kNumServerThreads = 10;
Steven Moreland52eee942021-06-03 00:59:28 +0000897 constexpr size_t kNumCalls = 500;
Steven Morelandc6046982021-04-20 00:49:42 +0000898
Steven Moreland4313d7e2021-07-15 23:41:22 +0000899 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumServerThreads});
Steven Morelandc6046982021-04-20 00:49:42 +0000900
901 std::vector<std::thread> threads;
902 for (size_t i = 0; i < kNumClientThreads; i++) {
903 threads.push_back(std::thread([&] {
904 for (size_t j = 0; j < kNumCalls; j++) {
905 EXPECT_OK(proc.rootIface->sendString("a"));
906 }
907
908 // check threads are not stuck
909 EXPECT_OK(proc.rootIface->sleepMs(250));
910 }));
911 }
912
913 for (auto& t : threads) t.join();
914}
915
Steven Morelandc1635952021-04-01 16:20:47 +0000916TEST_P(BinderRpc, OnewayCallDoesNotWait) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000917 constexpr size_t kReallyLongTimeMs = 100;
918 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
919
Steven Moreland4313d7e2021-07-15 23:41:22 +0000920 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +0000921
922 size_t epochMsBefore = epochMillis();
923
924 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
925
926 size_t epochMsAfter = epochMillis();
927 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
928}
929
Steven Morelandc1635952021-04-01 16:20:47 +0000930TEST_P(BinderRpc, OnewayCallQueueing) {
Steven Moreland5553ac42020-11-11 02:14:45 +0000931 constexpr size_t kNumSleeps = 10;
932 constexpr size_t kNumExtraServerThreads = 4;
933 constexpr size_t kSleepMs = 50;
934
935 // make sure calls to the same object happen on the same thread
Steven Moreland4313d7e2021-07-15 23:41:22 +0000936 auto proc = createRpcTestSocketServerProcess({.numThreads = 1 + kNumExtraServerThreads});
Steven Moreland5553ac42020-11-11 02:14:45 +0000937
938 EXPECT_OK(proc.rootIface->lock());
939
940 for (size_t i = 0; i < kNumSleeps; i++) {
941 // these should be processed serially
942 proc.rootIface->sleepMsAsync(kSleepMs);
943 }
944 // should also be processesed serially
945 EXPECT_OK(proc.rootIface->unlockInMsAsync(kSleepMs));
946
947 size_t epochMsBefore = epochMillis();
948 EXPECT_OK(proc.rootIface->lockUnlock());
949 size_t epochMsAfter = epochMillis();
950
951 EXPECT_GT(epochMsAfter, epochMsBefore + kSleepMs * kNumSleeps);
Steven Morelandf5174272021-05-25 00:39:28 +0000952
953 // pending oneway transactions hold ref, make sure we read data on all
954 // sockets
955 std::vector<std::thread> threads;
956 for (size_t i = 0; i < 1 + kNumExtraServerThreads; i++) {
957 threads.push_back(std::thread([&] { EXPECT_OK(proc.rootIface->sleepMs(250)); }));
958 }
959 for (auto& t : threads) t.join();
Steven Moreland5553ac42020-11-11 02:14:45 +0000960}
961
Steven Morelandd45be622021-06-04 02:19:37 +0000962TEST_P(BinderRpc, OnewayCallExhaustion) {
963 constexpr size_t kNumClients = 2;
964 constexpr size_t kTooLongMs = 1000;
965
Steven Moreland4313d7e2021-07-15 23:41:22 +0000966 auto proc = createRpcTestSocketServerProcess({.numThreads = kNumClients, .numSessions = 2});
Steven Morelandd45be622021-06-04 02:19:37 +0000967
968 // Build up oneway calls on the second session to make sure it terminates
969 // and shuts down. The first session should be unaffected (proc destructor
970 // checks the first session).
971 auto iface = interface_cast<IBinderRpcTest>(proc.proc.sessions.at(1).root);
972
973 std::vector<std::thread> threads;
974 for (size_t i = 0; i < kNumClients; i++) {
975 // one of these threads will get stuck queueing a transaction once the
976 // socket fills up, the other will be able to fill up transactions on
977 // this object
978 threads.push_back(std::thread([&] {
979 while (iface->sleepMsAsync(kTooLongMs).isOk()) {
980 }
981 }));
982 }
983 for (auto& t : threads) t.join();
984
985 Status status = iface->sleepMsAsync(kTooLongMs);
986 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
987
Steven Moreland798e0d12021-07-14 23:19:25 +0000988 // now that it has died, wait for the remote session to shutdown
989 std::vector<int32_t> remoteCounts;
990 do {
991 EXPECT_OK(proc.rootIface->countBinders(&remoteCounts));
992 } while (remoteCounts.size() == kNumClients);
993
Steven Morelandd45be622021-06-04 02:19:37 +0000994 // the second session should be shutdown in the other process by the time we
995 // are able to join above (it'll only be hung up once it finishes processing
996 // any pending commands). We need to erase this session from the record
997 // here, so that the destructor for our session won't check that this
998 // session is valid, but we still want it to test the other session.
999 proc.proc.sessions.erase(proc.proc.sessions.begin() + 1);
1000}
1001
Steven Moreland659416d2021-05-11 00:47:50 +00001002TEST_P(BinderRpc, Callbacks) {
1003 const static std::string kTestString = "good afternoon!";
1004
Steven Morelandc7d40132021-06-10 03:42:11 +00001005 for (bool callIsOneway : {true, false}) {
1006 for (bool callbackIsOneway : {true, false}) {
1007 for (bool delayed : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001008 auto proc = createRpcTestSocketServerProcess(
1009 {.numThreads = 1, .numSessions = 1, .numIncomingConnections = 1});
Steven Morelandc7d40132021-06-10 03:42:11 +00001010 auto cb = sp<MyBinderRpcCallback>::make();
Steven Moreland659416d2021-05-11 00:47:50 +00001011
Steven Morelandc7d40132021-06-10 03:42:11 +00001012 if (callIsOneway) {
1013 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
1014 kTestString));
1015 } else {
1016 EXPECT_OK(
1017 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
1018 }
Steven Moreland659416d2021-05-11 00:47:50 +00001019
Steven Morelandc7d40132021-06-10 03:42:11 +00001020 using std::literals::chrono_literals::operator""s;
1021 std::unique_lock<std::mutex> _l(cb->mMutex);
1022 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
Steven Moreland659416d2021-05-11 00:47:50 +00001023
Steven Morelandc7d40132021-06-10 03:42:11 +00001024 EXPECT_EQ(cb->mValues.size(), 1)
1025 << "callIsOneway: " << callIsOneway
1026 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
1027 if (cb->mValues.empty()) continue;
1028 EXPECT_EQ(cb->mValues.at(0), kTestString)
1029 << "callIsOneway: " << callIsOneway
1030 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
Steven Moreland659416d2021-05-11 00:47:50 +00001031
Steven Morelandc7d40132021-06-10 03:42:11 +00001032 // since we are severing the connection, we need to go ahead and
1033 // tell the server to shutdown and exit so that waitpid won't hang
Steven Moreland798e0d12021-07-14 23:19:25 +00001034 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
1035 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
1036 }
Steven Moreland659416d2021-05-11 00:47:50 +00001037
Steven Moreland1b304292021-07-15 22:59:34 +00001038 // since this session has an incoming connection w/ a threadpool, we
Steven Morelandc7d40132021-06-10 03:42:11 +00001039 // need to manually shut it down
1040 EXPECT_TRUE(proc.proc.sessions.at(0).session->shutdownAndWait(true));
Steven Moreland659416d2021-05-11 00:47:50 +00001041
Steven Morelandc7d40132021-06-10 03:42:11 +00001042 proc.expectAlreadyShutdown = true;
1043 }
Steven Moreland659416d2021-05-11 00:47:50 +00001044 }
1045 }
1046}
1047
Steven Moreland195edb82021-06-08 02:44:39 +00001048TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001049 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland195edb82021-06-08 02:44:39 +00001050 auto cb = sp<MyBinderRpcCallback>::make();
1051
1052 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
1053 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
1054}
1055
Steven Morelandc1635952021-04-01 16:20:47 +00001056TEST_P(BinderRpc, Die) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001057 for (bool doDeathCleanup : {true, false}) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001058 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland5553ac42020-11-11 02:14:45 +00001059
1060 // make sure there is some state during crash
1061 // 1. we hold their binder
1062 sp<IBinderRpcSession> session;
1063 EXPECT_OK(proc.rootIface->openSession("happy", &session));
1064 // 2. they hold our binder
1065 sp<IBinder> binder = new BBinder();
1066 EXPECT_OK(proc.rootIface->holdBinder(binder));
1067
1068 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->die(doDeathCleanup).transactionError())
1069 << "Do death cleanup: " << doDeathCleanup;
1070
Steven Morelandaf4ca712021-05-24 23:22:08 +00001071 proc.expectAlreadyShutdown = true;
Steven Moreland5553ac42020-11-11 02:14:45 +00001072 }
1073}
1074
Steven Morelandd7302072021-05-15 01:32:04 +00001075TEST_P(BinderRpc, UseKernelBinderCallingId) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001076 auto proc = createRpcTestSocketServerProcess({});
Steven Morelandd7302072021-05-15 01:32:04 +00001077
1078 // we can't allocate IPCThreadState so actually the first time should
1079 // succeed :(
1080 EXPECT_OK(proc.rootIface->useKernelBinderCallingId());
1081
1082 // second time! we catch the error :)
1083 EXPECT_EQ(DEAD_OBJECT, proc.rootIface->useKernelBinderCallingId().transactionError());
1084
Steven Morelandaf4ca712021-05-24 23:22:08 +00001085 proc.expectAlreadyShutdown = true;
Steven Morelandd7302072021-05-15 01:32:04 +00001086}
1087
Steven Moreland37aff182021-03-26 02:04:16 +00001088TEST_P(BinderRpc, WorksWithLibbinderNdkPing) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001089 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001090
1091 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1092 ASSERT_NE(binder, nullptr);
1093
1094 ASSERT_EQ(STATUS_OK, AIBinder_ping(binder.get()));
1095}
1096
1097TEST_P(BinderRpc, WorksWithLibbinderNdkUserTransaction) {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001098 auto proc = createRpcTestSocketServerProcess({});
Steven Moreland37aff182021-03-26 02:04:16 +00001099
1100 ndk::SpAIBinder binder = ndk::SpAIBinder(AIBinder_fromPlatformBinder(proc.rootBinder));
1101 ASSERT_NE(binder, nullptr);
1102
1103 auto ndkBinder = aidl::IBinderRpcTest::fromBinder(binder);
1104 ASSERT_NE(ndkBinder, nullptr);
1105
1106 std::string out;
1107 ndk::ScopedAStatus status = ndkBinder->doubleString("aoeu", &out);
1108 ASSERT_TRUE(status.isOk()) << status.getDescription();
1109 ASSERT_EQ("aoeuaoeu", out);
1110}
1111
Steven Moreland5553ac42020-11-11 02:14:45 +00001112ssize_t countFds() {
1113 DIR* dir = opendir("/proc/self/fd/");
1114 if (dir == nullptr) return -1;
1115 ssize_t ret = 0;
1116 dirent* ent;
1117 while ((ent = readdir(dir)) != nullptr) ret++;
1118 closedir(dir);
1119 return ret;
1120}
1121
Steven Morelandc1635952021-04-01 16:20:47 +00001122TEST_P(BinderRpc, Fds) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001123 ssize_t beforeFds = countFds();
1124 ASSERT_GE(beforeFds, 0);
1125 {
Steven Moreland4313d7e2021-07-15 23:41:22 +00001126 auto proc = createRpcTestSocketServerProcess({.numThreads = 10});
Steven Moreland5553ac42020-11-11 02:14:45 +00001127 ASSERT_EQ(OK, proc.rootBinder->pingBinder());
1128 }
1129 ASSERT_EQ(beforeFds, countFds()) << (system("ls -l /proc/self/fd/"), "fd leak?");
1130}
1131
Steven Morelandda573042021-06-12 01:13:45 +00001132static bool testSupportVsockLoopback() {
1133 unsigned int vsockPort = allocateVsockPort();
1134 sp<RpcServer> server = RpcServer::make();
1135 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1136 CHECK(server->setupVsockServer(vsockPort));
1137 server->start();
1138
1139 sp<RpcSession> session = RpcSession::make();
1140 bool okay = session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort);
Steven Moreland798e0d12021-07-14 23:19:25 +00001141 while (!server->shutdown()) usleep(10000);
Steven Morelandda573042021-06-12 01:13:45 +00001142 ALOGE("Detected vsock loopback supported: %d", okay);
1143 return okay;
1144}
1145
1146static std::vector<SocketType> testSocketTypes() {
1147 std::vector<SocketType> ret = {SocketType::UNIX, SocketType::INET};
1148
1149 static bool hasVsockLoopback = testSupportVsockLoopback();
1150
1151 if (hasVsockLoopback) {
1152 ret.push_back(SocketType::VSOCK);
1153 }
1154
1155 return ret;
1156}
1157
1158INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc, ::testing::ValuesIn(testSocketTypes()),
Steven Morelandf6ec4632021-04-01 16:20:47 +00001159 PrintSocketType);
Steven Morelandc1635952021-04-01 16:20:47 +00001160
Yifan Hong4ffb0c72021-05-07 18:35:14 -07001161class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
1162
1163TEST_P(BinderRpcServerRootObject, WeakRootObject) {
1164 using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
1165 auto setRootObject = [](bool isStrong) -> SetFn {
1166 return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
1167 };
1168
1169 auto server = RpcServer::make();
1170 auto [isStrong1, isStrong2] = GetParam();
1171 auto binder1 = sp<BBinder>::make();
1172 IBinder* binderRaw1 = binder1.get();
1173 setRootObject(isStrong1)(server.get(), binder1);
1174 EXPECT_EQ(binderRaw1, server->getRootObject());
1175 binder1.clear();
1176 EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
1177
1178 auto binder2 = sp<BBinder>::make();
1179 IBinder* binderRaw2 = binder2.get();
1180 setRootObject(isStrong2)(server.get(), binder2);
1181 EXPECT_EQ(binderRaw2, server->getRootObject());
1182 binder2.clear();
1183 EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
1184}
1185
1186INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
1187 ::testing::Combine(::testing::Bool(), ::testing::Bool()));
1188
Yifan Hong1a235852021-05-13 16:07:47 -07001189class OneOffSignal {
1190public:
1191 // If notify() was previously called, or is called within |duration|, return true; else false.
1192 template <typename R, typename P>
1193 bool wait(std::chrono::duration<R, P> duration) {
1194 std::unique_lock<std::mutex> lock(mMutex);
1195 return mCv.wait_for(lock, duration, [this] { return mValue; });
1196 }
1197 void notify() {
1198 std::unique_lock<std::mutex> lock(mMutex);
1199 mValue = true;
1200 lock.unlock();
1201 mCv.notify_all();
1202 }
1203
1204private:
1205 std::mutex mMutex;
1206 std::condition_variable mCv;
1207 bool mValue = false;
1208};
1209
1210TEST(BinderRpc, Shutdown) {
1211 auto addr = allocateSocketAddress();
1212 unlink(addr.c_str());
1213 auto server = RpcServer::make();
1214 server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1215 ASSERT_TRUE(server->setupUnixDomainServer(addr.c_str()));
1216 auto joinEnds = std::make_shared<OneOffSignal>();
1217
1218 // If things are broken and the thread never stops, don't block other tests. Because the thread
1219 // may run after the test finishes, it must not access the stack memory of the test. Hence,
1220 // shared pointers are passed.
1221 std::thread([server, joinEnds] {
1222 server->join();
1223 joinEnds->notify();
1224 }).detach();
1225
1226 bool shutdown = false;
1227 for (int i = 0; i < 10 && !shutdown; i++) {
1228 usleep(300 * 1000); // 300ms; total 3s
1229 if (server->shutdown()) shutdown = true;
1230 }
1231 ASSERT_TRUE(shutdown) << "server->shutdown() never returns true";
1232
1233 ASSERT_TRUE(joinEnds->wait(2s))
1234 << "After server->shutdown() returns true, join() did not stop after 2s";
1235}
1236
Yifan Hong194acf22021-06-29 18:44:56 -07001237TEST(BinderRpc, Java) {
1238#if !defined(__ANDROID__)
1239 GTEST_SKIP() << "This test is only run on Android. Though it can technically run on host on"
1240 "createRpcDelegateServiceManager() with a device attached, such test belongs "
1241 "to binderHostDeviceTest. Hence, just disable this test on host.";
1242#endif // !__ANDROID__
1243 sp<IServiceManager> sm = defaultServiceManager();
1244 ASSERT_NE(nullptr, sm);
1245 // Any Java service with non-empty getInterfaceDescriptor() would do.
1246 // Let's pick batteryproperties.
1247 auto binder = sm->checkService(String16("batteryproperties"));
1248 ASSERT_NE(nullptr, binder);
1249 auto descriptor = binder->getInterfaceDescriptor();
1250 ASSERT_GE(descriptor.size(), 0);
1251 ASSERT_EQ(OK, binder->pingBinder());
1252
1253 auto rpcServer = RpcServer::make();
1254 rpcServer->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
1255 unsigned int port;
1256 ASSERT_TRUE(rpcServer->setupInetServer(0, &port));
1257 auto socket = rpcServer->releaseServer();
1258
1259 auto keepAlive = sp<BBinder>::make();
1260 ASSERT_EQ(OK, binder->setRpcClientDebug(std::move(socket), keepAlive));
1261
1262 auto rpcSession = RpcSession::make();
1263 ASSERT_TRUE(rpcSession->setupInetClient("127.0.0.1", port));
1264 auto rpcBinder = rpcSession->getRootObject();
1265 ASSERT_NE(nullptr, rpcBinder);
1266
1267 ASSERT_EQ(OK, rpcBinder->pingBinder());
1268
1269 ASSERT_EQ(descriptor, rpcBinder->getInterfaceDescriptor())
1270 << "getInterfaceDescriptor should not crash system_server";
1271 ASSERT_EQ(OK, rpcBinder->pingBinder());
1272}
1273
Steven Morelandc1635952021-04-01 16:20:47 +00001274} // namespace android
1275
1276int main(int argc, char** argv) {
Steven Moreland5553ac42020-11-11 02:14:45 +00001277 ::testing::InitGoogleTest(&argc, argv);
1278 android::base::InitLogging(argv, android::base::StderrLogger, android::base::DefaultAborter);
1279 return RUN_ALL_TESTS();
1280}