blob: 1e8d93d81f21cc13996211e1cbd71580e470f23d [file] [log] [blame]
Andrei Homescu9a9b1b42022-10-14 01:40:59 +00001/*
2 * Copyright (C) 2022 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
17#include <chrono>
18#include <cstdlib>
19#include <type_traits>
20
21#include "binderRpcTestCommon.h"
22#include "binderRpcTestFixture.h"
23
24using namespace std::chrono_literals;
25using namespace std::placeholders;
26using testing::AssertionFailure;
27using testing::AssertionResult;
28using testing::AssertionSuccess;
29
30namespace android {
31
32static_assert(RPC_WIRE_PROTOCOL_VERSION + 1 == RPC_WIRE_PROTOCOL_VERSION_NEXT ||
33 RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL);
34
35TEST(BinderRpcParcel, EntireParcelFormatted) {
36 Parcel p;
37 p.writeInt32(3);
38
39 EXPECT_DEATH_IF_SUPPORTED(p.markForBinder(sp<BBinder>::make()),
40 "format must be set before data is written");
41}
42
43TEST(BinderRpc, CannotUseNextWireVersion) {
44 auto session = RpcSession::make();
45 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT));
46 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 1));
47 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 2));
48 EXPECT_FALSE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_NEXT + 15));
49}
50
51TEST(BinderRpc, CanUseExperimentalWireVersion) {
52 auto session = RpcSession::make();
53 EXPECT_TRUE(session->setProtocolVersion(RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL));
54}
55
56TEST_P(BinderRpc, Ping) {
57 auto proc = createRpcTestSocketServerProcess({});
58 ASSERT_NE(proc.rootBinder, nullptr);
59 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
60}
61
62TEST_P(BinderRpc, GetInterfaceDescriptor) {
63 auto proc = createRpcTestSocketServerProcess({});
64 ASSERT_NE(proc.rootBinder, nullptr);
65 EXPECT_EQ(IBinderRpcTest::descriptor, proc.rootBinder->getInterfaceDescriptor());
66}
67
68TEST_P(BinderRpc, MultipleSessions) {
69 if (serverSingleThreaded()) {
70 // Tests with multiple sessions require a multi-threaded service,
71 // but work fine on a single-threaded client
72 GTEST_SKIP() << "This test requires a multi-threaded service";
73 }
74
75 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 5});
76 for (auto session : proc.proc->sessions) {
77 ASSERT_NE(nullptr, session.root);
78 EXPECT_EQ(OK, session.root->pingBinder());
79 }
80}
81
82TEST_P(BinderRpc, SeparateRootObject) {
83 if (serverSingleThreaded()) {
84 GTEST_SKIP() << "This test requires a multi-threaded service";
85 }
86
87 SocketType type = std::get<0>(GetParam());
88 if (type == SocketType::PRECONNECTED || type == SocketType::UNIX ||
89 type == SocketType::UNIX_BOOTSTRAP) {
90 // we can't get port numbers for unix sockets
91 return;
92 }
93
94 auto proc = createRpcTestSocketServerProcess({.numSessions = 2});
95
96 int port1 = 0;
97 EXPECT_OK(proc.rootIface->getClientPort(&port1));
98
99 sp<IBinderRpcTest> rootIface2 = interface_cast<IBinderRpcTest>(proc.proc->sessions.at(1).root);
100 int port2;
101 EXPECT_OK(rootIface2->getClientPort(&port2));
102
103 // we should have a different IBinderRpcTest object created for each
104 // session, because we use setPerSessionRootObject
105 EXPECT_NE(port1, port2);
106}
107
108TEST_P(BinderRpc, TransactionsMustBeMarkedRpc) {
109 auto proc = createRpcTestSocketServerProcess({});
110 Parcel data;
111 Parcel reply;
112 EXPECT_EQ(BAD_TYPE, proc.rootBinder->transact(IBinder::PING_TRANSACTION, data, &reply, 0));
113}
114
115TEST_P(BinderRpc, AppendSeparateFormats) {
116 auto proc1 = createRpcTestSocketServerProcess({});
117 auto proc2 = createRpcTestSocketServerProcess({});
118
119 Parcel pRaw;
120
121 Parcel p1;
122 p1.markForBinder(proc1.rootBinder);
123 p1.writeInt32(3);
124
125 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&pRaw, 0, pRaw.dataSize()));
126 EXPECT_EQ(BAD_TYPE, pRaw.appendFrom(&p1, 0, p1.dataSize()));
127
128 Parcel p2;
129 p2.markForBinder(proc2.rootBinder);
130 p2.writeInt32(7);
131
132 EXPECT_EQ(BAD_TYPE, p1.appendFrom(&p2, 0, p2.dataSize()));
133 EXPECT_EQ(BAD_TYPE, p2.appendFrom(&p1, 0, p1.dataSize()));
134}
135
136TEST_P(BinderRpc, UnknownTransaction) {
137 auto proc = createRpcTestSocketServerProcess({});
138 Parcel data;
139 data.markForBinder(proc.rootBinder);
140 Parcel reply;
141 EXPECT_EQ(UNKNOWN_TRANSACTION, proc.rootBinder->transact(1337, data, &reply, 0));
142}
143
144TEST_P(BinderRpc, SendSomethingOneway) {
145 auto proc = createRpcTestSocketServerProcess({});
146 EXPECT_OK(proc.rootIface->sendString("asdf"));
147}
148
149TEST_P(BinderRpc, SendAndGetResultBack) {
150 auto proc = createRpcTestSocketServerProcess({});
151 std::string doubled;
152 EXPECT_OK(proc.rootIface->doubleString("cool ", &doubled));
153 EXPECT_EQ("cool cool ", doubled);
154}
155
156TEST_P(BinderRpc, SendAndGetResultBackBig) {
157 auto proc = createRpcTestSocketServerProcess({});
158 std::string single = std::string(1024, 'a');
159 std::string doubled;
160 EXPECT_OK(proc.rootIface->doubleString(single, &doubled));
161 EXPECT_EQ(single + single, doubled);
162}
163
164TEST_P(BinderRpc, InvalidNullBinderReturn) {
165 auto proc = createRpcTestSocketServerProcess({});
166
167 sp<IBinder> outBinder;
168 EXPECT_EQ(proc.rootIface->getNullBinder(&outBinder).transactionError(), UNEXPECTED_NULL);
169}
170
171TEST_P(BinderRpc, CallMeBack) {
172 auto proc = createRpcTestSocketServerProcess({});
173
174 int32_t pingResult;
175 EXPECT_OK(proc.rootIface->pingMe(new MyBinderRpcSession("foo"), &pingResult));
176 EXPECT_EQ(OK, pingResult);
177
178 EXPECT_EQ(0, MyBinderRpcSession::gNum);
179}
180
181TEST_P(BinderRpc, RepeatBinder) {
182 auto proc = createRpcTestSocketServerProcess({});
183
184 sp<IBinder> inBinder = new MyBinderRpcSession("foo");
185 sp<IBinder> outBinder;
186 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
187 EXPECT_EQ(inBinder, outBinder);
188
189 wp<IBinder> weak = inBinder;
190 inBinder = nullptr;
191 outBinder = nullptr;
192
193 // Force reading a reply, to process any pending dec refs from the other
194 // process (the other process will process dec refs there before processing
195 // the ping here).
196 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
197
198 EXPECT_EQ(nullptr, weak.promote());
199
200 EXPECT_EQ(0, MyBinderRpcSession::gNum);
201}
202
203TEST_P(BinderRpc, RepeatTheirBinder) {
204 auto proc = createRpcTestSocketServerProcess({});
205
206 sp<IBinderRpcSession> session;
207 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
208
209 sp<IBinder> inBinder = IInterface::asBinder(session);
210 sp<IBinder> outBinder;
211 EXPECT_OK(proc.rootIface->repeatBinder(inBinder, &outBinder));
212 EXPECT_EQ(inBinder, outBinder);
213
214 wp<IBinder> weak = inBinder;
215 session = nullptr;
216 inBinder = nullptr;
217 outBinder = nullptr;
218
219 // Force reading a reply, to process any pending dec refs from the other
220 // process (the other process will process dec refs there before processing
221 // the ping here).
222 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
223
224 EXPECT_EQ(nullptr, weak.promote());
225}
226
227TEST_P(BinderRpc, RepeatBinderNull) {
228 auto proc = createRpcTestSocketServerProcess({});
229
230 sp<IBinder> outBinder;
231 EXPECT_OK(proc.rootIface->repeatBinder(nullptr, &outBinder));
232 EXPECT_EQ(nullptr, outBinder);
233}
234
235TEST_P(BinderRpc, HoldBinder) {
236 auto proc = createRpcTestSocketServerProcess({});
237
238 IBinder* ptr = nullptr;
239 {
240 sp<IBinder> binder = new BBinder();
241 ptr = binder.get();
242 EXPECT_OK(proc.rootIface->holdBinder(binder));
243 }
244
245 sp<IBinder> held;
246 EXPECT_OK(proc.rootIface->getHeldBinder(&held));
247
248 EXPECT_EQ(held.get(), ptr);
249
250 // stop holding binder, because we test to make sure references are cleaned
251 // up
252 EXPECT_OK(proc.rootIface->holdBinder(nullptr));
253 // and flush ref counts
254 EXPECT_EQ(OK, proc.rootBinder->pingBinder());
255}
256
257// START TESTS FOR LIMITATIONS OF SOCKET BINDER
258// These are behavioral differences form regular binder, where certain usecases
259// aren't supported.
260
261TEST_P(BinderRpc, CannotMixBindersBetweenUnrelatedSocketSessions) {
262 auto proc1 = createRpcTestSocketServerProcess({});
263 auto proc2 = createRpcTestSocketServerProcess({});
264
265 sp<IBinder> outBinder;
266 EXPECT_EQ(INVALID_OPERATION,
267 proc1.rootIface->repeatBinder(proc2.rootBinder, &outBinder).transactionError());
268}
269
270TEST_P(BinderRpc, CannotMixBindersBetweenTwoSessionsToTheSameServer) {
271 if (serverSingleThreaded()) {
272 GTEST_SKIP() << "This test requires a multi-threaded service";
273 }
274
275 auto proc = createRpcTestSocketServerProcess({.numThreads = 1, .numSessions = 2});
276
277 sp<IBinder> outBinder;
278 EXPECT_EQ(INVALID_OPERATION,
279 proc.rootIface->repeatBinder(proc.proc->sessions.at(1).root, &outBinder)
280 .transactionError());
281}
282
283TEST_P(BinderRpc, CannotSendRegularBinderOverSocketBinder) {
284 if (!kEnableKernelIpc || noKernel()) {
285 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
286 "at build time.";
287 }
288
289 auto proc = createRpcTestSocketServerProcess({});
290
291 sp<IBinder> someRealBinder = IInterface::asBinder(defaultServiceManager());
292 sp<IBinder> outBinder;
293 EXPECT_EQ(INVALID_OPERATION,
294 proc.rootIface->repeatBinder(someRealBinder, &outBinder).transactionError());
295}
296
297TEST_P(BinderRpc, CannotSendSocketBinderOverRegularBinder) {
298 if (!kEnableKernelIpc || noKernel()) {
299 GTEST_SKIP() << "Test disabled because Binder kernel driver was disabled "
300 "at build time.";
301 }
302
303 auto proc = createRpcTestSocketServerProcess({});
304
305 // for historical reasons, IServiceManager interface only returns the
306 // exception code
307 EXPECT_EQ(binder::Status::EX_TRANSACTION_FAILED,
308 defaultServiceManager()->addService(String16("not_suspicious"), proc.rootBinder));
309}
310
311// END TESTS FOR LIMITATIONS OF SOCKET BINDER
312
313TEST_P(BinderRpc, RepeatRootObject) {
314 auto proc = createRpcTestSocketServerProcess({});
315
316 sp<IBinder> outBinder;
317 EXPECT_OK(proc.rootIface->repeatBinder(proc.rootBinder, &outBinder));
318 EXPECT_EQ(proc.rootBinder, outBinder);
319}
320
321TEST_P(BinderRpc, NestedTransactions) {
322 auto proc = createRpcTestSocketServerProcess({
323 // Enable FD support because it uses more stack space and so represents
324 // something closer to a worst case scenario.
325 .clientFileDescriptorTransportMode = RpcSession::FileDescriptorTransportMode::UNIX,
326 .serverSupportedFileDescriptorTransportModes =
327 {RpcSession::FileDescriptorTransportMode::UNIX},
328 });
329
330 auto nastyNester = sp<MyBinderRpcTest>::make();
331 EXPECT_OK(proc.rootIface->nestMe(nastyNester, 10));
332
333 wp<IBinder> weak = nastyNester;
334 nastyNester = nullptr;
335 EXPECT_EQ(nullptr, weak.promote());
336}
337
338TEST_P(BinderRpc, SameBinderEquality) {
339 auto proc = createRpcTestSocketServerProcess({});
340
341 sp<IBinder> a;
342 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
343
344 sp<IBinder> b;
345 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
346
347 EXPECT_EQ(a, b);
348}
349
350TEST_P(BinderRpc, SameBinderEqualityWeak) {
351 auto proc = createRpcTestSocketServerProcess({});
352
353 sp<IBinder> a;
354 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&a));
355 wp<IBinder> weak = a;
356 a = nullptr;
357
358 sp<IBinder> b;
359 EXPECT_OK(proc.rootIface->alwaysGiveMeTheSameBinder(&b));
360
361 // this is the wrong behavior, since BpBinder
362 // doesn't implement onIncStrongAttempted
363 // but make sure there is no crash
364 EXPECT_EQ(nullptr, weak.promote());
365
366 GTEST_SKIP() << "Weak binders aren't currently re-promotable for RPC binder.";
367
368 // In order to fix this:
369 // - need to have incStrongAttempted reflected across IPC boundary (wait for
370 // response to promote - round trip...)
371 // - sendOnLastWeakRef, to delete entries out of RpcState table
372 EXPECT_EQ(b, weak.promote());
373}
374
375#define expectSessions(expected, iface) \
376 do { \
377 int session; \
378 EXPECT_OK((iface)->getNumOpenSessions(&session)); \
379 EXPECT_EQ(expected, session); \
380 } while (false)
381
382TEST_P(BinderRpc, SingleSession) {
383 auto proc = createRpcTestSocketServerProcess({});
384
385 sp<IBinderRpcSession> session;
386 EXPECT_OK(proc.rootIface->openSession("aoeu", &session));
387 std::string out;
388 EXPECT_OK(session->getName(&out));
389 EXPECT_EQ("aoeu", out);
390
391 expectSessions(1, proc.rootIface);
392 session = nullptr;
393 expectSessions(0, proc.rootIface);
394}
395
396TEST_P(BinderRpc, ManySessions) {
397 auto proc = createRpcTestSocketServerProcess({});
398
399 std::vector<sp<IBinderRpcSession>> sessions;
400
401 for (size_t i = 0; i < 15; i++) {
402 expectSessions(i, proc.rootIface);
403 sp<IBinderRpcSession> session;
404 EXPECT_OK(proc.rootIface->openSession(std::to_string(i), &session));
405 sessions.push_back(session);
406 }
407 expectSessions(sessions.size(), proc.rootIface);
408 for (size_t i = 0; i < sessions.size(); i++) {
409 std::string out;
410 EXPECT_OK(sessions.at(i)->getName(&out));
411 EXPECT_EQ(std::to_string(i), out);
412 }
413 expectSessions(sessions.size(), proc.rootIface);
414
415 while (!sessions.empty()) {
416 sessions.pop_back();
417 expectSessions(sessions.size(), proc.rootIface);
418 }
419 expectSessions(0, proc.rootIface);
420}
421
422TEST_P(BinderRpc, OnewayCallDoesNotWait) {
423 constexpr size_t kReallyLongTimeMs = 100;
424 constexpr size_t kSleepMs = kReallyLongTimeMs * 5;
425
426 auto proc = createRpcTestSocketServerProcess({});
427
428 size_t epochMsBefore = epochMillis();
429
430 EXPECT_OK(proc.rootIface->sleepMsAsync(kSleepMs));
431
432 size_t epochMsAfter = epochMillis();
433 EXPECT_LT(epochMsAfter, epochMsBefore + kReallyLongTimeMs);
434}
435
436TEST_P(BinderRpc, Callbacks) {
437 const static std::string kTestString = "good afternoon!";
438
439 for (bool callIsOneway : {true, false}) {
440 for (bool callbackIsOneway : {true, false}) {
441 for (bool delayed : {true, false}) {
442 if (clientOrServerSingleThreaded() &&
443 (callIsOneway || callbackIsOneway || delayed)) {
444 // we have no incoming connections to receive the callback
445 continue;
446 }
447
448 size_t numIncomingConnections = clientOrServerSingleThreaded() ? 0 : 1;
449 auto proc = createRpcTestSocketServerProcess(
450 {.numThreads = 1,
451 .numSessions = 1,
452 .numIncomingConnections = numIncomingConnections});
453 auto cb = sp<MyBinderRpcCallback>::make();
454
455 if (callIsOneway) {
456 EXPECT_OK(proc.rootIface->doCallbackAsync(cb, callbackIsOneway, delayed,
457 kTestString));
458 } else {
459 EXPECT_OK(
460 proc.rootIface->doCallback(cb, callbackIsOneway, delayed, kTestString));
461 }
462
463 // if both transactions are synchronous and the response is sent back on the
464 // same thread, everything should have happened in a nested call. Otherwise,
465 // the callback will be processed on another thread.
466 if (callIsOneway || callbackIsOneway || delayed) {
467 using std::literals::chrono_literals::operator""s;
468 RpcMutexUniqueLock _l(cb->mMutex);
469 cb->mCv.wait_for(_l, 1s, [&] { return !cb->mValues.empty(); });
470 }
471
472 EXPECT_EQ(cb->mValues.size(), 1)
473 << "callIsOneway: " << callIsOneway
474 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
475 if (cb->mValues.empty()) continue;
476 EXPECT_EQ(cb->mValues.at(0), kTestString)
477 << "callIsOneway: " << callIsOneway
478 << " callbackIsOneway: " << callbackIsOneway << " delayed: " << delayed;
479
480 // since we are severing the connection, we need to go ahead and
481 // tell the server to shutdown and exit so that waitpid won't hang
482 if (auto status = proc.rootIface->scheduleShutdown(); !status.isOk()) {
483 EXPECT_EQ(DEAD_OBJECT, status.transactionError()) << status;
484 }
485
486 // since this session has an incoming connection w/ a threadpool, we
487 // need to manually shut it down
488 EXPECT_TRUE(proc.proc->sessions.at(0).session->shutdownAndWait(true));
489 proc.expectAlreadyShutdown = true;
490 }
491 }
492 }
493}
494
495TEST_P(BinderRpc, OnewayCallbackWithNoThread) {
496 auto proc = createRpcTestSocketServerProcess({});
497 auto cb = sp<MyBinderRpcCallback>::make();
498
499 Status status = proc.rootIface->doCallback(cb, true /*oneway*/, false /*delayed*/, "anything");
500 EXPECT_EQ(WOULD_BLOCK, status.transactionError());
501}
502
503TEST_P(BinderRpc, AidlDelegatorTest) {
504 auto proc = createRpcTestSocketServerProcess({});
505 auto myDelegator = sp<IBinderRpcTestDelegator>::make(proc.rootIface);
506 ASSERT_NE(nullptr, myDelegator);
507
508 std::string doubled;
509 EXPECT_OK(myDelegator->doubleString("cool ", &doubled));
510 EXPECT_EQ("cool cool ", doubled);
511}
512
513} // namespace android