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