• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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 //#define LOG_NDEBUG 0
18 #define LOG_TAG "hidl_test_java_native"
19 
20 #include <android-base/file.h>
21 #include <android-base/logging.h>
22 
23 #include <android/hardware/tests/baz/1.0/IBaz.h>
24 #include <android/hardware/tests/memory/2.0/IMemoryInterface.h>
25 #include <android/hardware/tests/memory/2.0/types.h>
26 #include <android/hardware/tests/safeunion/1.0/IOtherInterface.h>
27 #include <android/hardware/tests/safeunion/1.0/ISafeUnion.h>
28 #include <android/hidl/allocator/1.0/IAllocator.h>
29 
30 #include <hidlmemory/mapping.h>
31 #include <hidl/LegacySupport.h>
32 #include <hidl/ServiceManagement.h>
33 #include <gtest/gtest.h>
34 
35 #include <hidl/HidlTransportSupport.h>
36 #include <hidl/Status.h>
37 
38 #include <numeric>
39 #include <sys/stat.h>
40 
41 using ::android::sp;
42 using ::android::hardware::tests::baz::V1_0::IBase;
43 using ::android::hardware::tests::baz::V1_0::IBaz;
44 using ::android::hardware::tests::baz::V1_0::IBazCallback;
45 using ::android::hardware::tests::memory::V2_0::IMemoryInterface;
46 using ::android::hardware::tests::memory::V2_0::TwoMemory;
47 using ::android::hardware::tests::safeunion::V1_0::IOtherInterface;
48 using ::android::hardware::tests::safeunion::V1_0::ISafeUnion;
49 
50 using ::android::hardware::hidl_array;
51 using ::android::hardware::hidl_vec;
52 using ::android::hardware::hidl_memory;
53 using ::android::hardware::hidl_handle;
54 using ::android::hardware::hidl_string;
55 using ::android::hardware::defaultPassthroughServiceImplementation;
56 using ::android::hardware::Return;
57 using ::android::hardware::Status;
58 using ::android::hardware::Void;
59 
60 using ::android::hidl::allocator::V1_0::IAllocator;
61 using ::android::hidl::memory::V1_0::IMemory;
62 
63 using HandleTypeSafeUnion = ISafeUnion::HandleTypeSafeUnion;
64 using InterfaceTypeSafeUnion = ISafeUnion::InterfaceTypeSafeUnion;
65 using LargeSafeUnion = ISafeUnion::LargeSafeUnion;
66 using SmallSafeUnion = ISafeUnion::SmallSafeUnion;
67 
68 struct BazCallback : public IBazCallback {
69     Return<void> heyItsMe(const sp<IBazCallback> &cb) override;
70     Return<void> hey() override;
71 };
72 
heyItsMe(const sp<IBazCallback> & cb)73 Return<void> BazCallback::heyItsMe(
74         const sp<IBazCallback> &cb) {
75     LOG(INFO) << "SERVER: heyItsMe cb = " << cb.get();
76 
77     return Void();
78 }
79 
hey()80 Return<void> BazCallback::hey() {
81     LOG(INFO) << "SERVER: hey";
82 
83     return Void();
84 }
85 
86 struct OtherInterface : public IOtherInterface {
concatTwoStringsOtherInterface87     Return<void> concatTwoStrings(const hidl_string& a, const hidl_string& b,
88                                   concatTwoStrings_cb _hidl_cb) override {
89         hidl_string result = std::string(a) + std::string(b);
90         _hidl_cb(result);
91 
92         return Void();
93     }
94 };
95 
96 struct MemoryInterface : public IMemoryInterface {
MemoryInterfaceMemoryInterface97     MemoryInterface() {
98         sp<IAllocator> ashmem = IAllocator::getService("ashmem");
99         LOG_FATAL_IF(ashmem == nullptr);
100         ashmem->allocate(8, [&](bool success, const hidl_memory& m) {
101             LOG_FATAL_IF(!success);
102             (void) success;
103             mMemory = m;
104         });
105         sp<IMemory> memory = mapMemory(mMemory);
106 
107         LOG_FATAL_IF(memory == nullptr);
108         uint8_t* data =
109             static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
110         for (size_t i = 0; i < 8; ++i) {
111             data[i] = i;
112         }
113         memory->commit();
114     }
115 
bitwiseNotMemoryInterface116     Return<void> bitwiseNot(const hidl_memory& mem) override {
117         sp<IMemory> memory = mapMemory(mem);
118         if (memory == nullptr) {
119             return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
120                                              "Could not map hidl_memory");
121         }
122         uint8_t* data =
123             static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
124 
125         memory->update();
126         for (size_t i = 0; i < memory->getSize(); i++) {
127             data[i] = ~data[i];
128         }
129         memory->commit();
130 
131         return Void();
132     }
133 
getTestMemMemoryInterface134     Return<void> getTestMem(getTestMem_cb _hidl_cb) override {
135         _hidl_cb(mMemory);
136         return Status::ok();
137     }
138 
getSumDiffMemoryInterface139     Return<void> getSumDiff(const TwoMemory& in, getSumDiff_cb _hidl_cb) override {
140         if (in.mem1.size() != in.mem2.size()) {
141             return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
142                                              "Buffers must be the same size.");
143         }
144         const size_t size = in.mem1.size();
145 
146         // Map first input.
147         sp<IMemory> memory_in1 = mapMemory(in.mem1);
148         if (memory_in1 == nullptr) {
149             return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
150                                              "Could not map hidl_memory");
151         }
152         uint8_t* data_in1 =
153             static_cast<uint8_t*>(static_cast<void*>(memory_in1->getPointer()));
154         memory_in1->update();
155 
156         // Map second input.
157         sp<IMemory> memory_in2 = mapMemory(in.mem2);
158         if (memory_in2 == nullptr) {
159             return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
160                                              "Could not map hidl_memory");
161         }
162         uint8_t* data_in2 =
163             static_cast<uint8_t*>(static_cast<void*>(memory_in2->getPointer()));
164         memory_in2->update();
165 
166         TwoMemory out;
167         sp<IAllocator> ashmem = IAllocator::getService("ashmem");
168         LOG_FATAL_IF(ashmem == nullptr);
169 
170         // Map first output.
171         ashmem->allocate(size, [&](bool success, const hidl_memory& m) {
172             LOG_FATAL_IF(!success);
173             (void) success;
174             out.mem1 = m;
175         });
176         sp<IMemory> memory_out1 = mapMemory(out.mem1);
177         LOG_FATAL_IF(memory_out1 == nullptr);
178         uint8_t* data_out1 =
179             static_cast<uint8_t*>(static_cast<void*>(memory_out1->getPointer()));
180 
181         // Map second output.
182         ashmem->allocate(size, [&](bool success, const hidl_memory& m) {
183             LOG_FATAL_IF(!success);
184             (void) success;
185             out.mem2 = m;
186         });
187         sp<IMemory> memory_out2 = mapMemory(out.mem2);
188         LOG_FATAL_IF(memory_out2 == nullptr);
189         uint8_t* data_out2 =
190             static_cast<uint8_t*>(static_cast<void*>(memory_out2->getPointer()));
191 
192         for (size_t i = 0; i < size; ++i) {
193             data_out1[i] = data_in1[i] + data_in2[i];
194             data_out2[i] = data_in1[i] - data_in2[i];
195         }
196 
197         memory_out1->commit();
198         memory_out2->commit();
199 
200         _hidl_cb(out);
201         return Status::ok();
202     }
203 
204  private:
205     hidl_memory mMemory;
206 };
207 
208 using std::to_string;
209 
usage(const char * me)210 static void usage(const char *me) {
211     fprintf(stderr, "%s [-c]lient | [-s]erver\n", me);
212 }
213 
214 struct HidlEnvironment : public ::testing::Environment {
SetUpHidlEnvironment215     void SetUp() override {
216     }
217 
TearDownHidlEnvironment218     void TearDown() override {
219     }
220 };
221 
222 struct HidlTest : public ::testing::Test {
223     sp<IBaz> baz;
224     sp<ISafeUnion> safeunionInterface;
225     sp<IOtherInterface> otherInterface;
226 
SetUpHidlTest227     void SetUp() override {
228         using namespace ::android::hardware;
229 
230         ::android::hardware::details::waitForHwService(IBaz::descriptor, "default");
231         baz = IBaz::getService();
232         CHECK(baz != nullptr);
233         CHECK(baz->isRemote());
234 
235         ::android::hardware::details::waitForHwService(ISafeUnion::descriptor, "default");
236         safeunionInterface = ISafeUnion::getService();
237         CHECK(safeunionInterface != nullptr);
238         CHECK(safeunionInterface->isRemote());
239 
240         ::android::hardware::details::waitForHwService(IOtherInterface::descriptor, "default");
241         otherInterface = IOtherInterface::getService();
242         CHECK(otherInterface != nullptr);
243         CHECK(otherInterface->isRemote());
244     }
245 
TearDownHidlTest246     void TearDown() override {
247     }
248 };
249 
250 template <typename T>
EXPECT_OK(const::android::hardware::Return<T> & ret)251 static void EXPECT_OK(const ::android::hardware::Return<T> &ret) {
252     EXPECT_TRUE(ret.isOk());
253 }
254 
255 template<typename T, typename S>
isArrayEqual(const T arr1,const S arr2,size_t size)256 static inline bool isArrayEqual(const T arr1, const S arr2, size_t size) {
257     for(size_t i = 0; i < size; i++)
258         if(arr1[i] != arr2[i])
259             return false;
260     return true;
261 }
262 
TEST_F(HidlTest,GetDescriptorTest)263 TEST_F(HidlTest, GetDescriptorTest) {
264     EXPECT_OK(baz->interfaceDescriptor([&] (const auto &desc) {
265         EXPECT_EQ(desc, IBaz::descriptor);
266     }));
267 }
268 
TEST_F(HidlTest,BazSomeBaseMethodTest)269 TEST_F(HidlTest, BazSomeBaseMethodTest) {
270     EXPECT_OK(baz->someBaseMethod());
271 }
272 
TEST_F(HidlTest,BazSomeOtherBaseMethodTest)273 TEST_F(HidlTest, BazSomeOtherBaseMethodTest) {
274     IBase::Foo foo;
275     foo.x = 1;
276     foo.y.z = 2.5;
277     // A valid UTF-8 string
278     foo.y.s = "Hello, world, \x46\x6F\x6F\x20\xC2\xA9\x20\x62\x61\x72\x20\xF0\x9D\x8C\x86\x20\x54\x72\x65\x62\x6C\x65\x20\xE2\x98\x83\x20\x72\x6F\x63\x6B\x73";
279 
280     foo.aaa.resize(5);
281     for (size_t i = 0; i < foo.aaa.size(); ++i) {
282         foo.aaa[i].z = 1.0f + (float)i * 0.01f;
283         foo.aaa[i].s = ("Hello, world " + std::to_string(i)).c_str();
284     }
285 
286     EXPECT_OK(
287             baz->someOtherBaseMethod(
288                 foo,
289                 [&](const auto &result) {
290                     // Strings should have the same size as they did before
291                     // marshaling. b/35038064
292                     EXPECT_EQ(result.y.s.size(), foo.y.s.size());
293                     EXPECT_EQ(foo, result);
294                }));
295 }
296 
TEST_F(HidlTest,SomeOtherBaseMethodInvalidString)297 TEST_F(HidlTest, SomeOtherBaseMethodInvalidString) {
298     IBase::Foo foo {
299         .y = {
300             .s = "\xff",
301         }
302     };
303 
304     auto ret = baz->someOtherBaseMethod(foo, [](const IBase::Foo& ret) {
305         EXPECT_EQ(ret.y.s, "?");  // :)
306     });
307 
308     EXPECT_TRUE(ret.isOk());
309 }
310 
TEST_F(HidlTest,BazSomeMethodWithFooArraysTest)311 TEST_F(HidlTest, BazSomeMethodWithFooArraysTest) {
312     hidl_array<IBase::Foo, 2> foo;
313 
314     foo[0].x = 1;
315     foo[0].y.z = 2.5;
316     foo[0].y.s = "Hello, world";
317 
318     foo[0].aaa.resize(5);
319     for (size_t i = 0; i < foo[0].aaa.size(); ++i) {
320         foo[0].aaa[i].z = 1.0f + (float)i * 0.01f;
321         foo[0].aaa[i].s = ("Hello, world " + std::to_string(i)).c_str();
322     }
323 
324     foo[1].x = 2;
325     foo[1].y.z = -2.5;
326     foo[1].y.s = "Morituri te salutant";
327 
328     foo[1].aaa.resize(3);
329     for (size_t i = 0; i < foo[1].aaa.size(); ++i) {
330         foo[1].aaa[i].z = 2.0f - (float)i * 0.01f;
331         foo[1].aaa[i].s = ("Alea iacta est: " + std::to_string(i)).c_str();
332     }
333 
334     hidl_array<IBaz::Foo, 2> fooExpectedOutput;
335     fooExpectedOutput[0] = foo[1];
336     fooExpectedOutput[1] = foo[0];
337 
338     EXPECT_OK(
339             baz->someMethodWithFooArrays(
340                 foo,
341                 [&](const auto &result) {
342                     EXPECT_EQ(result, fooExpectedOutput);
343                }));
344 }
345 
TEST_F(HidlTest,BazSomeMethodWithFooVectorsTest)346 TEST_F(HidlTest, BazSomeMethodWithFooVectorsTest) {
347     hidl_vec<IBase::Foo> foo;
348     foo.resize(2);
349 
350     foo[0].x = 1;
351     foo[0].y.z = 2.5;
352     foo[0].y.s = "Hello, world";
353 
354     foo[0].aaa.resize(5);
355     for (size_t i = 0; i < foo[0].aaa.size(); ++i) {
356         foo[0].aaa[i].z = 1.0f + (float)i * 0.01f;
357         foo[0].aaa[i].s = ("Hello, world " + std::to_string(i)).c_str();
358     }
359 
360     foo[1].x = 2;
361     foo[1].y.z = -2.5;
362     foo[1].y.s = "Morituri te salutant";
363 
364     foo[1].aaa.resize(3);
365     for (size_t i = 0; i < foo[1].aaa.size(); ++i) {
366         foo[1].aaa[i].z = 2.0f - (float)i * 0.01f;
367         foo[1].aaa[i].s = ("Alea iacta est: " + std::to_string(i)).c_str();
368     }
369 
370     hidl_vec<IBaz::Foo> fooExpectedOutput;
371     fooExpectedOutput.resize(2);
372     fooExpectedOutput[0] = foo[1];
373     fooExpectedOutput[1] = foo[0];
374 
375     EXPECT_OK(
376             baz->someMethodWithFooVectors(
377                 foo,
378                 [&](const auto &result) {
379                     EXPECT_EQ(result, fooExpectedOutput);
380                 }));
381 }
382 
TEST_F(HidlTest,BazSomeMethodWithVectorOfArray)383 TEST_F(HidlTest, BazSomeMethodWithVectorOfArray) {
384     IBase::VectorOfArray in, expectedOut;
385     in.addresses.resize(3);
386     expectedOut.addresses.resize(3);
387 
388     size_t k = 0;
389     const size_t n = in.addresses.size();
390 
391     for (size_t i = 0; i < n; ++i) {
392         for (size_t j = 0; j < 6; ++j, ++k) {
393             in.addresses[i][j] = k;
394             expectedOut.addresses[n - 1 - i][j] = k;
395         }
396     }
397 
398     EXPECT_OK(
399             baz->someMethodWithVectorOfArray(
400                 in,
401                 [&](const auto &out) {
402                     EXPECT_EQ(expectedOut, out);
403                 }));
404 }
405 
TEST_F(HidlTest,BazSomeMethodTakingAVectorOfArray)406 TEST_F(HidlTest, BazSomeMethodTakingAVectorOfArray) {
407     hidl_vec<hidl_array<uint8_t, 6> > in, expectedOut;
408     in.resize(3);
409     expectedOut.resize(3);
410 
411     size_t k = 0;
412     const size_t n = in.size();
413     for (size_t i = 0; i < n; ++i) {
414         for (size_t j = 0; j < 6; ++j, ++k) {
415             in[i][j] = k;
416             expectedOut[n - 1 - i][j] = k;
417         }
418     }
419 
420     EXPECT_OK(
421             baz->someMethodTakingAVectorOfArray(
422                 in,
423                 [&](const auto &out) {
424                     EXPECT_EQ(expectedOut, out);
425                 }));
426 }
427 
numberToEnglish(int x)428 static std::string numberToEnglish(int x) {
429     static const char *const kDigits[] = {
430         "zero",
431         "one",
432         "two",
433         "three",
434         "four",
435         "five",
436         "six",
437         "seven",
438         "eight",
439         "nine",
440     };
441 
442     if (x < 0) {
443         return "negative " + numberToEnglish(-x);
444     }
445 
446     if (x < 10) {
447         return kDigits[x];
448     }
449 
450     if (x <= 15) {
451         static const char *const kSpecialTens[] = {
452             "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
453         };
454 
455         return kSpecialTens[x - 10];
456     }
457 
458     if (x < 20) {
459         return std::string(kDigits[x % 10]) + "teen";
460     }
461 
462     if (x < 100) {
463         static const char *const kDecades[] = {
464             "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
465             "eighty", "ninety",
466         };
467 
468         return std::string(kDecades[x / 10 - 2]) + kDigits[x % 10];
469     }
470 
471     return "positively huge!";
472 }
473 
TEST_F(HidlTest,BazTransposeTest)474 TEST_F(HidlTest, BazTransposeTest) {
475     IBase::StringMatrix5x3 in;
476     IBase::StringMatrix3x5 expectedOut;
477 
478     for (int i = 0; i < 5; ++i) {
479         for (int j = 0; j < 3; ++j) {
480             in.s[i][j] = expectedOut.s[j][i] = numberToEnglish(3 * i + j + 1).c_str();
481         }
482     }
483 
484     EXPECT_OK(baz->transpose(
485                 in,
486                 [&](const auto &out) {
487                     EXPECT_EQ(expectedOut, out);
488                 }));
489 }
490 
TEST_F(HidlTest,BazTranspose2Test)491 TEST_F(HidlTest, BazTranspose2Test) {
492     hidl_array<hidl_string, 5, 3> in;
493     hidl_array<hidl_string, 3, 5> expectedOut;
494 
495     for (int i = 0; i < 5; ++i) {
496         for (int j = 0; j < 3; ++j) {
497             in[i][j] = expectedOut[j][i] = numberToEnglish(3 * i + j + 1).c_str();
498         }
499     }
500 
501     EXPECT_OK(baz->transpose2(
502                 in,
503                 [&](const auto &out) {
504                     EXPECT_EQ(expectedOut, out);
505                 }));
506 }
507 
TEST_F(HidlTest,BazSomeBoolMethodTest)508 TEST_F(HidlTest, BazSomeBoolMethodTest) {
509     auto result = baz->someBoolMethod(true);
510     EXPECT_OK(result);
511     EXPECT_EQ(result, false);
512 }
513 
TEST_F(HidlTest,BazSomeBoolArrayMethodTest)514 TEST_F(HidlTest, BazSomeBoolArrayMethodTest) {
515     hidl_array<bool, 3> someBoolArray;
516     someBoolArray[0] = true;
517     someBoolArray[1] = false;
518     someBoolArray[2] = true;
519 
520     hidl_array<bool, 4> expectedOut;
521     expectedOut[0] = false;
522     expectedOut[1] = true;
523     expectedOut[2] = false;
524     expectedOut[3] = true;
525 
526     EXPECT_OK(
527             baz->someBoolArrayMethod(
528                 someBoolArray,
529                 [&](const auto &result) {
530                     EXPECT_EQ(expectedOut, result);
531                 }));
532 }
533 
TEST_F(HidlTest,BazSomeBoolVectorMethodTest)534 TEST_F(HidlTest, BazSomeBoolVectorMethodTest) {
535     hidl_vec<bool> someBoolVector, expected;
536     someBoolVector.resize(4);
537     expected.resize(4);
538 
539     for (size_t i = 0; i < someBoolVector.size(); ++i) {
540         someBoolVector[i] = ((i & 1) == 0);
541         expected[i] = !someBoolVector[i];
542     }
543 
544     EXPECT_OK(
545             baz->someBoolVectorMethod(
546                 someBoolVector,
547                 [&](const auto &result) {
548                     EXPECT_EQ(expected, result);
549                 }));
550 }
551 
TEST_F(HidlTest,BazDoThisMethodTest)552 TEST_F(HidlTest, BazDoThisMethodTest) {
553     EXPECT_OK(baz->doThis(1.0f));
554 }
555 
TEST_F(HidlTest,BazDoThatAndReturnSomethingMethodTest)556 TEST_F(HidlTest, BazDoThatAndReturnSomethingMethodTest) {
557     auto result = baz->doThatAndReturnSomething(1);
558     EXPECT_OK(result);
559     EXPECT_EQ(result, 666);
560 }
561 
TEST_F(HidlTest,BazDoQuiteABitMethodTest)562 TEST_F(HidlTest, BazDoQuiteABitMethodTest) {
563     auto result = baz->doQuiteABit(1, 2LL, 3.0f, 4.0);
564 
565     EXPECT_OK(result);
566     EXPECT_EQ(result, 666.5);
567 }
568 
TEST_F(HidlTest,BazDoSomethingElseMethodTest)569 TEST_F(HidlTest, BazDoSomethingElseMethodTest) {
570     hidl_array<int32_t, 15> param;
571     hidl_array<int32_t, 32> expected;
572 
573     for (size_t i = 0; i < 15; ++i) {
574         param[i] = expected[15 + i] = i;
575         expected[i] = 2 * i;
576     }
577 
578     expected[30] = 1;
579     expected[31] = 2;
580 
581     EXPECT_OK(
582             baz->doSomethingElse(
583                 param,
584                 [&](const auto &result) {
585                     EXPECT_EQ(expected, result);
586                 }));
587 }
588 
TEST_F(HidlTest,BazDoStuffAndReturnAStringMethodTest)589 TEST_F(HidlTest, BazDoStuffAndReturnAStringMethodTest) {
590     std::string expected = "Hello, world!";
591     EXPECT_OK(
592             baz->doStuffAndReturnAString(
593                 [&](const auto &result) {
594                     EXPECT_EQ(expected, result);
595                 }));
596 }
597 
TEST_F(HidlTest,BazMapThisVectorMethodTest)598 TEST_F(HidlTest, BazMapThisVectorMethodTest) {
599     hidl_vec<int32_t> vec_param, expected;
600     vec_param.resize(15);
601     expected.resize(15);
602 
603     for (size_t i = 0; i < 15; ++i) {
604         vec_param[i] = i;
605         expected[i] = 2 * i;
606     }
607 
608     EXPECT_OK(
609             baz->mapThisVector(
610                 vec_param,
611                 [&](const auto &result) {
612                     EXPECT_EQ(expected, result);
613                 }));
614 }
615 
TEST_F(HidlTest,BazCallMeMethodTest)616 TEST_F(HidlTest, BazCallMeMethodTest) {
617     EXPECT_OK(baz->callMe(new BazCallback()));
618 }
619 
TEST_F(HidlTest,BazCallMeLaterMethodTest)620 TEST_F(HidlTest, BazCallMeLaterMethodTest) {
621     EXPECT_OK(baz->callMeLater(new BazCallback()));
622     EXPECT_OK(baz->iAmFreeNow());
623 }
624 
TEST_F(HidlTest,BazUseAnEnumMethodTest)625 TEST_F(HidlTest, BazUseAnEnumMethodTest) {
626     auto result = baz->useAnEnum(IBaz::SomeEnum::bar);
627 
628     EXPECT_OK(result);
629     EXPECT_TRUE(result == IBaz::SomeEnum::quux);
630 }
631 
TEST_F(HidlTest,BazHaveSomeStringsMethodTest)632 TEST_F(HidlTest, BazHaveSomeStringsMethodTest) {
633     hidl_array<hidl_string, 3> string_params;
634     string_params[0] = "one";
635     string_params[1] = "two";
636     string_params[2] = "three";
637 
638     hidl_array<hidl_string, 2> expected;
639     expected[0] = "Hello";
640     expected[1] = "World";
641 
642     EXPECT_OK(
643             baz->haveSomeStrings(
644                 string_params,
645                 [&](const auto &result) {
646                     EXPECT_EQ(expected, result);
647                 }));
648 }
649 
TEST_F(HidlTest,BazHaveAStringVecMethodTest)650 TEST_F(HidlTest, BazHaveAStringVecMethodTest) {
651     hidl_vec<hidl_string> string_vec{ "Uno", "Dos", "Tres", "Cuatro" };
652     hidl_vec<hidl_string> expected{"Hello", "World"};
653 
654     EXPECT_OK(
655             baz->haveAStringVec(
656                 string_vec,
657                 [&](const auto &result) {
658                     EXPECT_EQ(expected, result);
659                 }));
660 }
661 
TEST_F(HidlTest,BazRepeatBitfieldVecTest)662 TEST_F(HidlTest, BazRepeatBitfieldVecTest) {
663     hidl_vec<uint8_t> vec{0 | IBaz::BitField::V1, 0 | IBaz::BitField::V2};
664 
665     EXPECT_OK(baz->repeatBitfieldVec(vec, [&](const auto& result) { EXPECT_EQ(vec, result); }));
666 }
667 
TEST_F(HidlTest,BazReturnABunchOfStringsMethodTest)668 TEST_F(HidlTest, BazReturnABunchOfStringsMethodTest) {
669     std::string expectedA = "Eins";
670     std::string expectedB = "Zwei";
671     std::string expectedC = "Drei";
672     EXPECT_OK(
673             baz->returnABunchOfStrings(
674                 [&](const auto &a, const auto &b, const auto &c) {
675                     EXPECT_EQ(a, expectedA);
676                     EXPECT_EQ(b, expectedB);
677                     EXPECT_EQ(c, expectedC);
678                 }));
679 }
680 
TEST_F(HidlTest,BazTestArrays)681 TEST_F(HidlTest, BazTestArrays) {
682     IBase::LotsOfPrimitiveArrays in;
683 
684     for (size_t i = 0; i < 128; ++i) {
685         in.byte1[i] = i;
686         in.boolean1[i] = (i & 4) != 0;
687         in.double1[i] = i;
688     }
689 
690     size_t k = 0;
691     for (size_t i = 0; i < 8; ++i) {
692         for (size_t j = 0; j < 128; ++j, ++k) {
693             in.byte2[i][j] = k;
694             in.boolean2[i][j] = (k & 4) != 0;
695             in.double2[i][j] = k;
696         }
697     }
698 
699     size_t m = 0;
700     for (size_t i = 0; i < 8; ++i) {
701         for (size_t j = 0; j < 16; ++j) {
702             for (size_t k = 0; k < 128; ++k, ++m) {
703                 in.byte3[i][j][k] = m;
704                 in.boolean3[i][j][k] = (m & 4) != 0;
705                 in.double3[i][j][k] = m;
706             }
707         }
708     }
709 
710     EXPECT_OK(
711             baz->testArrays(in,
712                 [&](const auto &out) {
713                     EXPECT_EQ(in, out);
714                 }));
715 }
716 
TEST_F(HidlTest,BazTestByteVecs)717 TEST_F(HidlTest, BazTestByteVecs) {
718     hidl_vec<IBase::ByteOneDim> in;
719     in.resize(8);
720 
721     size_t k = 0;
722     for (size_t i = 0; i < in.size(); ++i) {
723         for (size_t j = 0; j < 128; ++j, ++k) {
724             in[i][j] = k;
725         }
726     }
727 
728     EXPECT_OK(baz->testByteVecs(
729                 in, [&](const auto &out) { EXPECT_EQ(in, out); }));
730 }
731 
TEST_F(HidlTest,BazTestBooleanVecs)732 TEST_F(HidlTest, BazTestBooleanVecs) {
733     hidl_vec<IBase::BooleanOneDim> in;
734     in.resize(8);
735 
736     size_t k = 0;
737     for (size_t i = 0; i < in.size(); ++i) {
738         for (size_t j = 0; j < 128; ++j, ++k) {
739             in[i][j] = (k & 4) != 0;
740         }
741     }
742 
743     EXPECT_OK(baz->testBooleanVecs(
744                 in, [&](const auto &out) { EXPECT_EQ(in, out); }));
745 }
746 
TEST_F(HidlTest,BazTestDoubleVecs)747 TEST_F(HidlTest, BazTestDoubleVecs) {
748     hidl_vec<IBase::DoubleOneDim> in;
749     in.resize(8);
750 
751     size_t k = 0;
752     for (size_t i = 0; i < in.size(); ++i) {
753         for (size_t j = 0; j < 128; ++j, ++k) {
754             in[i][j] = k;
755         }
756     }
757 
758     EXPECT_OK(baz->testDoubleVecs(
759                 in, [&](const auto &out) { EXPECT_EQ(in, out); }));
760 }
761 
TEST_F(HidlTest,TwowayMethodOnewayEnabledTest)762 TEST_F(HidlTest, TwowayMethodOnewayEnabledTest) {
763     using ::android::hardware::IBinder;
764     using ::android::hardware::Parcel;
765 
766     sp<IBinder> binder = ::android::hardware::toBinder(baz);
767 
768     Parcel request, reply;
769     EXPECT_EQ(::android::OK, request.writeInterfaceToken(IBaz::descriptor));
770     EXPECT_EQ(::android::OK, request.writeInt64(1234));
771     // IBaz::doThatAndReturnSomething is two-way but we call it using FLAG_ONEWAY.
772     EXPECT_EQ(::android::OK, binder->transact(18 /*doThatAndReturnSomething*/, request, &reply,
773                                               IBinder::FLAG_ONEWAY));
774 
775     ::android::hardware::Status status;
776     EXPECT_EQ(::android::NOT_ENOUGH_DATA, ::android::hardware::readFromParcel(&status, reply));
777     EXPECT_EQ(::android::hardware::Status::EX_TRANSACTION_FAILED, status.exceptionCode());
778 
779     EXPECT_OK(baz->ping());  // still works
780 }
781 
TEST_F(HidlTest,OnewayMethodOnewayDisabledTest)782 TEST_F(HidlTest, OnewayMethodOnewayDisabledTest) {
783     using ::android::hardware::IBinder;
784     using ::android::hardware::Parcel;
785 
786     sp<IBinder> binder = ::android::hardware::toBinder(baz);
787 
788     Parcel request, reply;
789     EXPECT_EQ(::android::OK, request.writeInterfaceToken(IBaz::descriptor));
790     EXPECT_EQ(::android::OK, request.writeFloat(1.0f));
791     // IBaz::doThis is oneway but we call it without using FLAG_ONEWAY.
792     EXPECT_EQ(
793             // Expect UNKNOWN_ERROR because the JNI class JHwBinder always sets
794             // the reply to UNKNOWN_ERROR for two-way transactions if the
795             // transaction itself did not send a reply.
796             ::android::UNKNOWN_ERROR,
797             binder->transact(17 /*doThis*/, request, &reply, 0 /* Not FLAG_ONEWAY */));
798 
799     EXPECT_OK(baz->ping());  // still works
800 }
801 
TEST_F(HidlTest,SafeUnionNoInitTest)802 TEST_F(HidlTest, SafeUnionNoInitTest) {
803     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& safeUnion) {
804         EXPECT_EQ(LargeSafeUnion::hidl_discriminator::noinit, safeUnion.getDiscriminator());
805     }));
806 }
807 
TEST_F(HidlTest,SafeUnionSimpleTest)808 TEST_F(HidlTest, SafeUnionSimpleTest) {
809     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& safeUnion) {
810         EXPECT_OK(safeunionInterface->setA(safeUnion, -5, [&](const LargeSafeUnion& safeUnion) {
811             EXPECT_EQ(LargeSafeUnion::hidl_discriminator::a, safeUnion.getDiscriminator());
812             EXPECT_EQ(-5, safeUnion.a());
813 
814             uint64_t max = std::numeric_limits<uint64_t>::max();
815             EXPECT_OK(
816                 safeunionInterface->setD(safeUnion, max, [&](const LargeSafeUnion& safeUnion) {
817                     EXPECT_EQ(LargeSafeUnion::hidl_discriminator::d, safeUnion.getDiscriminator());
818                     EXPECT_EQ(max, safeUnion.d());
819                 }));
820         }));
821     }));
822 }
823 
TEST_F(HidlTest,SafeUnionArrayLikeTypesTest)824 TEST_F(HidlTest, SafeUnionArrayLikeTypesTest) {
825     const std::array<int64_t, 5> testArray{1, -2, 3, -4, 5};
826     const hidl_vec<uint64_t> testVector{std::numeric_limits<uint64_t>::max()};
827 
828     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& safeUnion) {
829         EXPECT_OK(
830             safeunionInterface->setF(safeUnion, testArray, [&](const LargeSafeUnion& safeUnion) {
831                 EXPECT_EQ(LargeSafeUnion::hidl_discriminator::f, safeUnion.getDiscriminator());
832 
833                 for (size_t i = 0; i < testArray.size(); i++) {
834                     EXPECT_EQ(testArray[i], safeUnion.f()[i]);
835                 }
836             }));
837 
838         EXPECT_OK(
839             safeunionInterface->setI(safeUnion, testVector, [&](const LargeSafeUnion& safeUnion) {
840                 EXPECT_EQ(LargeSafeUnion::hidl_discriminator::i, safeUnion.getDiscriminator());
841                 EXPECT_EQ(testVector, safeUnion.i());
842             }));
843     }));
844 }
845 
TEST_F(HidlTest,SafeUnionStringTypeTest)846 TEST_F(HidlTest, SafeUnionStringTypeTest) {
847     const std::string testString =
848         "This is an inordinately long test string to exercise hidl_string types in safe unions.";
849 
850     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& safeUnion) {
851         EXPECT_OK(safeunionInterface->setG(
852             safeUnion, hidl_string(testString), [&](const LargeSafeUnion& safeUnion) {
853                 EXPECT_EQ(LargeSafeUnion::hidl_discriminator::g, safeUnion.getDiscriminator());
854                 EXPECT_EQ(testString, std::string(safeUnion.g()));
855             }));
856     }));
857 }
858 
TEST_F(HidlTest,SafeUnionNestedTest)859 TEST_F(HidlTest, SafeUnionNestedTest) {
860     SmallSafeUnion smallSafeUnion;
861     smallSafeUnion.a(1);
862 
863     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& safeUnion) {
864         EXPECT_OK(safeunionInterface->setL(
865             safeUnion, smallSafeUnion, [&](const LargeSafeUnion& safeUnion) {
866                 EXPECT_EQ(LargeSafeUnion::hidl_discriminator::l, safeUnion.getDiscriminator());
867 
868                 EXPECT_EQ(SmallSafeUnion::hidl_discriminator::a, safeUnion.l().getDiscriminator());
869                 EXPECT_EQ(1, safeUnion.l().a());
870             }));
871     }));
872 }
873 
874 // does not check for fd equality
checkNativeHandlesDataEquality(const native_handle_t * reference,const native_handle_t * result)875 static void checkNativeHandlesDataEquality(const native_handle_t* reference,
876                                        const native_handle_t* result) {
877     if (reference == nullptr || result == nullptr) {
878         EXPECT_EQ(reference == nullptr, result == nullptr);
879         return;
880     }
881 
882     ASSERT_NE(reference, result);
883     ASSERT_EQ(reference->version, result->version);
884     EXPECT_EQ(reference->numFds, result->numFds);
885     EXPECT_EQ(reference->numInts, result->numInts);
886 
887     int offset = reference->numFds;
888     int numInts = reference->numInts;
889     EXPECT_TRUE(isArrayEqual(&(reference->data[offset]), &(result->data[offset]), numInts));
890 }
891 
TEST_F(HidlTest,SafeUnionInterfaceNullHandleTest)892 TEST_F(HidlTest, SafeUnionInterfaceNullHandleTest) {
893     InterfaceTypeSafeUnion safeUnion;
894 
895     EXPECT_OK(safeunionInterface->setInterfaceF(
896         safeUnion, hidl_handle(nullptr), [&](const InterfaceTypeSafeUnion& safeUnion) {
897             EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::f,
898                       safeUnion.getDiscriminator());
899 
900             checkNativeHandlesDataEquality(nullptr, safeUnion.f().getNativeHandle());
901         }));
902 }
903 
TEST_F(HidlTest,SafeUnionInterfaceTest)904 TEST_F(HidlTest, SafeUnionInterfaceTest) {
905     const std::array<int8_t, 7> testArray{-1, -2, -3, 0, 1, 2, 3};
906     const hidl_vec<hidl_string> testVector{"So", "Many", "Words"};
907     const std::string testStringA = "Hello";
908     const std::string testStringB = "World";
909 
910     const std::array<int, 6> testHandleData{2, -32, 10, -4329454, 11, 24};
911     native_handle_t* h = native_handle_create(0, testHandleData.size());
912     CHECK(sizeof(testHandleData) == testHandleData.size() * sizeof(int));
913     std::memcpy(h->data, testHandleData.data(), sizeof(testHandleData));
914 
915     std::vector<hidl_handle> testHandlesVector(256);
916     for (size_t i = 0; i < testHandlesVector.size(); i++) {
917         testHandlesVector[i].setTo(native_handle_clone(h), true /* shouldOwn */);
918     }
919 
920     EXPECT_OK(
921         safeunionInterface->newInterfaceTypeSafeUnion([&](const InterfaceTypeSafeUnion& safeUnion) {
922             EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::noinit,
923                       safeUnion.getDiscriminator());
924 
925             EXPECT_OK(safeunionInterface->setInterfaceB(
926                 safeUnion, testArray, [&](const InterfaceTypeSafeUnion& safeUnion) {
927                     EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::b,
928                               safeUnion.getDiscriminator());
929 
930                     for (size_t i = 0; i < testArray.size(); i++) {
931                         EXPECT_EQ(testArray[i], safeUnion.b()[i]);
932                     }
933                 }));
934 
935             EXPECT_OK(safeunionInterface->setInterfaceD(
936                 safeUnion, testStringA, [&](const InterfaceTypeSafeUnion& safeUnion) {
937                     EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::d,
938                               safeUnion.getDiscriminator());
939                     EXPECT_EQ(testStringA, safeUnion.d());
940                 }));
941 
942             EXPECT_OK(safeunionInterface->setInterfaceE(
943                 safeUnion, testVector, [&](const InterfaceTypeSafeUnion& safeUnion) {
944                     EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::e,
945                               safeUnion.getDiscriminator());
946                     EXPECT_EQ(testVector, safeUnion.e());
947                 }));
948 
949             EXPECT_OK(safeunionInterface->setInterfaceF(
950                 safeUnion, hidl_handle(h), [&](const InterfaceTypeSafeUnion& safeUnion) {
951                     EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::f,
952                               safeUnion.getDiscriminator());
953 
954                     const native_handle_t* result = safeUnion.f().getNativeHandle();
955                     checkNativeHandlesDataEquality(h, result);
956                 }));
957 
958             EXPECT_OK(safeunionInterface->setInterfaceG(
959                 safeUnion, testHandlesVector, [&](const InterfaceTypeSafeUnion& safeUnion) {
960                     EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::g,
961                               safeUnion.getDiscriminator());
962 
963                     for (size_t i = 0; i < testHandlesVector.size(); i++) {
964                         checkNativeHandlesDataEquality(h, safeUnion.g()[i].getNativeHandle());
965                     }
966                 }));
967         }));
968 
969     // Same-process interface calls are not supported in Java, so we use
970     // a safe_union instance bound to this (client) process instead of
971     // safeunionInterface to exercise this test-case. Ref: b/110957763.
972     InterfaceTypeSafeUnion safeUnion;
973     safeUnion.c(otherInterface);
974 
975     EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::c, safeUnion.getDiscriminator());
976     EXPECT_OK(safeUnion.c()->concatTwoStrings(
977         hidl_string(testStringA), hidl_string(testStringB), [&](const hidl_string& result) {
978             EXPECT_EQ(testStringA + testStringB, std::string(result));
979         }));
980 
981     native_handle_delete(h);
982 }
983 
TEST_F(HidlTest,SafeUnionNullHandleTest)984 TEST_F(HidlTest, SafeUnionNullHandleTest) {
985     HandleTypeSafeUnion safeUnion;
986 
987     EXPECT_OK(safeunionInterface->setHandleA(
988         safeUnion, hidl_handle(nullptr), [&](const HandleTypeSafeUnion& safeUnion) {
989             EXPECT_EQ(HandleTypeSafeUnion::hidl_discriminator::a,
990                       safeUnion.getDiscriminator());
991 
992             checkNativeHandlesDataEquality(nullptr, safeUnion.a().getNativeHandle());
993         }));
994 }
995 
TEST_F(HidlTest,SafeUnionSimpleHandleTest)996 TEST_F(HidlTest, SafeUnionSimpleHandleTest) {
997     const std::array<int, 6> testData{2, -32, 10, -4329454, 11, 24};
998     native_handle_t* h = native_handle_create(0, testData.size());
999     ASSERT_EQ(sizeof(testData), testData.size() * sizeof(int));
1000     std::memcpy(h->data, testData.data(), sizeof(testData));
1001 
1002     std::array<hidl_handle, 5> testArray;
1003     for (size_t i = 0; i < testArray.size(); i++) {
1004         testArray[i].setTo(native_handle_clone(h), true /* shouldOwn */);
1005     }
1006 
1007     std::vector<hidl_handle> testVector(256);
1008     for (size_t i = 0; i < testVector.size(); i++) {
1009         testVector[i].setTo(native_handle_clone(h), true /* shouldOwn */);
1010     }
1011 
1012     EXPECT_OK(
1013         safeunionInterface->newHandleTypeSafeUnion([&](const HandleTypeSafeUnion& safeUnion) {
1014             EXPECT_OK(safeunionInterface->setHandleA(
1015                 safeUnion, hidl_handle(h), [&](const HandleTypeSafeUnion& safeUnion) {
1016                     EXPECT_EQ(HandleTypeSafeUnion::hidl_discriminator::a,
1017                               safeUnion.getDiscriminator());
1018 
1019                     checkNativeHandlesDataEquality(h, safeUnion.a().getNativeHandle());
1020                 }));
1021 
1022             EXPECT_OK(safeunionInterface->setHandleB(
1023                 safeUnion, testArray, [&](const HandleTypeSafeUnion& safeUnion) {
1024                     EXPECT_EQ(HandleTypeSafeUnion::hidl_discriminator::b,
1025                               safeUnion.getDiscriminator());
1026 
1027                     for (size_t i = 0; i < testArray.size(); i++) {
1028                         checkNativeHandlesDataEquality(h, safeUnion.b()[i].getNativeHandle());
1029                     }
1030                 }));
1031 
1032             EXPECT_OK(safeunionInterface->setHandleC(
1033                 safeUnion, testVector, [&](const HandleTypeSafeUnion& safeUnion) {
1034                     EXPECT_EQ(HandleTypeSafeUnion::hidl_discriminator::c,
1035                               safeUnion.getDiscriminator());
1036 
1037                     for (size_t i = 0; i < testVector.size(); i++) {
1038                         checkNativeHandlesDataEquality(h, safeUnion.c()[i].getNativeHandle());
1039                     }
1040                 }));
1041         }));
1042 
1043     native_handle_delete(h);
1044 }
1045 
TEST_F(HidlTest,SafeUnionVecOfHandlesWithOneFdTest)1046 TEST_F(HidlTest, SafeUnionVecOfHandlesWithOneFdTest) {
1047     const std::vector<std::string> testStrings{"This ", "is ", "so ", "much ", "data!\n"};
1048     const std::string testFileName = "/data/local/tmp/SafeUnionVecOfHandlesWithOneFdTest";
1049     const std::array<int, 6> testData{2, -32, 10, -4329454, 11, 24};
1050     ASSERT_EQ(sizeof(testData), testData.size() * sizeof(int));
1051 
1052     const std::string goldenResult = std::accumulate(testStrings.begin(),
1053                                                      testStrings.end(),
1054                                                      std::string());
1055 
1056     int fd = open(testFileName.c_str(), (O_RDWR | O_TRUNC | O_CREAT), (S_IRUSR | S_IWUSR));
1057     ASSERT_TRUE(fd >= 0);
1058 
1059     native_handle* h = native_handle_create(1 /* numFds */, testData.size() /* numInts */);
1060     std::memcpy(&(h->data[1]), testData.data(), sizeof(testData));
1061     h->data[0] = fd;
1062 
1063     hidl_vec<hidl_handle> testHandles(testStrings.size());
1064     for (size_t i = 0; i < testHandles.size(); i++) {
1065         testHandles[i].setTo(native_handle_clone(h), true /* shouldOwn */);
1066     }
1067 
1068     EXPECT_OK(
1069         safeunionInterface->newHandleTypeSafeUnion([&](const HandleTypeSafeUnion& safeUnion) {
1070             EXPECT_OK(safeunionInterface->setHandleC(
1071                 safeUnion, testHandles, [&](const HandleTypeSafeUnion& safeUnion) {
1072                     EXPECT_EQ(HandleTypeSafeUnion::hidl_discriminator::c,
1073                               safeUnion.getDiscriminator());
1074 
1075                     for (size_t i = 0; i < safeUnion.c().size(); i++) {
1076                         const native_handle_t* reference = testHandles[i].getNativeHandle();
1077                         const native_handle_t* result = safeUnion.c()[i].getNativeHandle();
1078                         checkNativeHandlesDataEquality(reference, result);
1079 
1080                         // Original FDs should be dup'd
1081                         int resultFd = result->data[0];
1082                         EXPECT_NE(reference->data[0], resultFd);
1083 
1084                         EXPECT_TRUE(android::base::WriteStringToFd(testStrings[i], resultFd));
1085                         EXPECT_EQ(0, fsync(resultFd));
1086                     }
1087                 }));
1088         }));
1089 
1090     std::string result;
1091     lseek(fd, 0, SEEK_SET);
1092 
1093     EXPECT_TRUE(android::base::ReadFdToString(fd, &result));
1094     EXPECT_EQ(goldenResult, result);
1095 
1096     native_handle_delete(h);
1097     EXPECT_EQ(0, close(fd));
1098     EXPECT_EQ(0, remove(testFileName.c_str()));
1099 }
1100 
TEST_F(HidlTest,SafeUnionHandleWithMultipleFdsTest)1101 TEST_F(HidlTest, SafeUnionHandleWithMultipleFdsTest) {
1102     const std::vector<std::string> testStrings{"This ", "is ", "so ", "much ", "data!\n"};
1103     const std::string testFileName = "/data/local/tmp/SafeUnionHandleWithMultipleFdsTest";
1104     const std::array<int, 6> testData{2, -32, 10, -4329454, 11, 24};
1105     ASSERT_EQ(sizeof(testData), testData.size() * sizeof(int));
1106 
1107     const std::string goldenResult = std::accumulate(testStrings.begin(),
1108                                                      testStrings.end(),
1109                                                      std::string());
1110 
1111     int fd = open(testFileName.c_str(), (O_RDWR | O_TRUNC | O_CREAT), (S_IRUSR | S_IWUSR));
1112     ASSERT_TRUE(fd >= 0);
1113 
1114     const int numFds = testStrings.size();
1115     native_handle* h = native_handle_create(numFds, testData.size() /* numInts */);
1116     std::memcpy(&(h->data[numFds]), testData.data(), sizeof(testData));
1117     for (size_t i = 0; i < numFds; i++) {
1118         h->data[i] = fd;
1119     }
1120 
1121     hidl_handle testHandle;
1122     testHandle.setTo(h, false /* shouldOwn */);
1123 
1124     EXPECT_OK(
1125         safeunionInterface->newHandleTypeSafeUnion([&](const HandleTypeSafeUnion& safeUnion) {
1126             EXPECT_OK(safeunionInterface->setHandleA(
1127                 safeUnion, testHandle, [&](const HandleTypeSafeUnion& safeUnion) {
1128                     EXPECT_EQ(HandleTypeSafeUnion::hidl_discriminator::a,
1129                               safeUnion.getDiscriminator());
1130 
1131                     const native_handle_t* result = safeUnion.a().getNativeHandle();
1132                     checkNativeHandlesDataEquality(h, result);
1133 
1134                     for (size_t i = 0; i < result->numFds; i++) {
1135                         // Original FDs should be dup'd
1136                         int resultFd = result->data[i];
1137                         EXPECT_NE(h->data[i], resultFd);
1138 
1139                         EXPECT_TRUE(android::base::WriteStringToFd(testStrings[i], resultFd));
1140                         EXPECT_EQ(0, fsync(resultFd));
1141                     }
1142                 }));
1143         }));
1144 
1145     std::string result;
1146     lseek(fd, 0, SEEK_SET);
1147 
1148     EXPECT_TRUE(android::base::ReadFdToString(fd, &result));
1149     EXPECT_EQ(goldenResult, result);
1150 
1151     native_handle_delete(h);
1152     EXPECT_EQ(0, close(fd));
1153     EXPECT_EQ(0, remove(testFileName.c_str()));
1154 }
1155 
TEST_F(HidlTest,SafeUnionEqualityTest)1156 TEST_F(HidlTest, SafeUnionEqualityTest) {
1157     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& one) {
1158         EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& two) {
1159             EXPECT_TRUE(one == two);
1160             EXPECT_FALSE(one != two);
1161         }));
1162 
1163         EXPECT_OK(safeunionInterface->setA(one, 1, [&](const LargeSafeUnion& one) {
1164             EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& two) {
1165                 EXPECT_FALSE(one == two);
1166                 EXPECT_TRUE(one != two);
1167             }));
1168 
1169             EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& two) {
1170                 EXPECT_OK(safeunionInterface->setB(two, 1, [&](const LargeSafeUnion& two) {
1171                     EXPECT_FALSE(one == two);
1172                     EXPECT_TRUE(one != two);
1173                 }));
1174             }));
1175 
1176             EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& two) {
1177                 EXPECT_OK(safeunionInterface->setA(two, 2, [&](const LargeSafeUnion& two) {
1178                     EXPECT_FALSE(one == two);
1179                     EXPECT_TRUE(one != two);
1180                 }));
1181             }));
1182 
1183             EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& two) {
1184                 EXPECT_OK(safeunionInterface->setA(two, 1, [&](const LargeSafeUnion& two) {
1185                     EXPECT_TRUE(one == two);
1186                     EXPECT_FALSE(one != two);
1187                 }));
1188             }));
1189         }));
1190     }));
1191 }
1192 
1193 template <typename T, size_t start, size_t end>
expectRangeEqual(const T * t,uint8_t byte)1194 void expectRangeEqual(const T* t, uint8_t byte) {
1195     static_assert(start < sizeof(T));
1196     static_assert(end <= sizeof(T));
1197 
1198     const uint8_t* buf = reinterpret_cast<const uint8_t*>(t);
1199 
1200     for (size_t i = start; i < end; i++) {
1201         EXPECT_EQ(byte, buf[i]) << i;
1202     }
1203 }
1204 
TEST_F(HidlTest,UninitTest)1205 TEST_F(HidlTest, UninitTest) {
1206     IBase::Foo foo;
1207     foo.x = 1;
1208     foo.y = {0, ""};
1209 
1210     static_assert(offsetof(IBase::Foo, x) == 0);
1211     static_assert(sizeof(foo.x) == 4);
1212     static_assert(offsetof(IBase::Foo, aaa) == 8);
1213 
1214     uint8_t* buf = reinterpret_cast<uint8_t*>(&foo);
1215     memset(buf + 4, 0xFF, 4);
1216 
1217     // this should not affect the result for remote Java (but would for remote C++)
1218     expectRangeEqual<IBase::Foo, 4, 8>(&foo, 0xFF);
1219 
1220     // run many times, if this error case is hit, it will only be hit
1221     // sometimes.
1222     for (size_t i = 0; i < 100; i++) {
1223         EXPECT_OK(baz->someOtherBaseMethod(
1224                 foo, [](const IBase::Foo& foo) { expectRangeEqual<IBase::Foo, 4, 8>(&foo, 0); }));
1225     }
1226 }
1227 
main(int argc,char ** argv)1228 int main(int argc, char **argv) {
1229     setenv("TREBLE_TESTING_OVERRIDE", "true", true);
1230 
1231     using namespace android::hardware;
1232 
1233     const char *me = argv[0];
1234 
1235     bool wantClient = false;
1236     bool wantServer = false;
1237 
1238     int res;
1239     while ((res = getopt(argc, argv, "chs")) >= 0) {
1240         switch (res) {
1241             case 'c':
1242             {
1243                 wantClient = true;
1244                 break;
1245             }
1246 
1247             case 's':
1248             {
1249                 wantServer = true;
1250                 break;
1251             }
1252 
1253             case '?':
1254             case 'h':
1255             default:
1256             {
1257                 usage(me);
1258                 exit(1);
1259                 break;
1260             }
1261         }
1262     }
1263 
1264     if ((!wantClient && !wantServer) || (wantClient && wantServer)) {
1265         usage(me);
1266         exit(1);
1267     }
1268 
1269     if (wantClient) {
1270         ::testing::AddGlobalTestEnvironment(new HidlEnvironment);
1271         ::testing::InitGoogleTest(&argc, argv);
1272         int status = RUN_ALL_TESTS();
1273         return status;
1274     }
1275 
1276     ::android::status_t status;
1277     configureRpcThreadpool(1, true);
1278 
1279     status = registerPassthroughServiceImplementation<IBaz>();
1280     CHECK(status == ::android::OK) << "IBaz didn't register";
1281 
1282     status = registerPassthroughServiceImplementation<ISafeUnion>();
1283     CHECK(status == ::android::OK) << "ISafeUnion didn't register";
1284 
1285     sp<IOtherInterface> otherInterface = new OtherInterface();
1286     status = otherInterface->registerAsService();
1287     CHECK(status == ::android::OK) << "IOtherInterface didn't register";
1288 
1289     sp<IMemoryInterface> memoryInterface = new MemoryInterface();
1290     status = memoryInterface->registerAsService();
1291     CHECK(status == ::android::OK) << "IMemoryInterface didn't register";
1292 
1293     joinRpcThreadpool();
1294     return 0;
1295 }
1296