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