• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #define LOG_TAG "hidl_test_client"
2 
3 #include "FooCallback.h"
4 #include "hidl_test.h"
5 
6 #include <android-base/file.h>
7 #include <android-base/logging.h>
8 
9 #include <android/hidl/manager/1.0/IServiceNotification.h>
10 #include <android/hidl/manager/1.2/IServiceManager.h>
11 
12 #include <android/hidl/allocator/1.0/IAllocator.h>
13 #include <android/hidl/memory/1.0/IMemory.h>
14 #include <android/hidl/memory/token/1.0/IMemoryToken.h>
15 #include <android/hidl/token/1.0/ITokenManager.h>
16 
17 #include <android/hardware/tests/bar/1.0/BnHwBar.h>
18 #include <android/hardware/tests/bar/1.0/BpHwBar.h>
19 #include <android/hardware/tests/bar/1.0/IBar.h>
20 #include <android/hardware/tests/bar/1.0/IComplicated.h>
21 #include <android/hardware/tests/bar/1.0/IImportRules.h>
22 #include <android/hardware/tests/baz/1.0/BnHwBaz.h>
23 #include <android/hardware/tests/baz/1.0/IBaz.h>
24 #include <android/hardware/tests/expression/1.0/IExpression.h>
25 #include <android/hardware/tests/foo/1.0/BnHwSimple.h>
26 #include <android/hardware/tests/foo/1.0/BpHwSimple.h>
27 #include <android/hardware/tests/foo/1.0/BsSimple.h>
28 #include <android/hardware/tests/foo/1.0/IFoo.h>
29 #include <android/hardware/tests/hash/1.0/IHash.h>
30 #include <android/hardware/tests/inheritance/1.0/IChild.h>
31 #include <android/hardware/tests/inheritance/1.0/IFetcher.h>
32 #include <android/hardware/tests/inheritance/1.0/IGrandparent.h>
33 #include <android/hardware/tests/inheritance/1.0/IParent.h>
34 #include <android/hardware/tests/memory/1.0/IMemoryTest.h>
35 #include <android/hardware/tests/multithread/1.0/IMultithread.h>
36 #include <android/hardware/tests/safeunion/1.0/ISafeUnion.h>
37 #include <android/hardware/tests/safeunion/cpp/1.0/ICppSafeUnion.h>
38 #include <android/hardware/tests/trie/1.0/ITrie.h>
39 
40 #include <gtest/gtest.h>
41 #if GTEST_IS_THREADSAFE
42 #include <sys/types.h>
43 #include <sys/wait.h>
44 #include <signal.h>
45 #include <errno.h>
46 #include <pthread.h>
47 #else
48 #error "GTest did not detect pthread library."
49 #endif
50 
51 #include <getopt.h>
52 #include <inttypes.h>
53 #include <algorithm>
54 #include <condition_variable>
55 #include <fstream>
56 #include <future>
57 #include <limits>
58 #include <mutex>
59 #include <random>
60 #include <set>
61 #include <sstream>
62 #include <sys/stat.h>
63 #include <thread>
64 #include <type_traits>
65 #include <unordered_set>
66 #include <utility>
67 #include <vector>
68 
69 #include <hidl-test/FooHelper.h>
70 #include <hidl-util/FQName.h>
71 
72 #include <hidl/ServiceManagement.h>
73 #include <hidl/Status.h>
74 #include <hidlmemory/HidlMemoryToken.h>
75 #include <hidlmemory/mapping.h>
76 
77 #include <utils/Condition.h>
78 #include <utils/Timers.h>
79 
80 #define EXPECT_OK(__ret__) EXPECT_TRUE(isOk(__ret__))
81 #define EXPECT_FAIL(__ret__) EXPECT_FALSE(isOk(__ret__))
82 #define EXPECT_ARRAYEQ(__a1__, __a2__, __size__) EXPECT_TRUE(isArrayEqual(__a1__, __a2__, __size__))
83 
84 // forward declarations.
85 class HidlEnvironment;
86 
87 // static storage
88 enum TestMode {
89     BINDERIZED,
90     PASSTHROUGH
91 };
92 
93 static HidlEnvironment *gHidlEnvironment = nullptr;
94 
95 using ::android::Condition;
96 using ::android::DELAY_NS;
97 using ::android::DELAY_S;
98 using ::android::FQName;
99 using ::android::MultiDimensionalToString;
100 using ::android::Mutex;
101 using ::android::ONEWAY_TOLERANCE_NS;
102 using ::android::sp;
103 using ::android::to_string;
104 using ::android::TOLERANCE_NS;
105 using ::android::wp;
106 using ::android::hardware::GrantorDescriptor;
107 using ::android::hardware::hidl_array;
108 using ::android::hardware::hidl_death_recipient;
109 using ::android::hardware::hidl_handle;
110 using ::android::hardware::hidl_memory;
111 using ::android::hardware::hidl_string;
112 using ::android::hardware::hidl_vec;
113 using ::android::hardware::HidlMemory;
114 using ::android::hardware::MQDescriptor;
115 using ::android::hardware::MQFlavor;
116 using ::android::hardware::Return;
117 using ::android::hardware::Void;
118 using ::android::hardware::tests::bar::V1_0::IBar;
119 using ::android::hardware::tests::bar::V1_0::IComplicated;
120 using ::android::hardware::tests::baz::V1_0::IBaz;
121 using ::android::hardware::tests::expression::V1_0::IExpression;
122 using ::android::hardware::tests::foo::V1_0::Abc;
123 using ::android::hardware::tests::foo::V1_0::IFoo;
124 using ::android::hardware::tests::foo::V1_0::IFooCallback;
125 using ::android::hardware::tests::foo::V1_0::ISimple;
126 using ::android::hardware::tests::foo::V1_0::implementation::FooCallback;
127 using ::android::hardware::tests::hash::V1_0::IHash;
128 using ::android::hardware::tests::inheritance::V1_0::IChild;
129 using ::android::hardware::tests::inheritance::V1_0::IFetcher;
130 using ::android::hardware::tests::inheritance::V1_0::IGrandparent;
131 using ::android::hardware::tests::inheritance::V1_0::IParent;
132 using ::android::hardware::tests::memory::V1_0::IMemoryTest;
133 using ::android::hardware::tests::multithread::V1_0::IMultithread;
134 using ::android::hardware::tests::safeunion::cpp::V1_0::ICppSafeUnion;
135 using ::android::hardware::tests::safeunion::V1_0::ISafeUnion;
136 using ::android::hardware::tests::trie::V1_0::ITrie;
137 using ::android::hardware::tests::trie::V1_0::TrieNode;
138 using ::android::hidl::allocator::V1_0::IAllocator;
139 using ::android::hidl::base::V1_0::IBase;
140 using ::android::hidl::manager::V1_0::IServiceNotification;
141 using ::android::hidl::manager::V1_2::IServiceManager;
142 using ::android::hidl::memory::block::V1_0::MemoryBlock;
143 using ::android::hidl::memory::token::V1_0::IMemoryToken;
144 using ::android::hidl::memory::V1_0::IMemory;
145 using ::android::hidl::token::V1_0::ITokenManager;
146 using std::to_string;
147 
148 using HandleTypeSafeUnion = ISafeUnion::HandleTypeSafeUnion;
149 using InterfaceTypeSafeUnion = ISafeUnion::InterfaceTypeSafeUnion;
150 using LargeSafeUnion = ISafeUnion::LargeSafeUnion;
151 using SmallSafeUnion = ISafeUnion::SmallSafeUnion;
152 
153 template <typename T>
154 using hidl_enum_range = ::android::hardware::hidl_enum_range<T>;
155 
156 template <typename T>
isOk(const::android::hardware::Return<T> & ret)157 static inline ::testing::AssertionResult isOk(const ::android::hardware::Return<T> &ret) {
158     return ret.isOk()
159         ? (::testing::AssertionSuccess() << ret.description())
160         : (::testing::AssertionFailure() << ret.description());
161 }
162 
163 template<typename T, typename S>
isArrayEqual(const T arr1,const S arr2,size_t size)164 static inline bool isArrayEqual(const T arr1, const S arr2, size_t size) {
165     for(size_t i = 0; i < size; i++)
166         if(arr1[i] != arr2[i])
167             return false;
168     return true;
169 }
170 
171 template<typename T>
to_string(std::set<T> set)172 std::string to_string(std::set<T> set) {
173     std::stringstream ss;
174     ss << "{";
175 
176     bool first = true;
177     for (const T &item : set) {
178         if (first) {
179             first = false;
180         } else {
181             ss << ", ";
182         }
183 
184         ss << to_string(item);
185     }
186 
187     ss << "}";
188 
189     return ss.str();
190 }
191 
192 // does not check for fd equality
checkNativeHandlesDataEquality(const native_handle_t * reference,const native_handle_t * result)193 static void checkNativeHandlesDataEquality(const native_handle_t* reference,
194                                            const native_handle_t* result) {
195     if (reference == nullptr || result == nullptr) {
196         EXPECT_EQ(reference, result);
197         return;
198     }
199 
200     ASSERT_EQ(reference->version, result->version);
201     EXPECT_EQ(reference->numFds, result->numFds);
202     EXPECT_EQ(reference->numInts, result->numInts);
203 
204     int offset = reference->numFds;
205     int numInts = reference->numInts;
206     EXPECT_ARRAYEQ(&(reference->data[offset]), &(result->data[offset]), numInts);
207 }
208 
209 template <typename T, MQFlavor flavor>
checkMQDescriptorEquality(const MQDescriptor<T,flavor> & expected,const MQDescriptor<T,flavor> & actual)210 static void checkMQDescriptorEquality(const MQDescriptor<T, flavor>& expected,
211                                       const MQDescriptor<T, flavor>& actual) {
212     checkNativeHandlesDataEquality(expected.handle(), actual.handle());
213     EXPECT_EQ(expected.grantors().size(), actual.grantors().size());
214     EXPECT_EQ(expected.getQuantum(), actual.getQuantum());
215     EXPECT_EQ(expected.getFlags(), actual.getFlags());
216 }
217 
218 struct Simple : public ISimple {
SimpleSimple219     Simple(int32_t cookie)
220         : mCookie(cookie) {
221     }
222 
getCookieSimple223     Return<int32_t> getCookie() override {
224         return mCookie;
225     }
226 
customVecIntSimple227     Return<void> customVecInt(customVecInt_cb _cb) override {
228         _cb(hidl_vec<int32_t>());
229         return Void();
230     }
231 
customVecStrSimple232     Return<void> customVecStr(customVecStr_cb _cb) override {
233         hidl_vec<hidl_string> vec;
234         vec.resize(2);
235         _cb(vec);
236         return Void();
237     }
238 
mystrSimple239     Return<void> mystr(mystr_cb _cb) override {
240         _cb(hidl_string());
241         return Void();
242     }
243 
myhandleSimple244     Return<void> myhandle(myhandle_cb _cb) override {
245         auto h = native_handle_create(0, 1);
246         _cb(h);
247         native_handle_delete(h);
248         return Void();
249     }
250 
251 private:
252     int32_t mCookie;
253 };
254 
255 struct SimpleParent : public IParent {
doGrandparentSimpleParent256     Return<void> doGrandparent() override {
257         return Void();
258     }
doParentSimpleParent259     Return<void> doParent() override {
260         return Void();
261     }
262 };
263 
264 struct SimpleChild : public IChild {
doGrandparentSimpleChild265     Return<void> doGrandparent() override {
266         return Void();
267     }
doParentSimpleChild268     Return <void> doParent() override {
269         return Void();
270     }
doChildSimpleChild271     Return <void> doChild() override {
272         return Void();
273     }
274 };
275 
276 struct Complicated : public IComplicated {
ComplicatedComplicated277     Complicated(int32_t cookie)
278         : mCookie(cookie) {
279     }
280 
getCookieComplicated281     Return<int32_t> getCookie() override {
282         return mCookie;
283     }
284 
customVecIntComplicated285     Return<void> customVecInt(customVecInt_cb _cb) override {
286         _cb(hidl_vec<int32_t>());
287         return Void();
288     }
customVecStrComplicated289     Return<void> customVecStr(customVecStr_cb _cb) override {
290         hidl_vec<hidl_string> vec;
291         vec.resize(2);
292         _cb(vec);
293         return Void();
294     }
295 
mystrComplicated296     Return<void> mystr(mystr_cb _cb) override {
297         _cb(hidl_string());
298         return Void();
299     }
300 
myhandleComplicated301     Return<void> myhandle(myhandle_cb _cb) override {
302         auto h = native_handle_create(0, 1);
303         _cb(h);
304         native_handle_delete(h);
305         return Void();
306     }
307 
308 private:
309     int32_t mCookie;
310 };
311 
312 struct ServiceNotification : public IServiceNotification {
313     std::mutex mutex;
314     std::condition_variable condition;
315 
onRegistrationServiceNotification316     Return<void> onRegistration(const hidl_string &fqName,
317                                 const hidl_string &name,
318                                 bool preexisting) override {
319         if (preexisting) {
320             // not interested in things registered from previous runs of hidl_test
321             return Void();
322         }
323 
324         std::unique_lock<std::mutex> lock(mutex);
325 
326         mRegistered.push_back(std::string(fqName.c_str()) + "/" + name.c_str());
327 
328         lock.unlock();
329         condition.notify_one();
330 
331         return Void();
332     }
333 
getRegistrationsServiceNotification334     const std::vector<std::string> &getRegistrations() const {
335         return mRegistered;
336     }
337 
338 private:
339     std::vector<std::string> mRegistered{};
340 };
341 
342 class HidlEnvironment : public ::testing::Environment {
343 public:
344     sp<IServiceManager> manager;
345     sp<ITokenManager> tokenManager;
346     sp<IAllocator> ashmemAllocator;
347     sp<IMemoryTest> memoryTest;
348     sp<IFetcher> fetcher;
349     sp<IFoo> foo;
350     sp<IBaz> baz;
351     sp<IBaz> dyingBaz;
352     sp<IBar> bar;
353     sp<IMultithread> multithreadInterface;
354     sp<ITrie> trieInterface;
355     sp<ICppSafeUnion> cppSafeunionInterface;
356     sp<ISafeUnion> safeunionInterface;
357     TestMode mode;
358     bool enableDelayMeasurementTests;
HidlEnvironment(TestMode mode,bool enableDelayMeasurementTests)359     HidlEnvironment(TestMode mode, bool enableDelayMeasurementTests) :
360         mode(mode), enableDelayMeasurementTests(enableDelayMeasurementTests) {};
361 
getServices()362     void getServices() {
363         manager = IServiceManager::getService();
364 
365         // alternatively:
366         // manager = defaultServiceManager()
367 
368         ASSERT_NE(manager, nullptr);
369         ASSERT_TRUE(manager->isRemote()); // manager is always remote
370 
371         tokenManager = ITokenManager::getService();
372         ASSERT_NE(tokenManager, nullptr);
373         ASSERT_TRUE(tokenManager->isRemote()); // tokenManager is always remote
374 
375         ashmemAllocator = IAllocator::getService("ashmem");
376         ASSERT_NE(ashmemAllocator, nullptr);
377         ASSERT_TRUE(ashmemAllocator->isRemote()); // allocator is always remote
378 
379         // getStub is true if we are in passthrough mode to skip checking
380         // binderized server, false for binderized mode.
381 
382         memoryTest = IMemoryTest::getService("memory", mode == PASSTHROUGH /* getStub */);
383         ASSERT_NE(memoryTest, nullptr);
384         ASSERT_EQ(memoryTest->isRemote(), mode == BINDERIZED);
385 
386         fetcher = IFetcher::getService("fetcher", mode == PASSTHROUGH /* getStub */);
387         ASSERT_NE(fetcher, nullptr);
388         ASSERT_EQ(fetcher->isRemote(), mode == BINDERIZED);
389 
390         foo = IFoo::getService("foo", mode == PASSTHROUGH /* getStub */);
391         ASSERT_NE(foo, nullptr);
392         ASSERT_EQ(foo->isRemote(), mode == BINDERIZED);
393 
394         baz = IBaz::getService("baz", mode == PASSTHROUGH /* getStub */);
395         ASSERT_NE(baz, nullptr);
396         ASSERT_EQ(baz->isRemote(), mode == BINDERIZED);
397 
398         dyingBaz = IBaz::getService("dyingBaz", mode == PASSTHROUGH /* getStub */);
399         ASSERT_NE(dyingBaz, nullptr);
400         ASSERT_EQ(dyingBaz->isRemote(), mode == BINDERIZED);
401 
402         bar = IBar::getService("foo", mode == PASSTHROUGH /* getStub */);
403         ASSERT_NE(bar, nullptr);
404         ASSERT_EQ(bar->isRemote(), mode == BINDERIZED);
405 
406         multithreadInterface =
407             IMultithread::getService("multithread", mode == PASSTHROUGH /* getStub */);
408         ASSERT_NE(multithreadInterface, nullptr);
409         ASSERT_EQ(multithreadInterface->isRemote(), mode == BINDERIZED);
410 
411         trieInterface = ITrie::getService("trie", mode == PASSTHROUGH /* getStub */);
412         ASSERT_NE(trieInterface, nullptr);
413         ASSERT_EQ(trieInterface->isRemote(), mode == BINDERIZED);
414 
415         cppSafeunionInterface =
416             ICppSafeUnion::getService("default", mode == PASSTHROUGH /* getStub */);
417         ASSERT_NE(cppSafeunionInterface, nullptr);
418         ASSERT_EQ(cppSafeunionInterface->isRemote(), mode == BINDERIZED);
419 
420         safeunionInterface = ISafeUnion::getService("safeunion", mode == PASSTHROUGH /* getStub */);
421         ASSERT_NE(safeunionInterface, nullptr);
422         ASSERT_EQ(safeunionInterface->isRemote(), mode == BINDERIZED);
423     }
424 
SetUp()425     void SetUp() override {
426         ALOGI("Environment setup beginning...");
427         getServices();
428         ALOGI("Environment setup complete.");
429     }
430 };
431 
432 class HidlTest : public ::testing::Test {
433 public:
434     sp<IServiceManager> manager;
435     sp<ITokenManager> tokenManager;
436     sp<IAllocator> ashmemAllocator;
437     sp<IMemoryTest> memoryTest;
438     sp<IFetcher> fetcher;
439     sp<IFoo> foo;
440     sp<IBaz> baz;
441     sp<IBaz> dyingBaz;
442     sp<IBar> bar;
443     sp<ITrie> trieInterface;
444     sp<ICppSafeUnion> cppSafeunionInterface;
445     sp<ISafeUnion> safeunionInterface;
446     TestMode mode = TestMode::PASSTHROUGH;
447 
SetUp()448     void SetUp() override {
449         ALOGI("Test setup beginning...");
450         manager = gHidlEnvironment->manager;
451         tokenManager = gHidlEnvironment->tokenManager;
452         ashmemAllocator = gHidlEnvironment->ashmemAllocator;
453         memoryTest = gHidlEnvironment->memoryTest;
454         fetcher = gHidlEnvironment->fetcher;
455         foo = gHidlEnvironment->foo;
456         baz = gHidlEnvironment->baz;
457         dyingBaz = gHidlEnvironment->dyingBaz;
458         bar = gHidlEnvironment->bar;
459         trieInterface = gHidlEnvironment->trieInterface;
460         cppSafeunionInterface = gHidlEnvironment->cppSafeunionInterface;
461         safeunionInterface = gHidlEnvironment->safeunionInterface;
462         mode = gHidlEnvironment->mode;
463         ALOGI("Test setup complete");
464     }
465 };
466 
TEST_F(HidlTest,ToStringTest)467 TEST_F(HidlTest, ToStringTest) {
468     using namespace android::hardware;
469 
470     LOG(INFO) << toString(IFoo::Everything{});
471 
472     // Note that handles don't need to be deleted because MQDescriptor takes ownership
473     // and deletes them when destructed.
474     auto handle = native_handle_create(0, 1);
475     auto handle2 = native_handle_create(0, 1);
476     handle->data[0] = 5;
477     handle2->data[0] = 6;
478     IFoo::Everything e{
479         .u = {.number = 3},
480         .number = 10,
481         .h = handle,
482         .descSync = {std::vector<GrantorDescriptor>(), handle, 5},
483         .descUnsync = {std::vector<GrantorDescriptor>(), handle2, 6},
484         .mem = hidl_memory("mymem", handle, 5),
485         .p = reinterpret_cast<void*>(0x6),
486         .vs = {"hello", "world"},
487         .multidimArray = hidl_vec<hidl_string>{"hello", "great", "awesome", "nice"}.data(),
488         .sArray = hidl_vec<hidl_string>{"awesome", "thanks", "you're welcome"}.data(),
489         .anotherStruct = {.first = "first", .last = "last"},
490         .bf = IFoo::BitField::V0 | IFoo::BitField::V2};
491     LOG(INFO) << toString(e);
492     LOG(INFO) << toString(foo);
493     // toString is for debugging purposes only; no good EXPECT
494     // statement can be written here.
495 }
496 
TEST_F(HidlTest,PrintToTest)497 TEST_F(HidlTest, PrintToTest) {
498     using namespace android::hardware::tests;
499     using ::testing::PrintToString;
500 
501     trie::V1_0::TrieNode trieNode;
502     trieNode.isTerminal = true;
503     LOG(INFO) << PrintToString(trieNode);
504 
505     // The exact contents of the string are for debugging purposes, but to be
506     // friendly it should provide a name for the boolean field.
507     EXPECT_TRUE(PrintToString(trieNode).find("isTerminal") != std::string::npos);
508 
509     LOG(INFO) << PrintToString(trie::V1_0::E1::OK);
510     LOG(INFO) << PrintToString(trie::V1_0::E1::ANOTHER);
511     LOG(INFO) << PrintToString(trie::V1_0::E2::ACCEPT);
512 
513     // The exact contents of the string are for debugging purposes, but to be
514     // friendly it should provide a name for each enum value.
515     EXPECT_TRUE(PrintToString(trie::V1_0::E1::OK).find("OK") != std::string::npos);
516     EXPECT_TRUE(PrintToString(trie::V1_0::E1::ANOTHER).find("ANOTHER") != std::string::npos);
517     EXPECT_TRUE(PrintToString(trie::V1_0::E2::ACCEPT).find("ACCEPT") != std::string::npos);
518 }
519 
TEST_F(HidlTest,ConstantExpressionTest)520 TEST_F(HidlTest, ConstantExpressionTest) {
521     // these tests are written so that these always evaluate to one
522 
523     for (const auto value : hidl_enum_range<IExpression::OperatorSanityCheck>()) {
524         EXPECT_EQ(1, static_cast<int32_t>(value));
525     }
526     for (const auto value : hidl_enum_range<IExpression::EnumTagTest>()) {
527         EXPECT_EQ(1, static_cast<int32_t>(value));
528     }
529 }
530 
TEST_F(HidlTest,PassthroughLookupTest)531 TEST_F(HidlTest, PassthroughLookupTest) {
532     // IFoo is special because it returns an interface no matter
533     //   what instance name is requested. In general, this is BAD!
534     EXPECT_NE(nullptr, IFoo::getService("", true /* getStub */).get());
535     EXPECT_NE(nullptr, IFoo::getService("a", true /* getStub */).get());
536     EXPECT_NE(nullptr, IFoo::getService("asdf", true /* getStub */).get());
537     EXPECT_NE(nullptr, IFoo::getService("::::::::", true /* getStub */).get());
538     EXPECT_NE(nullptr, IFoo::getService("/////", true /* getStub */).get());
539     EXPECT_NE(nullptr, IFoo::getService("\n", true /* getStub */).get());
540 }
541 
TEST_F(HidlTest,EnumIteratorTest)542 TEST_F(HidlTest, EnumIteratorTest) {
543     using Empty = ::android::hardware::tests::foo::V1_0::EnumIterators::Empty;
544     using Grandchild = ::android::hardware::tests::foo::V1_0::EnumIterators::Grandchild;
545     using SkipsValues = ::android::hardware::tests::foo::V1_0::EnumIterators::SkipsValues;
546     using MultipleValues = ::android::hardware::tests::foo::V1_0::EnumIterators::MultipleValues;
547 
548     for (const auto value : hidl_enum_range<Empty>()) {
549         (void)value;
550         ADD_FAILURE() << "Empty range should not iterate";
551     }
552 
553     EXPECT_EQ(hidl_enum_range<Grandchild>().begin(), hidl_enum_range<Grandchild>().cbegin());
554     EXPECT_EQ(hidl_enum_range<Grandchild>().end(), hidl_enum_range<Grandchild>().cend());
555     EXPECT_EQ(hidl_enum_range<Grandchild>().rbegin(), hidl_enum_range<Grandchild>().crbegin());
556     EXPECT_EQ(hidl_enum_range<Grandchild>().rend(), hidl_enum_range<Grandchild>().crend());
557 
558     auto it1 = hidl_enum_range<Grandchild>().begin();
559     EXPECT_EQ(Grandchild::A, *it1++);
560     EXPECT_EQ(Grandchild::B, *it1++);
561     EXPECT_EQ(hidl_enum_range<Grandchild>().end(), it1);
562     auto it1r = hidl_enum_range<Grandchild>().rbegin();
563     EXPECT_EQ(Grandchild::B, *it1r++);
564     EXPECT_EQ(Grandchild::A, *it1r++);
565     EXPECT_EQ(hidl_enum_range<Grandchild>().rend(), it1r);
566 
567     auto it2 = hidl_enum_range<SkipsValues>().begin();
568     EXPECT_EQ(SkipsValues::A, *it2++);
569     EXPECT_EQ(SkipsValues::B, *it2++);
570     EXPECT_EQ(SkipsValues::C, *it2++);
571     EXPECT_EQ(SkipsValues::D, *it2++);
572     EXPECT_EQ(SkipsValues::E, *it2++);
573     EXPECT_EQ(hidl_enum_range<SkipsValues>().end(), it2);
574     auto it2r = hidl_enum_range<SkipsValues>().rbegin();
575     EXPECT_EQ(SkipsValues::E, *it2r++);
576     EXPECT_EQ(SkipsValues::D, *it2r++);
577     EXPECT_EQ(SkipsValues::C, *it2r++);
578     EXPECT_EQ(SkipsValues::B, *it2r++);
579     EXPECT_EQ(SkipsValues::A, *it2r++);
580     EXPECT_EQ(hidl_enum_range<SkipsValues>().rend(), it2r);
581 
582     auto it3 = hidl_enum_range<MultipleValues>().begin();
583     EXPECT_EQ(MultipleValues::A, *it3++);
584     EXPECT_EQ(MultipleValues::B, *it3++);
585     EXPECT_EQ(MultipleValues::C, *it3++);
586     EXPECT_EQ(MultipleValues::D, *it3++);
587     EXPECT_EQ(hidl_enum_range<MultipleValues>().end(), it3);
588     auto it3r = hidl_enum_range<MultipleValues>().rbegin();
589     EXPECT_EQ(MultipleValues::D, *it3r++);
590     EXPECT_EQ(MultipleValues::C, *it3r++);
591     EXPECT_EQ(MultipleValues::B, *it3r++);
592     EXPECT_EQ(MultipleValues::A, *it3r++);
593     EXPECT_EQ(hidl_enum_range<MultipleValues>().rend(), it3r);
594 }
595 
TEST_F(HidlTest,EnumToStringTest)596 TEST_F(HidlTest, EnumToStringTest) {
597     using namespace std::string_literals;
598     using ::android::hardware::tests::foo::V1_0::toString;
599     // toString for enum
600     EXPECT_EQ(toString(IFoo::BitField::V0), "V0"s);
601     EXPECT_EQ(toString(static_cast<IFoo::BitField>(0)), "0"s)
602             << "Invalid enum isn't stringified correctly.";
603     EXPECT_EQ(toString(static_cast<IFoo::BitField>(IFoo::BitField::V0 | IFoo::BitField::V2)), "0x5"s)
604             << "Invalid enum isn't stringified correctly.";
605     // dump bitfields
606     EXPECT_EQ(toString<IFoo::BitField>((uint8_t)0 | IFoo::BitField::V0), "V0 (0x1)"s);
607     EXPECT_EQ(toString<IFoo::BitField>((uint8_t)0 | IFoo::BitField::V0 | IFoo::BitField::V2),
608               "V0 | V2 (0x5)"s);
609     EXPECT_EQ(toString<IFoo::BitField>((uint8_t)0xF), "V0 | V1 | V2 | V3 | VALL (0xf)"s);
610     EXPECT_EQ(toString<IFoo::BitField>((uint8_t)0xFF), "V0 | V1 | V2 | V3 | VALL | 0xf0 (0xff)"s);
611 
612     // inheritance
613     using Parent = ::android::hardware::tests::foo::V1_0::EnumIterators::Parent;
614     using EmptyChild = ::android::hardware::tests::foo::V1_0::EnumIterators::EmptyChild;
615     using Grandchild = ::android::hardware::tests::foo::V1_0::EnumIterators::Grandchild;
616     EXPECT_EQ(toString(Parent::A), "A"s);
617     EXPECT_EQ(toString(EmptyChild::A), "A"s);
618     EXPECT_EQ(toString(Grandchild::A), "A"s);
619     EXPECT_EQ(toString(Grandchild::B), "B"s);
620 }
621 
TEST_F(HidlTest,PingTest)622 TEST_F(HidlTest, PingTest) {
623     EXPECT_OK(manager->ping());
624 }
625 
TEST_F(HidlTest,TryGetServiceTest)626 TEST_F(HidlTest, TryGetServiceTest) {
627     sp<IServiceManager> dne = IServiceManager::tryGetService("boss");
628     ASSERT_EQ(dne, nullptr);
629 
630     sp<IServiceManager> manager = IServiceManager::tryGetService();
631     ASSERT_NE(manager, nullptr);
632 }
633 
TEST_F(HidlTest,ServiceListTest)634 TEST_F(HidlTest, ServiceListTest) {
635     static const std::set<std::string> binderizedSet = {
636         "android.hardware.tests.bar@1.0::IBar/foo",
637         "android.hardware.tests.inheritance@1.0::IFetcher/fetcher",
638         "android.hardware.tests.inheritance@1.0::IParent/parent",
639         "android.hardware.tests.inheritance@1.0::IParent/child",
640         "android.hardware.tests.inheritance@1.0::IChild/child",
641         "android.hardware.tests.inheritance@1.0::IGrandparent/child",
642         "android.hardware.tests.foo@1.0::IFoo/foo",
643         "android.hidl.manager@1.0::IServiceManager/default",
644         "android.hidl.manager@1.1::IServiceManager/default",
645     };
646 
647     static const std::set<std::string> passthroughSet = {
648         "android.hidl.manager@1.0::IServiceManager/default",
649         "android.hidl.manager@1.1::IServiceManager/default",
650     };
651 
652     std::set<std::string> activeSet;
653 
654     switch(mode) {
655         case BINDERIZED: {
656             activeSet = binderizedSet;
657         } break;
658 
659         case PASSTHROUGH: {
660             activeSet = passthroughSet;
661         } break;
662         default:
663             EXPECT_TRUE(false) << "unrecognized mode";
664     }
665 
666     EXPECT_OK(manager->list([&activeSet](const hidl_vec<hidl_string> &registered){
667         std::set<std::string> registeredSet;
668 
669         for (size_t i = 0; i < registered.size(); i++) {
670             registeredSet.insert(registered[i]);
671         }
672 
673         std::set<std::string> difference;
674         std::set_difference(activeSet.begin(), activeSet.end(),
675                             registeredSet.begin(), registeredSet.end(),
676                             std::inserter(difference, difference.begin()));
677 
678         EXPECT_EQ(difference.size(), 0u) << "service(s) not registered " << to_string(difference);
679     }));
680 }
681 
TEST_F(HidlTest,ServiceListByInterfaceTest)682 TEST_F(HidlTest, ServiceListByInterfaceTest) {
683     if (mode != BINDERIZED) {
684         // passthrough service manager does not know about services
685         return;
686     }
687 
688     EXPECT_OK(
689         manager->listByInterface(IParent::descriptor, [](const hidl_vec<hidl_string>& registered) {
690             std::set<std::string> registeredSet;
691 
692             for (size_t i = 0; i < registered.size(); i++) {
693                 registeredSet.insert(registered[i]);
694             }
695 
696             std::set<std::string> activeSet = {"parent", "child"};
697             std::set<std::string> difference;
698             std::set_difference(activeSet.begin(), activeSet.end(), registeredSet.begin(),
699                                 registeredSet.end(), std::inserter(difference, difference.begin()));
700 
701             EXPECT_EQ(difference.size(), 0u)
702                 << "service(s) not registered " << to_string(difference);
703         }));
704 }
705 
TEST_F(HidlTest,ServiceListManifestByInterfaceTest)706 TEST_F(HidlTest, ServiceListManifestByInterfaceTest) {
707     // system service
708     EXPECT_OK(manager->listManifestByInterface(IServiceManager::descriptor,
709                                                [](const hidl_vec<hidl_string>& registered) {
710                                                    ASSERT_EQ(1, registered.size());
711                                                    EXPECT_EQ("default", registered[0]);
712                                                }));
713 
714     // test service that will never be in a manifest
715     EXPECT_OK(manager->listManifestByInterface(
716         IParent::descriptor,
717         [](const hidl_vec<hidl_string>& registered) { ASSERT_EQ(0, registered.size()); }));
718     // invalid service
719     EXPECT_OK(manager->listManifestByInterface(
720         "!(*#&$ASDASLKDJasdlkjfads",
721         [](const hidl_vec<hidl_string>& registered) { ASSERT_EQ(0, registered.size()); }));
722 }
723 
TEST_F(HidlTest,SubInterfaceServiceRegistrationTest)724 TEST_F(HidlTest, SubInterfaceServiceRegistrationTest) {
725     using ::android::hardware::interfacesEqual;
726 
727     const std::string kInstanceName = "no-matter-what-it-is";
728     const std::string kOtherName = "something-different";
729 
730     sp<IChild> child = new SimpleChild();
731     sp<IParent> parent = new SimpleParent();
732 
733     EXPECT_EQ(::android::OK, child->registerAsService(kInstanceName));
734     EXPECT_EQ(::android::OK, child->registerAsService(kOtherName));
735 
736     EXPECT_TRUE(interfacesEqual(child, IChild::getService(kInstanceName)));
737     EXPECT_TRUE(interfacesEqual(child, IParent::getService(kInstanceName)));
738 
739     EXPECT_EQ(::android::OK, parent->registerAsService(kInstanceName));
740 
741     // FALSE since passthrough HAL will return an instance
742     // since binderized instance is nullptr
743     EXPECT_FALSE(interfacesEqual(parent, IChild::getService(kInstanceName)));
744     EXPECT_TRUE(interfacesEqual(parent, IParent::getService(kInstanceName)));
745 
746     // other instance name is unchanged
747     EXPECT_TRUE(interfacesEqual(child, IChild::getService(kOtherName)));
748     EXPECT_TRUE(interfacesEqual(child, IParent::getService(kOtherName)));
749 }
750 
TEST_F(HidlTest,ServiceNotificationTest)751 TEST_F(HidlTest, ServiceNotificationTest) {
752     if (mode != BINDERIZED) {
753         // service notifications aren't supported in passthrough mode
754         return;
755     }
756 
757     ServiceNotification* notification = new ServiceNotification();
758 
759     std::string instanceName = "test-instance";
760     EXPECT_TRUE(IParent::registerForNotifications(instanceName, notification));
761 
762     EXPECT_EQ(::android::OK, (new SimpleChild())->registerAsService(instanceName));
763     EXPECT_EQ(::android::OK, (new SimpleParent())->registerAsService(instanceName));
764 
765     std::unique_lock<std::mutex> lock(notification->mutex);
766 
767     notification->condition.wait_for(lock, std::chrono::milliseconds(500), [&notification]() {
768         return notification->getRegistrations().size() >= 2;
769     });
770 
771     std::vector<std::string> registrations = notification->getRegistrations();
772 
773     EXPECT_EQ(registrations.size(), 2u);
774 
775     EXPECT_EQ(to_string(registrations.data(), registrations.size()),
776               std::string("['") + IParent::descriptor + "/" + instanceName + "', '" +
777                   IParent::descriptor + "/" + instanceName + "']");
778 }
779 
TEST_F(HidlTest,ServiceUnregisterTest)780 TEST_F(HidlTest, ServiceUnregisterTest) {
781     const std::string instance = "some-instance-name";
782 
783     sp<ServiceNotification> sNotification = new ServiceNotification();
784 
785     // unregister all
786     EXPECT_TRUE(IParent::registerForNotifications(instance, sNotification));
787     EXPECT_TRUE(manager->unregisterForNotifications("", "", sNotification));
788 
789     // unregister all with instance name
790     EXPECT_TRUE(IParent::registerForNotifications(instance, sNotification));
791     EXPECT_TRUE(manager->unregisterForNotifications(IParent::descriptor, "", sNotification));
792 
793     // unregister package listener
794     EXPECT_TRUE(IParent::registerForNotifications("", sNotification));
795     EXPECT_TRUE(manager->unregisterForNotifications(IParent::descriptor, "", sNotification));
796 
797     // unregister listener for specific service and name
798     EXPECT_TRUE(IParent::registerForNotifications(instance, sNotification));
799     EXPECT_TRUE(manager->unregisterForNotifications(IParent::descriptor, instance, sNotification));
800 
801     EXPECT_FALSE(manager->unregisterForNotifications("", "", sNotification));
802 
803     // TODO(b/32837397): remote destructor is lazy
804     // wp<ServiceNotification> wNotification = sNotification;
805     // sNotification = nullptr;
806     // EXPECT_EQ(nullptr, wNotification.promote().get());
807 }
808 
TEST_F(HidlTest,ServiceAllNotificationTest)809 TEST_F(HidlTest, ServiceAllNotificationTest) {
810     ServiceNotification* notification = new ServiceNotification();
811 
812     std::string instanceOne = "test-instance-one";
813     std::string instanceTwo = "test-instance-two";
814     EXPECT_TRUE(ISimple::registerForNotifications("", notification));
815 
816     Simple* instanceA = new Simple(1);
817     EXPECT_EQ(::android::OK, instanceA->registerAsService(instanceOne));
818     Simple* instanceB = new Simple(2);
819     EXPECT_EQ(::android::OK, instanceB->registerAsService(instanceTwo));
820 
821     std::unique_lock<std::mutex> lock(notification->mutex);
822 
823     notification->condition.wait_for(lock, std::chrono::milliseconds(500), [&notification]() {
824         return notification->getRegistrations().size() >= 2;
825     });
826 
827     std::vector<std::string> registrations = notification->getRegistrations();
828     std::sort(registrations.begin(), registrations.end());
829 
830     EXPECT_EQ(registrations.size(), 2u);
831 
832     std::string descriptor = ISimple::descriptor;
833 
834     EXPECT_EQ(
835         to_string(registrations.data(), registrations.size()),
836         "['" + descriptor + "/" + instanceOne + "', '" + descriptor + "/" + instanceTwo + "']");
837 }
838 
TEST_F(HidlTest,DebugDumpTest)839 TEST_F(HidlTest, DebugDumpTest) {
840     EXPECT_OK(manager->debugDump([](const auto& list) {
841         for (const auto& debugInfo : list) {
842             FQName name;
843             EXPECT_TRUE(FQName::parse(debugInfo.interfaceName, &name)) << debugInfo.interfaceName;
844             EXPECT_TRUE(debugInfo.instanceName.size() > 0);
845         }
846     }));
847 }
848 
TEST_F(HidlTest,InterfacesEqualTest)849 TEST_F(HidlTest, InterfacesEqualTest) {
850     using android::hardware::interfacesEqual;
851 
852     sp<IParent> service1 = IParent::getService("child", mode == PASSTHROUGH /* getStub */);
853     sp<IParent> service2 = service1;
854 
855     // Passthrough services are reinstantiated whenever getService is called.
856     if (mode == BINDERIZED) {
857         service2 = IParent::getService("child");
858     }
859 
860     EXPECT_NE(nullptr, service1.get());
861     EXPECT_NE(nullptr, service2.get());
862     EXPECT_TRUE(interfacesEqual(service1, service2));
863 
864     sp<IChild> child = IChild::castFrom(service1);
865     EXPECT_NE(nullptr, child.get());  // it is actually a child
866 
867     EXPECT_TRUE(interfacesEqual(service1, child));
868     EXPECT_TRUE(interfacesEqual(service2, child));
869 }
870 
TEST_F(HidlTest,TestToken)871 TEST_F(HidlTest, TestToken) {
872     using android::hardware::interfacesEqual;
873 
874     Return<void> ret = tokenManager->createToken(manager, [&] (const hidl_vec<uint8_t> &token) {
875         Return<sp<IBase>> retService = tokenManager->get(token);
876         EXPECT_OK(retService);
877         if (retService.isOk()) {
878             sp<IBase> service = retService;
879             EXPECT_NE(nullptr, service.get());
880             sp<IServiceManager> retManager = IServiceManager::castFrom(service);
881 
882             EXPECT_TRUE(interfacesEqual(manager, retManager));
883         }
884 
885         Return<bool> unregisterRet = tokenManager->unregister(token);
886 
887         EXPECT_OK(unregisterRet);
888         if (unregisterRet.isOk()) {
889             EXPECT_TRUE(unregisterRet);
890         }
891     });
892     EXPECT_OK(ret);
893 }
894 
TEST_F(HidlTest,TestSharedMemory)895 TEST_F(HidlTest, TestSharedMemory) {
896     const uint8_t kValue = 0xCA;
897     hidl_memory mem_copy;
898     EXPECT_OK(ashmemAllocator->allocate(1024, [&](bool success, const hidl_memory& mem) {
899         EXPECT_EQ(success, true);
900 
901         sp<IMemory> memory = mapMemory(mem);
902 
903         EXPECT_NE(memory, nullptr);
904 
905         uint8_t* data = static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
906         EXPECT_NE(data, nullptr);
907 
908         EXPECT_EQ(memory->getSize(), mem.size());
909 
910         memory->update();
911         memset(data, 0, memory->getSize());
912         memory->commit();
913 
914         mem_copy = mem;
915         memoryTest->fillMemory(mem, kValue);
916 
917         memory->read();
918         for (size_t i = 0; i < mem.size(); i++) {
919             EXPECT_EQ(kValue, data[i]);
920         }
921         memory->commit();
922     }));
923 
924     // Test the memory persists after the call
925     sp<IMemory> memory = mapMemory(mem_copy);
926 
927     EXPECT_NE(memory, nullptr);
928 
929     uint8_t* data = static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
930     EXPECT_NE(data, nullptr);
931 
932     memory->read();
933     for (size_t i = 0; i < mem_copy.size(); i++) {
934         EXPECT_EQ(kValue, data[i]);
935     }
936     memory->commit();
937 
938     hidl_memory mem_move(std::move(mem_copy));
939     ASSERT_EQ(nullptr, mem_copy.handle());
940     ASSERT_EQ(0UL, mem_copy.size());
941     ASSERT_EQ("", mem_copy.name());
942 
943     memory.clear();
944     memory = mapMemory(mem_move);
945 
946     EXPECT_NE(memory, nullptr);
947 
948     data = static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
949     EXPECT_NE(data, nullptr);
950 
951     memory->read();
952     for (size_t i = 0; i < mem_move.size(); i++) {
953         EXPECT_EQ(kValue, data[i]);
954     }
955     memory->commit();
956 }
957 
TEST_F(HidlTest,BatchSharedMemory)958 TEST_F(HidlTest, BatchSharedMemory) {
959     const uint8_t kValue = 0xCA;
960     const uint64_t kBatchSize = 2;
961     hidl_vec<hidl_memory> batchCopy;
962 
963     ASSERT_TRUE(ashmemAllocator
964                         ->batchAllocate(1024, kBatchSize,
965                                         [&](bool success, const hidl_vec<hidl_memory>& batch) {
966                                             ASSERT_TRUE(success);
967                                             EXPECT_EQ(kBatchSize, batch.size());
968 
969                                             for (uint64_t i = 0; i < batch.size(); i++) {
970                                                 sp<IMemory> memory = mapMemory(batch[i]);
971 
972                                                 EXPECT_NE(nullptr, memory.get());
973 
974                                                 uint8_t* data = static_cast<uint8_t*>(
975                                                         static_cast<void*>(memory->getPointer()));
976                                                 EXPECT_NE(nullptr, data);
977 
978                                                 EXPECT_EQ(memory->getSize(), batch[i].size());
979 
980                                                 memory->update();
981                                                 memset(data, kValue, memory->getSize());
982                                                 memory->commit();
983                                             }
984 
985                                             batchCopy = batch;
986                                         })
987                         .isOk());
988 
989     for (uint64_t i = 0; i < batchCopy.size(); i++) {
990         // Test the memory persists after the call
991         sp<IMemory> memory = mapMemory(batchCopy[i]);
992 
993         ASSERT_NE(memory, nullptr);
994 
995         uint8_t* data = static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
996         ASSERT_NE(data, nullptr);
997 
998         memory->read();
999 
1000         for (size_t k = 0; k < batchCopy[i].size(); k++) {
1001             EXPECT_EQ(kValue, data[k]);
1002         }
1003         memory->commit();
1004     }
1005 }
1006 
TEST_F(HidlTest,MemoryBlock)1007 TEST_F(HidlTest, MemoryBlock) {
1008     const uint8_t kValue = 0xCA;
1009     using ::android::hardware::IBinder;
1010     using ::android::hardware::interfacesEqual;
1011     using ::android::hardware::toBinder;
1012 
1013     sp<HidlMemory> mem;
1014     EXPECT_OK(ashmemAllocator->allocate(1024, [&](bool success, const hidl_memory& _mem) {
1015         ASSERT_TRUE(success);
1016         mem = HidlMemory::getInstance(_mem);
1017     }));
1018     memoryTest->set(*mem);
1019     Return<sp<IMemoryToken>> tokenRet = memoryTest->get();
1020     EXPECT_OK(tokenRet);
1021     sp<IMemoryToken> token = tokenRet;
1022     EXPECT_NE(nullptr, token.get());
1023     EXPECT_OK(token->get([&](const hidl_memory& mem) {
1024         sp<IMemory> memory = mapMemory(mem);
1025 
1026         EXPECT_NE(nullptr, memory.get());
1027 
1028         uint8_t* data = static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
1029         EXPECT_NE(data, nullptr);
1030 
1031         EXPECT_EQ(memory->getSize(), mem.size());
1032 
1033         memory->update();
1034         memset(data, 0, memory->getSize());
1035         memory->commit();
1036 
1037         memoryTest->fillMemory(mem, kValue);
1038         memory->commit();
1039     }));
1040     MemoryBlock blk = {token, 0x200 /* size */, 0x100 /* offset */};
1041     EXPECT_OK(memoryTest->haveSomeMemoryBlock(blk, [&](const MemoryBlock& blkBack) {
1042         sp<IMemoryToken> tokenBack = blkBack.token;
1043         EXPECT_TRUE(interfacesEqual(token, tokenBack));
1044         EXPECT_EQ(blkBack.size, 0x200ULL);
1045         EXPECT_EQ(blkBack.offset, 0x100ULL);
1046         blk = blkBack;
1047     }));
1048 
1049     sp<IMemoryToken> mtoken = blk.token;
1050     mtoken->get([&](const hidl_memory& mem) {
1051         sp<IMemory> memory = mapMemory(mem);
1052         uint8_t* data = static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
1053         EXPECT_NE(data, nullptr);
1054         for (size_t i = 0; i < mem.size(); i++) {
1055             EXPECT_EQ(kValue, data[i]);
1056         }
1057     });
1058 }
1059 
TEST_F(HidlTest,NullSharedMemory)1060 TEST_F(HidlTest, NullSharedMemory) {
1061     hidl_memory memory{};
1062 
1063     EXPECT_EQ(nullptr, memory.handle());
1064 
1065     EXPECT_OK(memoryTest->haveSomeMemory(memory, [&](const hidl_memory &mem) {
1066         EXPECT_EQ(nullptr, mem.handle());
1067     }));
1068 }
1069 
TEST_F(HidlTest,FooGetDescriptorTest)1070 TEST_F(HidlTest, FooGetDescriptorTest) {
1071     EXPECT_OK(foo->interfaceDescriptor([&] (const auto &desc) {
1072         EXPECT_EQ(desc, mode == BINDERIZED
1073                 ? IBar::descriptor // service is actually IBar in binderized mode
1074                 : IFoo::descriptor); // dlopened, so service is IFoo
1075     }));
1076 }
1077 
TEST_F(HidlTest,FooConvertToBoolIfSmallTest)1078 TEST_F(HidlTest, FooConvertToBoolIfSmallTest) {
1079     hidl_vec<IFoo::Union> u = {
1080         {.intValue = 7}, {.intValue = 0}, {.intValue = 1}, {.intValue = 8},
1081     };
1082     EXPECT_OK(foo->convertToBoolIfSmall(IFoo::Discriminator::INT, u, [&](const auto& res) {
1083         ASSERT_EQ(4u, res.size());
1084         EXPECT_EQ(IFoo::Discriminator::INT, res[0].discriminator);
1085         EXPECT_EQ(u[0].intValue, res[0].value.intValue);
1086         EXPECT_EQ(IFoo::Discriminator::BOOL, res[1].discriminator);
1087         EXPECT_EQ(static_cast<bool>(u[1].intValue), res[1].value.boolValue);
1088         EXPECT_EQ(IFoo::Discriminator::BOOL, res[2].discriminator);
1089         EXPECT_EQ(static_cast<bool>(u[2].intValue), res[2].value.boolValue);
1090         EXPECT_EQ(IFoo::Discriminator::INT, res[3].discriminator);
1091         EXPECT_EQ(u[3].intValue, res[3].value.intValue);
1092     }));
1093 }
1094 
TEST_F(HidlTest,FooDoThisTest)1095 TEST_F(HidlTest, FooDoThisTest) {
1096     ALOGI("CLIENT call doThis.");
1097     EXPECT_OK(foo->doThis(1.0f));
1098     ALOGI("CLIENT doThis returned.");
1099 }
1100 
TEST_F(HidlTest,FooDoThatAndReturnSomethingTest)1101 TEST_F(HidlTest, FooDoThatAndReturnSomethingTest) {
1102     ALOGI("CLIENT call doThatAndReturnSomething.");
1103     int32_t result = foo->doThatAndReturnSomething(2.0f);
1104     ALOGI("CLIENT doThatAndReturnSomething returned %d.", result);
1105     EXPECT_EQ(result, 666);
1106 }
1107 
TEST_F(HidlTest,FooDoQuiteABitTest)1108 TEST_F(HidlTest, FooDoQuiteABitTest) {
1109     ALOGI("CLIENT call doQuiteABit");
1110     double something = foo->doQuiteABit(1, 2, 3.0f, 4.0);
1111     ALOGI("CLIENT doQuiteABit returned %f.", something);
1112     EXPECT_DOUBLE_EQ(something, 666.5);
1113 }
1114 
TEST_F(HidlTest,FooDoSomethingElseTest)1115 TEST_F(HidlTest, FooDoSomethingElseTest) {
1116 
1117     ALOGI("CLIENT call doSomethingElse");
1118     hidl_array<int32_t, 15> param;
1119     for (size_t i = 0; i < sizeof(param) / sizeof(param[0]); ++i) {
1120         param[i] = i;
1121     }
1122     EXPECT_OK(foo->doSomethingElse(param, [&](const auto &something) {
1123             ALOGI("CLIENT doSomethingElse returned %s.",
1124                   to_string(something).c_str());
1125             int32_t expect[] = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24,
1126                 26, 28, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1, 2};
1127             EXPECT_TRUE(isArrayEqual(something, expect, 32));
1128         }));
1129 }
1130 
TEST_F(HidlTest,FooDoStuffAndReturnAStringTest)1131 TEST_F(HidlTest, FooDoStuffAndReturnAStringTest) {
1132     ALOGI("CLIENT call doStuffAndReturnAString");
1133     EXPECT_OK(foo->doStuffAndReturnAString([&](const auto &something) {
1134             ALOGI("CLIENT doStuffAndReturnAString returned '%s'.",
1135                   something.c_str());
1136             EXPECT_STREQ(something.c_str(), "Hello, world");
1137             EXPECT_EQ(strlen("Hello, world"), something.size());
1138         }));
1139 }
1140 
TEST_F(HidlTest,FooMapThisVectorTest)1141 TEST_F(HidlTest, FooMapThisVectorTest) {
1142     hidl_vec<int32_t> vecParam;
1143     vecParam.resize(10);
1144     for (size_t i = 0; i < 10; ++i) {
1145         vecParam[i] = i;
1146     }
1147     EXPECT_OK(foo->mapThisVector(vecParam, [&](const auto &something) {
1148             ALOGI("CLIENT mapThisVector returned %s.",
1149                   to_string(something).c_str());
1150             int32_t expect[] = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18};
1151             EXPECT_TRUE(isArrayEqual(something, expect, something.size()));
1152         }));
1153 }
1154 
TEST_F(HidlTest,WrapTest)1155 TEST_F(HidlTest, WrapTest) {
1156     if (!gHidlEnvironment->enableDelayMeasurementTests) {
1157         return;
1158     }
1159 
1160     using ::android::hardware::tests::foo::V1_0::BnHwSimple;
1161     using ::android::hardware::tests::foo::V1_0::BsSimple;
1162     using ::android::hardware::tests::foo::V1_0::BpHwSimple;
1163     using ::android::hardware::details::HidlInstrumentor;
1164     nsecs_t now;
1165     int i = 0;
1166 
1167     now = systemTime();
1168     new BnHwSimple(new Simple(1));
1169     EXPECT_LT(systemTime() - now, 2000000) << "    for BnHwSimple(nonnull)";
1170 
1171     now = systemTime();
1172     new BnHwSimple(nullptr);
1173     EXPECT_LT(systemTime() - now, 2000000) << "    for BnHwSimple(null)";
1174 
1175     now = systemTime();
1176     new BsSimple(new Simple(1));
1177     EXPECT_LT(systemTime() - now, 2000000) << "    for BsSimple(nonnull)";
1178 
1179     now = systemTime();
1180     new BsSimple(nullptr);
1181     EXPECT_LT(systemTime() - now, 2000000) << "    for BsSimple(null)";
1182 
1183     now = systemTime();
1184     new BpHwSimple(nullptr);
1185     EXPECT_LT(systemTime() - now, 2000000) << "    for BpHwSimple(null)";
1186 
1187     now = systemTime();
1188     new ::android::hardware::details::HidlInstrumentor("", "");
1189     EXPECT_LT(systemTime() - now, 2000000) << "    for HidlInstrumentor";
1190 
1191     now = systemTime();
1192     i++;
1193     EXPECT_LT(systemTime() - now,    1000) << "    for nothing";
1194 }
1195 
TEST_F(HidlTest,FooCallMeTest)1196 TEST_F(HidlTest, FooCallMeTest) {
1197     if (!gHidlEnvironment->enableDelayMeasurementTests) {
1198         return;
1199     }
1200     sp<IFooCallback> fooCb = new FooCallback();
1201     ALOGI("CLIENT call callMe.");
1202     // callMe is oneway, should return instantly.
1203     nsecs_t now;
1204     now = systemTime();
1205     EXPECT_OK(foo->callMe(fooCb));
1206     EXPECT_LT(systemTime() - now, ONEWAY_TOLERANCE_NS);
1207     ALOGI("CLIENT callMe returned.");
1208 
1209     // Bar::callMe will invoke three methods on FooCallback; one will return
1210     // right away (even though it is a two-way method); the second one will
1211     // block Bar for DELAY_S seconds, and the third one will return
1212     // to Bar right away (is oneway) but will itself block for DELAY_S seconds.
1213     // We need a way to make sure that these three things have happened within
1214     // 2*DELAY_S seconds plus some small tolerance.
1215     //
1216     // Method FooCallback::reportResults() takes a timeout parameter.  It blocks for
1217     // that length of time, while waiting for the three methods above to
1218     // complete.  It returns the information of whether each method was invoked,
1219     // as well as how long the body of the method took to execute.  We verify
1220     // the information returned by reportResults() against the timeout we pass (which
1221     // is long enough for the method bodies to execute, plus tolerance), and
1222     // verify that eachof them executed, as expected, and took the length of
1223     // time to execute that we also expect.
1224 
1225     const nsecs_t waitNs =
1226         3 * DELAY_NS + TOLERANCE_NS;
1227     const nsecs_t reportResultsNs =
1228         2 * DELAY_NS + TOLERANCE_NS;
1229 
1230     ALOGI("CLIENT: Waiting for up to %" PRId64 " seconds.",
1231           nanoseconds_to_seconds(waitNs));
1232 
1233     fooCb->reportResults(waitNs,
1234                 [&](int64_t timeLeftNs,
1235                     const hidl_array<IFooCallback::InvokeInfo, 3> &invokeResults) {
1236         ALOGI("CLIENT: FooCallback::reportResults() is returning data.");
1237         ALOGI("CLIENT: Waited for %" PRId64 " milliseconds.",
1238               nanoseconds_to_milliseconds(waitNs - timeLeftNs));
1239 
1240         EXPECT_LE(waitNs - timeLeftNs, reportResultsNs)
1241                 << "waited for "
1242                 << (timeLeftNs >= 0 ? "" : "more than ")
1243                 << (timeLeftNs >= 0 ? (waitNs - timeLeftNs) : waitNs)
1244                 << "ns, expect to finish in "
1245                 << reportResultsNs << " ns";
1246 
1247         // two-way method, was supposed to return right away
1248         EXPECT_TRUE(invokeResults[0].invoked);
1249         EXPECT_LE(invokeResults[0].timeNs, invokeResults[0].callerBlockedNs);
1250         EXPECT_LE(invokeResults[0].callerBlockedNs, TOLERANCE_NS);
1251         // two-way method, was supposed to block caller for DELAY_NS
1252         EXPECT_TRUE(invokeResults[1].invoked);
1253         EXPECT_LE(invokeResults[1].timeNs, invokeResults[1].callerBlockedNs);
1254         EXPECT_LE(invokeResults[1].callerBlockedNs,
1255                     DELAY_NS + TOLERANCE_NS);
1256         // one-way method, do not block caller, but body was supposed to block for DELAY_NS
1257         EXPECT_TRUE(invokeResults[2].invoked);
1258         EXPECT_LE(invokeResults[2].callerBlockedNs, ONEWAY_TOLERANCE_NS);
1259         EXPECT_LE(invokeResults[2].timeNs, DELAY_NS + TOLERANCE_NS);
1260     });
1261 }
1262 
1263 
1264 
TEST_F(HidlTest,FooUseAnEnumTest)1265 TEST_F(HidlTest, FooUseAnEnumTest) {
1266     ALOGI("CLIENT call useAnEnum.");
1267     IFoo::SomeEnum sleepy = foo->useAnEnum(IFoo::SomeEnum::quux);
1268     ALOGI("CLIENT useAnEnum returned %u", (unsigned)sleepy);
1269     EXPECT_EQ(sleepy, IFoo::SomeEnum::goober);
1270 }
1271 
TEST_F(HidlTest,FooHaveAGooberTest)1272 TEST_F(HidlTest, FooHaveAGooberTest) {
1273     hidl_vec<IFoo::Goober> gooberVecParam;
1274     gooberVecParam.resize(2);
1275     gooberVecParam[0].name = "Hello";
1276     gooberVecParam[1].name = "World";
1277 
1278     ALOGI("CLIENT call haveAGooberVec.");
1279     EXPECT_OK(foo->haveAGooberVec(gooberVecParam));
1280     ALOGI("CLIENT haveAGooberVec returned.");
1281 
1282     ALOGI("CLIENT call haveaGoober.");
1283     EXPECT_OK(foo->haveAGoober(gooberVecParam[0]));
1284     ALOGI("CLIENT haveaGoober returned.");
1285 
1286     ALOGI("CLIENT call haveAGooberArray.");
1287     hidl_array<IFoo::Goober, 20> gooberArrayParam;
1288     EXPECT_OK(foo->haveAGooberArray(gooberArrayParam));
1289     ALOGI("CLIENT haveAGooberArray returned.");
1290 }
1291 
TEST_F(HidlTest,FooHaveATypeFromAnotherFileTest)1292 TEST_F(HidlTest, FooHaveATypeFromAnotherFileTest) {
1293     ALOGI("CLIENT call haveATypeFromAnotherFile.");
1294     Abc abcParam{};
1295     abcParam.x = "alphabet";
1296     abcParam.y = 3.14f;
1297     native_handle_t *handle = native_handle_create(0, 0);
1298     abcParam.z = handle;
1299     EXPECT_OK(foo->haveATypeFromAnotherFile(abcParam));
1300     ALOGI("CLIENT haveATypeFromAnotherFile returned.");
1301     native_handle_delete(handle);
1302     abcParam.z = nullptr;
1303 }
1304 
TEST_F(HidlTest,FooHaveSomeStringsTest)1305 TEST_F(HidlTest, FooHaveSomeStringsTest) {
1306     ALOGI("CLIENT call haveSomeStrings.");
1307     hidl_array<hidl_string, 3> stringArrayParam;
1308     stringArrayParam[0] = "What";
1309     stringArrayParam[1] = "a";
1310     stringArrayParam[2] = "disaster";
1311     EXPECT_OK(foo->haveSomeStrings(
1312                 stringArrayParam,
1313                 [&](const auto &out) {
1314                     ALOGI("CLIENT haveSomeStrings returned %s.",
1315                           to_string(out).c_str());
1316 
1317                     EXPECT_EQ(to_string(out), "['Hello', 'World']");
1318                 }));
1319     ALOGI("CLIENT haveSomeStrings returned.");
1320 }
1321 
TEST_F(HidlTest,FooHaveAStringVecTest)1322 TEST_F(HidlTest, FooHaveAStringVecTest) {
1323     ALOGI("CLIENT call haveAStringVec.");
1324     hidl_vec<hidl_string> stringVecParam;
1325     stringVecParam.resize(3);
1326     stringVecParam[0] = "What";
1327     stringVecParam[1] = "a";
1328     stringVecParam[2] = "disaster";
1329     EXPECT_OK(foo->haveAStringVec(
1330                 stringVecParam,
1331                 [&](const auto &out) {
1332                     ALOGI("CLIENT haveAStringVec returned %s.",
1333                           to_string(out).c_str());
1334 
1335                     EXPECT_EQ(to_string(out), "['Hello', 'World']");
1336                 }));
1337     ALOGI("CLIENT haveAStringVec returned.");
1338 }
1339 
TEST_F(HidlTest,FooTransposeMeTest)1340 TEST_F(HidlTest, FooTransposeMeTest) {
1341     hidl_array<float, 3, 5> in;
1342     float k = 1.0f;
1343     for (size_t i = 0; i < 3; ++i) {
1344         for (size_t j = 0; j < 5; ++j, ++k) {
1345             in[i][j] = k;
1346         }
1347     }
1348 
1349     ALOGI("CLIENT call transposeMe(%s).", to_string(in).c_str());
1350 
1351     EXPECT_OK(foo->transposeMe(
1352                 in,
1353                 [&](const auto &out) {
1354                     ALOGI("CLIENT transposeMe returned %s.",
1355                           to_string(out).c_str());
1356 
1357                     for (size_t i = 0; i < 3; ++i) {
1358                         for (size_t j = 0; j < 5; ++j) {
1359                             EXPECT_EQ(out[j][i], in[i][j]);
1360                         }
1361                     }
1362                 }));
1363 }
1364 
TEST_F(HidlTest,FooCallingDrWhoTest)1365 TEST_F(HidlTest, FooCallingDrWhoTest) {
1366     IFoo::MultiDimensional in;
1367 
1368     size_t k = 0;
1369     for (size_t i = 0; i < 5; ++i) {
1370         for (size_t j = 0; j < 3; ++j, ++k) {
1371             in.quuxMatrix[i][j].first = ("First " + std::to_string(k)).c_str();
1372             in.quuxMatrix[i][j].last = ("Last " + std::to_string(15-k)).c_str();
1373         }
1374     }
1375 
1376     ALOGI("CLIENT call callingDrWho(%s).",
1377           MultiDimensionalToString(in).c_str());
1378 
1379     EXPECT_OK(foo->callingDrWho(
1380                 in,
1381                 [&](const auto &out) {
1382                     ALOGI("CLIENT callingDrWho returned %s.",
1383                           MultiDimensionalToString(out).c_str());
1384 
1385                     size_t k = 0;
1386                     for (size_t i = 0; i < 5; ++i) {
1387                         for (size_t j = 0; j < 3; ++j, ++k) {
1388                             EXPECT_STREQ(
1389                                 out.quuxMatrix[i][j].first.c_str(),
1390                                 in.quuxMatrix[4 - i][2 - j].last.c_str());
1391 
1392                             EXPECT_STREQ(
1393                                 out.quuxMatrix[i][j].last.c_str(),
1394                                 in.quuxMatrix[4 - i][2 - j].first.c_str());
1395                         }
1396                     }
1397                 }));
1398 }
1399 
numberToEnglish(int x)1400 static std::string numberToEnglish(int x) {
1401     static const char *const kDigits[] = {
1402         "zero",
1403         "one",
1404         "two",
1405         "three",
1406         "four",
1407         "five",
1408         "six",
1409         "seven",
1410         "eight",
1411         "nine",
1412     };
1413 
1414     if (x < 0) {
1415         return "negative " + numberToEnglish(-x);
1416     }
1417 
1418     if (x < 10) {
1419         return kDigits[x];
1420     }
1421 
1422     if (x <= 15) {
1423         static const char *const kSpecialTens[] = {
1424             "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
1425         };
1426 
1427         return kSpecialTens[x - 10];
1428     }
1429 
1430     if (x < 20) {
1431         return std::string(kDigits[x % 10]) + "teen";
1432     }
1433 
1434     if (x < 100) {
1435         static const char *const kDecades[] = {
1436             "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
1437             "eighty", "ninety",
1438         };
1439 
1440         return std::string(kDecades[x / 10 - 2]) + kDigits[x % 10];
1441     }
1442 
1443     return "positively huge!";
1444 }
1445 
TEST_F(HidlTest,FooTransposeTest)1446 TEST_F(HidlTest, FooTransposeTest) {
1447     IFoo::StringMatrix5x3 in;
1448 
1449     for (int i = 0; i < 5; ++i) {
1450         for (int j = 0; j < 3; ++j) {
1451             in.s[i][j] = numberToEnglish(3 * i + j + 1).c_str();
1452         }
1453     }
1454 
1455     EXPECT_OK(foo->transpose(
1456                 in,
1457                 [&](const auto &out) {
1458                     EXPECT_EQ(
1459                         to_string(out),
1460                         "[['one', 'four', 'seven', 'ten', 'thirteen'], "
1461                          "['two', 'five', 'eight', 'eleven', 'fourteen'], "
1462                          "['three', 'six', 'nine', 'twelve', 'fifteen']]");
1463                 }));
1464 }
1465 
TEST_F(HidlTest,FooTranspose2Test)1466 TEST_F(HidlTest, FooTranspose2Test) {
1467     hidl_array<hidl_string, 5, 3> in;
1468 
1469     for (int i = 0; i < 5; ++i) {
1470         for (int j = 0; j < 3; ++j) {
1471             in[i][j] = numberToEnglish(3 * i + j + 1).c_str();
1472         }
1473     }
1474 
1475     EXPECT_OK(foo->transpose2(
1476                 in,
1477                 [&](const auto &out) {
1478                     EXPECT_EQ(
1479                         to_string(out),
1480                         "[['one', 'four', 'seven', 'ten', 'thirteen'], "
1481                          "['two', 'five', 'eight', 'eleven', 'fourteen'], "
1482                          "['three', 'six', 'nine', 'twelve', 'fifteen']]");
1483                 }));
1484 }
1485 
TEST_F(HidlTest,FooNullNativeHandleTest)1486 TEST_F(HidlTest, FooNullNativeHandleTest) {
1487     Abc xyz;
1488     xyz.z = nullptr;
1489     EXPECT_OK(bar->expectNullHandle(nullptr, xyz, [](bool hIsNull, bool xyzHasNull) {
1490         EXPECT_TRUE(hIsNull);
1491         EXPECT_TRUE(xyzHasNull);
1492     }));
1493 }
1494 
TEST_F(HidlTest,FooNullCallbackTest)1495 TEST_F(HidlTest, FooNullCallbackTest) {
1496     EXPECT_OK(foo->echoNullInterface(nullptr,
1497                 [](const auto receivedNull, const auto &intf) {
1498                    EXPECT_TRUE(receivedNull);
1499                    EXPECT_EQ(intf, nullptr);
1500                 }));
1501 }
1502 
TEST_F(HidlTest,StructWithFmq)1503 TEST_F(HidlTest, StructWithFmq) {
1504     IFoo::WithFmq w = {
1505         .scatterGathered =
1506             {
1507                 .descSync = {std::vector<GrantorDescriptor>(), native_handle_create(0, 1), 5},
1508             },
1509         .containsPointer =
1510             {
1511                 .descSync = {std::vector<GrantorDescriptor>(), native_handle_create(0, 1), 5},
1512                 .foo = nullptr,
1513             },
1514     };
1515     EXPECT_OK(foo->repeatWithFmq(w, [&](const IFoo::WithFmq& returned) {
1516         checkMQDescriptorEquality(w.scatterGathered.descSync, returned.scatterGathered.descSync);
1517         checkMQDescriptorEquality(w.containsPointer.descSync, returned.containsPointer.descSync);
1518 
1519         EXPECT_EQ(w.containsPointer.foo, returned.containsPointer.foo);
1520     }));
1521 }
1522 
TEST_F(HidlTest,FooSendVecTest)1523 TEST_F(HidlTest, FooSendVecTest) {
1524     hidl_vec<uint8_t> in;
1525     in.resize(16);
1526     for (size_t i = 0; i < in.size(); ++i) {
1527         in[i] = i;
1528     }
1529 
1530     EXPECT_OK(foo->sendVec(
1531                 in,
1532                 [&](const auto &out) {
1533                     EXPECT_EQ(to_string(in), to_string(out));
1534                 }));
1535 }
1536 
TEST_F(HidlTest,FooSendEmptyVecTest)1537 TEST_F(HidlTest, FooSendEmptyVecTest) {
1538     hidl_vec<uint8_t> in;
1539     EXPECT_OK(foo->sendVec(
1540                 in,
1541                 [&](const auto &out) {
1542                     EXPECT_EQ(out.size(), 0u);
1543                     EXPECT_EQ(to_string(in), to_string(out));
1544                 }));
1545 }
1546 
TEST_F(HidlTest,FooHaveAVectorOfInterfacesTest)1547 TEST_F(HidlTest, FooHaveAVectorOfInterfacesTest) {
1548     hidl_vec<sp<ISimple> > in;
1549     in.resize(16);
1550     for (size_t i = 0; i < in.size(); ++i) {
1551         in[i] = new Simple(i);
1552     }
1553 
1554     EXPECT_OK(foo->haveAVectorOfInterfaces(
1555                 in,
1556                 [&](const auto &out) {
1557                     EXPECT_EQ(in.size(), out.size());
1558                     for (size_t i = 0; i < in.size(); ++i) {
1559                         int32_t inCookie = in[i]->getCookie();
1560                         int32_t outCookie = out[i]->getCookie();
1561                         EXPECT_EQ(inCookie, outCookie);
1562                     }
1563                 }));
1564 }
1565 
TEST_F(HidlTest,FooHaveAVectorOfGenericInterfacesTest)1566 TEST_F(HidlTest, FooHaveAVectorOfGenericInterfacesTest) {
1567 
1568     hidl_vec<sp<::android::hidl::base::V1_0::IBase> > in;
1569     in.resize(16);
1570     for (size_t i = 0; i < in.size(); ++i) {
1571         sp<ISimple> s = new Simple(i);
1572         in[i] = s;
1573     }
1574 
1575     EXPECT_OK(foo->haveAVectorOfGenericInterfaces(
1576                 in,
1577                 [&](const auto &out) {
1578                     EXPECT_EQ(in.size(), out.size());
1579 
1580                     EXPECT_OK(out[0]->interfaceDescriptor([](const auto &name) {
1581                         ASSERT_STREQ(name.c_str(), ISimple::descriptor);
1582                     }));
1583                     for (size_t i = 0; i < in.size(); ++i) {
1584                         sp<ISimple> inSimple = ISimple::castFrom(in[i]);
1585                         sp<ISimple> outSimple = ISimple::castFrom(out[i]);
1586 
1587                         ASSERT_NE(inSimple.get(), nullptr);
1588                         ASSERT_NE(outSimple.get(), nullptr);
1589                         EXPECT_EQ(in[i], inSimple.get()); // pointers must be equal!
1590                         int32_t inCookie = inSimple->getCookie();
1591                         int32_t outCookie = outSimple->getCookie();
1592                         EXPECT_EQ(inCookie, outCookie);
1593                     }
1594                 }));
1595 }
1596 
TEST_F(HidlTest,FooStructEmbeddedHandleTest)1597 TEST_F(HidlTest, FooStructEmbeddedHandleTest) {
1598     EXPECT_OK(foo->createMyHandle([&](const auto &myHandle) {
1599         EXPECT_EQ(myHandle.guard, 666);
1600         const native_handle_t* handle = myHandle.h.getNativeHandle();
1601         EXPECT_EQ(handle->numInts, 10);
1602         EXPECT_EQ(handle->numFds, 0);
1603         int data[] = {2,3,5,7,11,13,17,19,21,23};
1604         EXPECT_ARRAYEQ(handle->data, data, 10);
1605     }));
1606 
1607     EXPECT_OK(foo->closeHandles());
1608 }
1609 
TEST_F(HidlTest,FooHandleVecTest)1610 TEST_F(HidlTest, FooHandleVecTest) {
1611     EXPECT_OK(foo->createHandles(3, [&](const auto &handles) {
1612         EXPECT_EQ(handles.size(), 3ull);
1613         int data[] = {2,3,5,7,11,13,17,19,21,23};
1614         for (size_t i = 0; i < 3; i++) {
1615             const native_handle_t *h = handles[i];
1616             EXPECT_EQ(h->numInts, 10) << " for element " << i;
1617             EXPECT_EQ(h->numFds, 0) << " for element " << i;
1618             EXPECT_ARRAYEQ(h->data, data, 10);
1619         }
1620     }));
1621 
1622     EXPECT_OK(foo->closeHandles());
1623 }
1624 
TEST_F(HidlTest,BazStructWithInterfaceTest)1625 TEST_F(HidlTest, BazStructWithInterfaceTest) {
1626     using ::android::hardware::interfacesEqual;
1627 
1628     const std::string testString = "Hello, World!";
1629     const std::array<int8_t, 7> testArray{-1, -2, -3, 0, 1, 2, 3};
1630     const hidl_vec<hidl_string> testStrings{"So", "Many", "Words"};
1631     const hidl_vec<bool> testVector{false, true, false, true, true, true};
1632 
1633     hidl_vec<bool> goldenResult(testVector.size());
1634     for (size_t i = 0; i < testVector.size(); i++) {
1635         goldenResult[i] = !testVector[i];
1636     }
1637 
1638     IBaz::StructWithInterface swi;
1639     swi.number = 42;
1640     swi.array = testArray;
1641     swi.oneString = testString;
1642     swi.vectorOfStrings = testStrings;
1643     swi.iface = baz;
1644 
1645     EXPECT_OK(baz->haveSomeStructWithInterface(swi, [&](const IBaz::StructWithInterface& swiBack) {
1646         EXPECT_EQ(42, swiBack.number);
1647         for (size_t i = 0; i < testArray.size(); i++) {
1648             EXPECT_EQ(testArray[i], swiBack.array[i]);
1649         }
1650 
1651         EXPECT_EQ(testString, std::string(swiBack.oneString));
1652         EXPECT_EQ(testStrings, swiBack.vectorOfStrings);
1653 
1654         EXPECT_TRUE(interfacesEqual(swi.iface, swiBack.iface));
1655     }));
1656 }
1657 
1658 struct HidlDeathRecipient : hidl_death_recipient {
1659     std::mutex mutex;
1660     std::condition_variable condition;
1661     wp<IBase> who;
1662     bool fired = false;
1663     uint64_t cookie = 0;
1664 
serviceDiedHidlDeathRecipient1665     void serviceDied(uint64_t cookie, const wp<IBase>& who) override {
1666         std::unique_lock<std::mutex> lock(mutex);
1667         fired = true;
1668         this->cookie = cookie;
1669         this->who = who;
1670         condition.notify_one();
1671     };
1672 };
1673 
TEST_F(HidlTest,DeathRecipientTest)1674 TEST_F(HidlTest, DeathRecipientTest) {
1675     sp<HidlDeathRecipient> recipient = new HidlDeathRecipient();
1676     sp<HidlDeathRecipient> recipient2 = new HidlDeathRecipient();
1677 
1678     EXPECT_TRUE(dyingBaz->linkToDeath(recipient, 0x1481));
1679 
1680     EXPECT_TRUE(dyingBaz->linkToDeath(recipient, 0x1482));
1681     EXPECT_TRUE(dyingBaz->unlinkToDeath(recipient));
1682 
1683     EXPECT_TRUE(dyingBaz->linkToDeath(recipient2, 0x2592));
1684     EXPECT_TRUE(dyingBaz->unlinkToDeath(recipient2));
1685 
1686     if (mode != BINDERIZED) {
1687         // Passthrough doesn't fire, nor does it keep state of
1688         // registered death recipients (so it won't fail unlinking
1689         // the same recipient twice).
1690         return;
1691     }
1692 
1693     EXPECT_FALSE(dyingBaz->unlinkToDeath(recipient2));
1694     auto ret = dyingBaz->dieNow();
1695     if (!ret.isOk()) {
1696         //do nothing, this is expected
1697     }
1698 
1699     // further calls fail
1700     EXPECT_FAIL(dyingBaz->ping());
1701 
1702     std::unique_lock<std::mutex> lock(recipient->mutex);
1703     recipient->condition.wait_for(lock, std::chrono::milliseconds(100), [&recipient]() {
1704             return recipient->fired;
1705     });
1706     EXPECT_TRUE(recipient->fired);
1707     EXPECT_EQ(recipient->cookie, 0x1481u);
1708     EXPECT_EQ(recipient->who, dyingBaz);
1709     std::unique_lock<std::mutex> lock2(recipient2->mutex);
1710     recipient2->condition.wait_for(lock2, std::chrono::milliseconds(100), [&recipient2]() {
1711             return recipient2->fired;
1712     });
1713     EXPECT_FALSE(recipient2->fired);
1714 
1715     // Verify servicemanager dropped its reference too
1716     sp<IBaz> deadBaz = IBaz::getService("dyingBaz", false);
1717     if (deadBaz != nullptr) {
1718         // Got a passthrough
1719         EXPECT_FALSE(deadBaz->isRemote());
1720     }
1721 }
1722 
TEST_F(HidlTest,BarThisIsNewTest)1723 TEST_F(HidlTest, BarThisIsNewTest) {
1724     // Now the tricky part, get access to the derived interface.
1725     ALOGI("CLIENT call thisIsNew.");
1726     EXPECT_OK(bar->thisIsNew());
1727     ALOGI("CLIENT thisIsNew returned.");
1728 }
1729 
expectGoodChild(sp<IChild> child)1730 static void expectGoodChild(sp<IChild> child) {
1731     ASSERT_NE(child.get(), nullptr);
1732     child = IChild::castFrom(child);
1733     ASSERT_NE(child.get(), nullptr);
1734     EXPECT_OK(child->doGrandparent());
1735     EXPECT_OK(child->doParent());
1736     EXPECT_OK(child->doChild());
1737 }
1738 
expectGoodParent(sp<IParent> parent)1739 static void expectGoodParent(sp<IParent> parent) {
1740     ASSERT_NE(parent.get(), nullptr);
1741     parent = IParent::castFrom(parent);
1742     ASSERT_NE(parent.get(), nullptr);
1743     EXPECT_OK(parent->doGrandparent());
1744     EXPECT_OK(parent->doParent());
1745     sp<IChild> child = IChild::castFrom(parent);
1746     expectGoodChild(child);
1747 }
1748 
expectGoodGrandparent(sp<IGrandparent> grandparent)1749 static void expectGoodGrandparent(sp<IGrandparent> grandparent) {
1750     ASSERT_NE(grandparent.get(), nullptr);
1751     grandparent = IGrandparent::castFrom(grandparent);
1752     ASSERT_NE(grandparent.get(), nullptr);
1753     EXPECT_OK(grandparent->doGrandparent());
1754     sp<IParent> parent = IParent::castFrom(grandparent);
1755     expectGoodParent(parent);
1756 }
1757 
TEST_F(HidlTest,FooHaveAnInterfaceTest)1758 TEST_F(HidlTest, FooHaveAnInterfaceTest) {
1759     sp<ISimple> in = new Complicated(42);
1760     Return<sp<ISimple>> ret = bar->haveAInterface(in);
1761     EXPECT_OK(ret);
1762     sp<ISimple> out = ret;
1763     ASSERT_NE(out.get(), nullptr);
1764     EXPECT_EQ(out->getCookie(), 42);
1765     EXPECT_OK(out->customVecInt([](const auto &) { }));
1766     EXPECT_OK(out->customVecStr([](const auto &) { }));
1767     EXPECT_OK(out->ping());
1768     EXPECT_OK(out->mystr([](const auto &) { }));
1769     EXPECT_OK(out->myhandle([](const auto &) { }));
1770 }
1771 
TEST_F(HidlTest,InheritRemoteGrandparentTest)1772 TEST_F(HidlTest, InheritRemoteGrandparentTest) {
1773     Return<sp<IGrandparent>> ret = fetcher->getGrandparent(true);
1774     EXPECT_OK(ret);
1775     expectGoodGrandparent(ret);
1776 }
1777 
TEST_F(HidlTest,InheritLocalGrandparentTest)1778 TEST_F(HidlTest, InheritLocalGrandparentTest) {
1779     Return<sp<IGrandparent>> ret = fetcher->getGrandparent(false);
1780     EXPECT_OK(ret);
1781     expectGoodGrandparent(ret);
1782 }
1783 
TEST_F(HidlTest,InheritRemoteParentTest)1784 TEST_F(HidlTest, InheritRemoteParentTest) {
1785     Return<sp<IParent>> ret = fetcher->getParent(true);
1786     EXPECT_OK(ret);
1787     expectGoodParent(ret);
1788 }
1789 
TEST_F(HidlTest,InheritLocalParentTest)1790 TEST_F(HidlTest, InheritLocalParentTest) {
1791     Return<sp<IParent>> ret = fetcher->getParent(false);
1792     EXPECT_OK(ret);
1793     expectGoodParent(ret);
1794 }
1795 
TEST_F(HidlTest,InheritRemoteChildTest)1796 TEST_F(HidlTest, InheritRemoteChildTest) {
1797     Return<sp<IChild>> ret = fetcher->getChild(true);
1798     EXPECT_OK(ret);
1799     expectGoodChild(ret);
1800 }
1801 
TEST_F(HidlTest,InheritLocalChildTest)1802 TEST_F(HidlTest, InheritLocalChildTest) {
1803     Return<sp<IChild>> ret = fetcher->getChild(false);
1804     EXPECT_OK(ret);
1805     expectGoodChild(ret);
1806 }
1807 
TEST_F(HidlTest,TestArrayDimensionality)1808 TEST_F(HidlTest, TestArrayDimensionality) {
1809     hidl_array<int, 2> oneDim;
1810     hidl_array<int, 2, 3> twoDim;
1811     hidl_array<int, 2, 3, 4> threeDim;
1812 
1813     EXPECT_EQ(oneDim.size(), 2u);
1814     EXPECT_EQ(twoDim.size(), std::make_tuple(2u, 3u));
1815     EXPECT_EQ(threeDim.size(), std::make_tuple(2u, 3u, 4u));
1816 }
1817 
TEST_F(HidlTest,StructEqualTest)1818 TEST_F(HidlTest, StructEqualTest) {
1819     using G = IFoo::Goober;
1820     using F = IFoo::Fumble;
1821     G g1{
1822         .q = 42,
1823         .name = "The Ultimate Question of Life, the Universe, and Everything",
1824         .address = "North Pole",
1825         .numbers = std::array<double, 10>{ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} },
1826         .fumble = F{.data = {.data = 50}},
1827         .gumble = F{.data = {.data = 60}}
1828     };
1829     G g2{
1830         .q = 42,
1831         .name = "The Ultimate Question of Life, the Universe, and Everything",
1832         .address = "North Pole",
1833         .numbers = std::array<double, 10>{ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} },
1834         .fumble = F{.data = {.data = 50}},
1835         .gumble = F{.data = {.data = 60}}
1836     };
1837     G g3{
1838         .q = 42,
1839         .name = "The Ultimate Question of Life, the Universe, and Everything",
1840         .address = "North Pole",
1841         .numbers = std::array<double, 10>{ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} },
1842         .fumble = F{.data = {.data = 50}},
1843         .gumble = F{.data = {.data = 61}}
1844     };
1845     // explicitly invoke operator== here.
1846     EXPECT_TRUE(g1 == g2);
1847     EXPECT_TRUE(g1 != g3);
1848 }
1849 
TEST_F(HidlTest,EnumEqualTest)1850 TEST_F(HidlTest, EnumEqualTest) {
1851     using E = IFoo::SomeEnum;
1852     E e1 = E::quux;
1853     E e2 = E::quux;
1854     E e3 = E::goober;
1855     // explicitly invoke operator== here.
1856     EXPECT_TRUE(e1 == e2);
1857     EXPECT_TRUE(e1 != e3);
1858 }
1859 
TEST_F(HidlTest,InvalidTransactionTest)1860 TEST_F(HidlTest, InvalidTransactionTest) {
1861     using ::android::hardware::tests::bar::V1_0::BnHwBar;
1862     using ::android::hardware::IBinder;
1863     using ::android::hardware::Parcel;
1864 
1865     sp<IBinder> binder = ::android::hardware::toBinder(bar);
1866 
1867     Parcel request, reply;
1868     EXPECT_EQ(::android::OK, request.writeInterfaceToken(IBar::descriptor));
1869     EXPECT_EQ(::android::UNKNOWN_TRANSACTION, binder->transact(1234, request, &reply));
1870 
1871     EXPECT_OK(bar->ping());  // still works
1872 }
1873 
TEST_F(HidlTest,EmptyTransactionTest)1874 TEST_F(HidlTest, EmptyTransactionTest) {
1875     using ::android::hardware::IBinder;
1876     using ::android::hardware::Parcel;
1877     using ::android::hardware::tests::bar::V1_0::BnHwBar;
1878 
1879     sp<IBinder> binder = ::android::hardware::toBinder(bar);
1880 
1881     Parcel request, reply;
1882     EXPECT_EQ(::android::BAD_TYPE, binder->transact(3 /*someBoolMethod*/, request, &reply));
1883 
1884     EXPECT_OK(bar->ping());  // still works
1885 }
1886 
TEST_F(HidlTest,WrongDescriptorTest)1887 TEST_F(HidlTest, WrongDescriptorTest) {
1888     using ::android::hardware::IBinder;
1889     using ::android::hardware::Parcel;
1890     using ::android::hardware::tests::bar::V1_0::BnHwBar;
1891 
1892     sp<IBinder> binder = ::android::hardware::toBinder(bar);
1893 
1894     Parcel request, reply;
1895     // wrong descriptor
1896     EXPECT_EQ(::android::OK, request.writeInterfaceToken("not a real descriptor"));
1897     EXPECT_EQ(::android::BAD_TYPE, binder->transact(3 /*someBoolMethod*/, request, &reply));
1898 
1899     EXPECT_OK(bar->ping());  // still works
1900 }
1901 
TEST_F(HidlTest,TwowayMethodOnewayEnabledTest)1902 TEST_F(HidlTest, TwowayMethodOnewayEnabledTest) {
1903     using ::android::hardware::IBinder;
1904     using ::android::hardware::Parcel;
1905     using ::android::hardware::tests::baz::V1_0::BnHwBaz;
1906 
1907     sp<IBinder> binder = ::android::hardware::toBinder(baz);
1908 
1909     Parcel request, reply;
1910     EXPECT_EQ(::android::OK, request.writeInterfaceToken(IBaz::descriptor));
1911     EXPECT_EQ(::android::OK, request.writeInt64(1234));
1912     // IBaz::doThatAndReturnSomething is two-way but we call it using FLAG_ONEWAY.
1913     EXPECT_EQ(::android::OK, binder->transact(19 /*doThatAndReturnSomething*/, request, &reply,
1914                                               IBinder::FLAG_ONEWAY));
1915 
1916     ::android::hardware::Status status;
1917     ::android::status_t readFromParcelStatus = ::android::hardware::readFromParcel(&status, reply);
1918     if (mode == BINDERIZED) {
1919         EXPECT_EQ(::android::NOT_ENOUGH_DATA, readFromParcelStatus);
1920         EXPECT_EQ(::android::hardware::Status::EX_TRANSACTION_FAILED, status.exceptionCode());
1921     } else {
1922         EXPECT_EQ(666, reply.readInt32());
1923     }
1924 
1925     EXPECT_OK(baz->ping());  // still works
1926 }
1927 
TEST_F(HidlTest,OnewayMethodOnewayDisabledTest)1928 TEST_F(HidlTest, OnewayMethodOnewayDisabledTest) {
1929     using ::android::hardware::IBinder;
1930     using ::android::hardware::Parcel;
1931     using ::android::hardware::tests::baz::V1_0::BnHwBaz;
1932 
1933     sp<IBinder> binder = ::android::hardware::toBinder(baz);
1934 
1935     Parcel request, reply;
1936     EXPECT_EQ(::android::OK, request.writeInterfaceToken(IBaz::descriptor));
1937     EXPECT_EQ(::android::OK, request.writeFloat(1.0f));
1938     nsecs_t now = systemTime();
1939     // IBaz::doThis is oneway but we call it without using FLAG_ONEWAY.
1940     EXPECT_EQ(
1941             // Expect OK because IPCThreadState::executeCommand for BR_TRANSACTION
1942             // sends an empty reply for two-way transactions if the transaction itself
1943             // did not send a reply.
1944             ::android::OK,
1945             binder->transact(18 /*doThis*/, request, &reply, 0 /* Not FLAG_ONEWAY */));
1946     if (gHidlEnvironment->enableDelayMeasurementTests) {
1947         // IBaz::doThis is oneway, should return instantly.
1948         EXPECT_LT(systemTime() - now, ONEWAY_TOLERANCE_NS);
1949     }
1950 
1951     EXPECT_OK(baz->ping());  // still works
1952 }
1953 
TEST_F(HidlTest,TrieSimpleTest)1954 TEST_F(HidlTest, TrieSimpleTest) {
1955     trieInterface->newTrie([&](const TrieNode& trie) {
1956         trieInterface->addStrings(trie, {"a", "ba"}, [&](const TrieNode& trie) {
1957             trieInterface->containsStrings(
1958                 trie, {"", "a", "b", "ab", "ba", "c"}, [](const hidl_vec<bool>& response) {
1959                     EXPECT_EQ(response,
1960                               std::vector<bool>({false, true, false, false, true, false}));
1961                 });
1962 
1963             trieInterface->addStrings(trie, {"", "ab", "bab"}, [&](const TrieNode& trie) {
1964                 trieInterface->containsStrings(
1965                     trie, {"", "a", "b", "ab", "ba", "c"}, [](const hidl_vec<bool>& response) {
1966                         EXPECT_EQ(response,
1967                                   std::vector<bool>({true, true, false, true, true, false}));
1968                     });
1969             });
1970         });
1971     });
1972 }
1973 
1974 struct RandomString {
nextRandomString1975     std::string next() {
1976         std::string ret(lengthDist(rng), 0);
1977         std::generate(ret.begin(), ret.end(), [&]() { return charDist(rng); });
1978         return ret;
1979     }
1980 
RandomStringRandomString1981     RandomString() : rng(std::random_device{}()), lengthDist(5, 10), charDist('a', 'a' + 10) {}
1982 
1983    private:
1984     std::default_random_engine rng;
1985     std::uniform_int_distribution<> lengthDist;
1986     std::uniform_int_distribution<> charDist;
1987 };
1988 
TEST_F(HidlTest,TrieStressTest)1989 TEST_F(HidlTest, TrieStressTest) {
1990     const size_t REQUEST_NUM = 1000;
1991     RandomString stringGenerator;
1992 
1993     trieInterface->newTrie([&](const TrieNode& trie) {
1994         std::vector<std::string> strings(REQUEST_NUM);
1995         for (auto& str : strings) {
1996             str = stringGenerator.next();
1997         }
1998 
1999         trieInterface->addStrings(
2000             trie, hidl_vec<hidl_string>(strings.begin(), strings.end()), [&](const TrieNode& trie) {
2001                 std::unordered_set<std::string> addedStrings(strings.begin(), strings.end());
2002 
2003                 for (size_t i = 0; i != REQUEST_NUM; ++i) {
2004                     strings.push_back(stringGenerator.next());
2005                 }
2006 
2007                 std::vector<bool> trueResponse(strings.size());
2008                 std::transform(strings.begin(), strings.end(), trueResponse.begin(),
2009                                [&](const std::string& str) {
2010                                    return addedStrings.find(str) != addedStrings.end();
2011                                });
2012 
2013                 trieInterface->containsStrings(
2014                     trie, hidl_vec<hidl_string>(strings.begin(), strings.end()),
2015                     [&](const hidl_vec<bool>& response) { EXPECT_EQ(response, trueResponse); });
2016             });
2017     });
2018 }
2019 
TEST_F(HidlTest,SafeUnionNoInitTest)2020 TEST_F(HidlTest, SafeUnionNoInitTest) {
2021     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& safeUnion) {
2022         EXPECT_EQ(LargeSafeUnion::hidl_discriminator::noinit, safeUnion.getDiscriminator());
2023     }));
2024 }
2025 
TEST_F(HidlTest,SafeUnionSimpleTest)2026 TEST_F(HidlTest, SafeUnionSimpleTest) {
2027     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& safeUnion) {
2028         EXPECT_OK(safeunionInterface->setA(safeUnion, -5, [&](const LargeSafeUnion& safeUnion) {
2029             EXPECT_EQ(LargeSafeUnion::hidl_discriminator::a, safeUnion.getDiscriminator());
2030             EXPECT_EQ(-5, safeUnion.a());
2031 
2032             uint64_t max = std::numeric_limits<uint64_t>::max();
2033             EXPECT_OK(
2034                 safeunionInterface->setD(safeUnion, max, [&](const LargeSafeUnion& safeUnion) {
2035                     EXPECT_EQ(LargeSafeUnion::hidl_discriminator::d, safeUnion.getDiscriminator());
2036                     EXPECT_EQ(max, safeUnion.d());
2037                 }));
2038         }));
2039     }));
2040 }
2041 
TEST_F(HidlTest,SafeUnionArrayLikeTypesTest)2042 TEST_F(HidlTest, SafeUnionArrayLikeTypesTest) {
2043     const std::array<int64_t, 5> testArray{1, -2, 3, -4, 5};
2044     const hidl_vec<uint64_t> testVector{std::numeric_limits<uint64_t>::max()};
2045 
2046     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& safeUnion) {
2047         EXPECT_OK(
2048             safeunionInterface->setF(safeUnion, testArray, [&](const LargeSafeUnion& safeUnion) {
2049                 EXPECT_EQ(LargeSafeUnion::hidl_discriminator::f, safeUnion.getDiscriminator());
2050 
2051                 for (size_t i = 0; i < testArray.size(); i++) {
2052                     EXPECT_EQ(testArray[i], safeUnion.f()[i]);
2053                 }
2054             }));
2055 
2056         EXPECT_OK(
2057             safeunionInterface->setI(safeUnion, testVector, [&](const LargeSafeUnion& safeUnion) {
2058                 EXPECT_EQ(LargeSafeUnion::hidl_discriminator::i, safeUnion.getDiscriminator());
2059                 EXPECT_EQ(testVector, safeUnion.i());
2060             }));
2061     }));
2062 }
2063 
TEST_F(HidlTest,SafeUnionStringTypeTest)2064 TEST_F(HidlTest, SafeUnionStringTypeTest) {
2065     const std::string testString =
2066         "This is an inordinately long test string to exercise hidl_string types in safe unions.";
2067 
2068     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& safeUnion) {
2069         EXPECT_OK(safeunionInterface->setG(
2070             safeUnion, hidl_string(testString), [&](const LargeSafeUnion& safeUnion) {
2071                 EXPECT_EQ(LargeSafeUnion::hidl_discriminator::g, safeUnion.getDiscriminator());
2072                 EXPECT_EQ(testString, std::string(safeUnion.g()));
2073             }));
2074     }));
2075 }
2076 
TEST_F(HidlTest,SafeUnionCopyConstructorTest)2077 TEST_F(HidlTest, SafeUnionCopyConstructorTest) {
2078     const hidl_vec<bool> testVector{true, false, true, false, false, false, true,  false,
2079                                     true, true,  true, false, false, true,  false, true};
2080 
2081     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& safeUnion) {
2082         EXPECT_OK(
2083             safeunionInterface->setH(safeUnion, testVector, [&](const LargeSafeUnion& safeUnion) {
2084                 LargeSafeUnion safeUnionCopy(safeUnion);
2085 
2086                 EXPECT_EQ(LargeSafeUnion::hidl_discriminator::h, safeUnionCopy.getDiscriminator());
2087                 EXPECT_EQ(testVector, safeUnionCopy.h());
2088             }));
2089     }));
2090 }
2091 
2092 template <typename T>
testZeroInit(const std::string & header)2093 void testZeroInit(const std::string& header) {
2094     uint8_t buf[sizeof(T)];
2095     memset(buf, 0xFF, sizeof(buf));
2096 
2097     T* t = new (buf) T;
2098 
2099     for (size_t i = 0; i < sizeof(T); i++) {
2100         EXPECT_EQ(0, buf[i]) << header << " at offset: " << i;
2101     }
2102 
2103     t->~T();
2104     t = nullptr;
2105 
2106     memset(buf, 0xFF, sizeof(buf));
2107     t = new (buf) T(T());  // copy constructor
2108 
2109     for (size_t i = 0; i < sizeof(T); i++) {
2110         EXPECT_EQ(0, buf[i]) << header << " at offset: " << i;
2111     }
2112 
2113     t->~T();
2114     t = nullptr;
2115 
2116     memset(buf, 0xFF, sizeof(buf));
2117     const T aT = T();
2118     t = new (buf) T(std::move(aT));  // move constructor
2119 
2120     for (size_t i = 0; i < sizeof(T); i++) {
2121         EXPECT_EQ(0, buf[i]) << header << " at offset: " << i;
2122     }
2123 
2124     t->~T();
2125     t = nullptr;
2126 }
2127 
TEST_F(HidlTest,SafeUnionUninit)2128 TEST_F(HidlTest, SafeUnionUninit) {
2129     testZeroInit<SmallSafeUnion>("SmallSafeUnion");
2130     testZeroInit<LargeSafeUnion>("LargeSafeUnion");
2131     testZeroInit<InterfaceTypeSafeUnion>("InterfaceTypeSafeUnion");
2132     testZeroInit<HandleTypeSafeUnion>("HandleTypeSafeUnion");
2133 }
2134 
TEST_F(HidlTest,SafeUnionMoveConstructorTest)2135 TEST_F(HidlTest, SafeUnionMoveConstructorTest) {
2136     sp<SimpleChild> otherInterface = new SimpleChild();
2137     ASSERT_EQ(1, otherInterface->getStrongCount());
2138 
2139     InterfaceTypeSafeUnion safeUnion;
2140     safeUnion.c(otherInterface);
2141     EXPECT_EQ(2, otherInterface->getStrongCount());
2142 
2143     InterfaceTypeSafeUnion anotherSafeUnion(std::move(safeUnion));
2144     EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::c,
2145               anotherSafeUnion.getDiscriminator());
2146     EXPECT_EQ(2, otherInterface->getStrongCount());
2147 }
2148 
TEST_F(HidlTest,SafeUnionCopyAssignmentTest)2149 TEST_F(HidlTest, SafeUnionCopyAssignmentTest) {
2150     const hidl_vec<hidl_string> testVector{"So", "Many", "Words"};
2151     InterfaceTypeSafeUnion safeUnion;
2152     safeUnion.e(testVector);
2153 
2154     InterfaceTypeSafeUnion anotherSafeUnion;
2155     anotherSafeUnion = safeUnion;
2156 
2157     EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::e, anotherSafeUnion.getDiscriminator());
2158     EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::e, safeUnion.getDiscriminator());
2159     EXPECT_NE(&(safeUnion.e()), &(anotherSafeUnion.e()));
2160     EXPECT_EQ(testVector, anotherSafeUnion.e());
2161     EXPECT_EQ(testVector, safeUnion.e());
2162 }
2163 
TEST_F(HidlTest,SafeUnionMoveAssignmentTest)2164 TEST_F(HidlTest, SafeUnionMoveAssignmentTest) {
2165     sp<SimpleChild> otherInterface = new SimpleChild();
2166     ASSERT_EQ(1, otherInterface->getStrongCount());
2167 
2168     InterfaceTypeSafeUnion safeUnion;
2169     safeUnion.c(otherInterface);
2170     EXPECT_EQ(2, otherInterface->getStrongCount());
2171 
2172     InterfaceTypeSafeUnion anotherSafeUnion;
2173     anotherSafeUnion.a(255);
2174     anotherSafeUnion = std::move(safeUnion);
2175 
2176     EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::c,
2177               anotherSafeUnion.getDiscriminator());
2178     EXPECT_EQ(2, otherInterface->getStrongCount());
2179 }
2180 
TEST_F(HidlTest,SafeUnionMutateTest)2181 TEST_F(HidlTest, SafeUnionMutateTest) {
2182     const std::array<int64_t, 5> testArray{-1, -2, -3, -4, -5};
2183     const std::string testString = "Test string";
2184     LargeSafeUnion safeUnion;
2185 
2186     safeUnion.f(testArray);
2187     safeUnion.f()[0] += 10;
2188     EXPECT_EQ(testArray[0] + 10, safeUnion.f()[0]);
2189 
2190     safeUnion.j(ISafeUnion::J());
2191     safeUnion.j().j3 = testString;
2192     EXPECT_EQ(testString, std::string(safeUnion.j().j3));
2193 }
2194 
TEST_F(HidlTest,SafeUnionNestedTest)2195 TEST_F(HidlTest, SafeUnionNestedTest) {
2196     SmallSafeUnion smallSafeUnion;
2197     smallSafeUnion.a(1);
2198 
2199     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& safeUnion) {
2200         EXPECT_OK(safeunionInterface->setL(
2201             safeUnion, smallSafeUnion, [&](const LargeSafeUnion& safeUnion) {
2202                 EXPECT_EQ(LargeSafeUnion::hidl_discriminator::l, safeUnion.getDiscriminator());
2203 
2204                 EXPECT_EQ(SmallSafeUnion::hidl_discriminator::a, safeUnion.l().getDiscriminator());
2205                 EXPECT_EQ(1, safeUnion.l().a());
2206             }));
2207     }));
2208 }
2209 
TEST_F(HidlTest,SafeUnionEnumTest)2210 TEST_F(HidlTest, SafeUnionEnumTest) {
2211     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& safeUnion) {
2212         EXPECT_OK(safeunionInterface->setM(
2213             safeUnion, ISafeUnion::BitField::V1, [&](const LargeSafeUnion& safeUnion) {
2214                 EXPECT_EQ(LargeSafeUnion::hidl_discriminator::m, safeUnion.getDiscriminator());
2215                 EXPECT_EQ(ISafeUnion::BitField::V1, safeUnion.m());
2216             }));
2217     }));
2218 }
2219 
TEST_F(HidlTest,SafeUnionBitFieldTest)2220 TEST_F(HidlTest, SafeUnionBitFieldTest) {
2221     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& safeUnion) {
2222         EXPECT_OK(safeunionInterface->setN(
2223             safeUnion, 0 | ISafeUnion::BitField::V1, [&](const LargeSafeUnion& safeUnion) {
2224                 EXPECT_EQ(LargeSafeUnion::hidl_discriminator::n, safeUnion.getDiscriminator());
2225                 EXPECT_EQ(0 | ISafeUnion::BitField::V1, safeUnion.n());
2226             }));
2227     }));
2228 }
2229 
TEST_F(HidlTest,SafeUnionInterfaceTest)2230 TEST_F(HidlTest, SafeUnionInterfaceTest) {
2231     const std::array<int8_t, 7> testArray{-1, -2, -3, 0, 1, 2, 3};
2232     const hidl_vec<hidl_string> testVector{"So", "Many", "Words"};
2233     const std::string testStringA = "Hello";
2234     const std::string testStringB = "World";
2235 
2236     EXPECT_OK(
2237         safeunionInterface->newInterfaceTypeSafeUnion([&](const InterfaceTypeSafeUnion& safeUnion) {
2238             EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::noinit,
2239                       safeUnion.getDiscriminator());
2240 
2241             isOk(safeunionInterface->setInterfaceB(
2242                 safeUnion, testArray, [&](const InterfaceTypeSafeUnion& safeUnion) {
2243                     EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::b,
2244                               safeUnion.getDiscriminator());
2245 
2246                     for (size_t i = 0; i < testArray.size(); i++) {
2247                         EXPECT_EQ(testArray[i], safeUnion.b()[i]);
2248                     }
2249 
2250                     EXPECT_OK(safeunionInterface->setInterfaceC(
2251                             safeUnion, manager, [&](const InterfaceTypeSafeUnion& safeUnion) {
2252                                 EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::c,
2253                                           safeUnion.getDiscriminator());
2254 
2255                                 using ::android::hardware::interfacesEqual;
2256                                 EXPECT_TRUE(interfacesEqual(safeUnion.c(), manager));
2257                             }));
2258                 }));
2259 
2260             EXPECT_OK(safeunionInterface->setInterfaceD(
2261                 safeUnion, testStringA, [&](const InterfaceTypeSafeUnion& safeUnion) {
2262                     EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::d,
2263                               safeUnion.getDiscriminator());
2264                     EXPECT_EQ(testStringA, safeUnion.d());
2265                 }));
2266 
2267             EXPECT_OK(safeunionInterface->setInterfaceE(
2268                 safeUnion, testVector, [&](const InterfaceTypeSafeUnion& safeUnion) {
2269                     EXPECT_EQ(InterfaceTypeSafeUnion::hidl_discriminator::e,
2270                               safeUnion.getDiscriminator());
2271                     EXPECT_EQ(testVector, safeUnion.e());
2272                 }));
2273         }));
2274 }
2275 
TEST_F(HidlTest,SafeUnionNullHandleTest)2276 TEST_F(HidlTest, SafeUnionNullHandleTest) {
2277     HandleTypeSafeUnion safeUnion;
2278 
2279     EXPECT_OK(safeunionInterface->setHandleA(
2280         safeUnion, hidl_handle(nullptr), [&](const HandleTypeSafeUnion& safeUnion) {
2281             EXPECT_EQ(HandleTypeSafeUnion::hidl_discriminator::a,
2282                       safeUnion.getDiscriminator());
2283 
2284             checkNativeHandlesDataEquality(nullptr, safeUnion.a().getNativeHandle());
2285         }));
2286 }
2287 
TEST_F(HidlTest,SafeUnionSimpleHandleTest)2288 TEST_F(HidlTest, SafeUnionSimpleHandleTest) {
2289     const std::array<int, 6> testData{2, -32, 10, -4329454, 11, 24};
2290     native_handle_t* h = native_handle_create(0, testData.size());
2291     ASSERT_EQ(sizeof(testData), testData.size() * sizeof(int));
2292     std::memcpy(h->data, testData.data(), sizeof(testData));
2293 
2294     std::array<hidl_handle, 5> testArray;
2295     for (size_t i = 0; i < testArray.size(); i++) {
2296         testArray[i].setTo(native_handle_clone(h), true /* shouldOwn */);
2297     }
2298 
2299     std::vector<hidl_handle> testVector(256);
2300     for (size_t i = 0; i < testVector.size(); i++) {
2301         testVector[i].setTo(native_handle_clone(h), true /* shouldOwn */);
2302     }
2303 
2304     EXPECT_OK(
2305         safeunionInterface->newHandleTypeSafeUnion([&](const HandleTypeSafeUnion& safeUnion) {
2306             EXPECT_OK(safeunionInterface->setHandleA(
2307                 safeUnion, hidl_handle(h), [&](const HandleTypeSafeUnion& safeUnion) {
2308                     EXPECT_EQ(HandleTypeSafeUnion::hidl_discriminator::a,
2309                               safeUnion.getDiscriminator());
2310 
2311                     checkNativeHandlesDataEquality(h, safeUnion.a().getNativeHandle());
2312                 }));
2313 
2314             EXPECT_OK(safeunionInterface->setHandleB(
2315                 safeUnion, testArray, [&](const HandleTypeSafeUnion& safeUnion) {
2316                     EXPECT_EQ(HandleTypeSafeUnion::hidl_discriminator::b,
2317                               safeUnion.getDiscriminator());
2318 
2319                     for (size_t i = 0; i < testArray.size(); i++) {
2320                         checkNativeHandlesDataEquality(h, safeUnion.b()[i].getNativeHandle());
2321                     }
2322                 }));
2323 
2324             EXPECT_OK(safeunionInterface->setHandleC(
2325                 safeUnion, testVector, [&](const HandleTypeSafeUnion& safeUnion) {
2326                     EXPECT_EQ(HandleTypeSafeUnion::hidl_discriminator::c,
2327                               safeUnion.getDiscriminator());
2328 
2329                     for (size_t i = 0; i < testVector.size(); i++) {
2330                         checkNativeHandlesDataEquality(h, safeUnion.c()[i].getNativeHandle());
2331                     }
2332                 }));
2333         }));
2334 
2335     native_handle_delete(h);
2336 }
2337 
TEST_F(HidlTest,SafeUnionVecOfHandlesWithOneFdTest)2338 TEST_F(HidlTest, SafeUnionVecOfHandlesWithOneFdTest) {
2339     const std::vector<std::string> testStrings{"This ", "is ", "so ", "much ", "data!\n"};
2340     const std::string testFileName = "/data/local/tmp/SafeUnionVecOfHandlesWithOneFdTest";
2341     const std::array<int, 6> testData{2, -32, 10, -4329454, 11, 24};
2342     ASSERT_EQ(sizeof(testData), testData.size() * sizeof(int));
2343 
2344     const std::string goldenResult = std::accumulate(testStrings.begin(),
2345                                                      testStrings.end(),
2346                                                      std::string());
2347 
2348     int fd = open(testFileName.c_str(), (O_RDWR | O_TRUNC | O_CREAT), (S_IRUSR | S_IWUSR));
2349     ASSERT_TRUE(fd >= 0);
2350 
2351     native_handle* h = native_handle_create(1 /* numFds */, testData.size() /* numInts */);
2352     std::memcpy(&(h->data[1]), testData.data(), sizeof(testData));
2353     h->data[0] = fd;
2354 
2355     hidl_vec<hidl_handle> testHandles(testStrings.size());
2356     for (size_t i = 0; i < testHandles.size(); i++) {
2357         testHandles[i].setTo(native_handle_clone(h), true /* shouldOwn */);
2358     }
2359 
2360     EXPECT_OK(
2361         safeunionInterface->newHandleTypeSafeUnion([&](const HandleTypeSafeUnion& safeUnion) {
2362             EXPECT_OK(safeunionInterface->setHandleC(
2363                 safeUnion, testHandles, [&](const HandleTypeSafeUnion& safeUnion) {
2364                     EXPECT_EQ(HandleTypeSafeUnion::hidl_discriminator::c,
2365                               safeUnion.getDiscriminator());
2366 
2367                     for (size_t i = 0; i < safeUnion.c().size(); i++) {
2368                         const native_handle_t* reference = testHandles[i].getNativeHandle();
2369                         const native_handle_t* result = safeUnion.c()[i].getNativeHandle();
2370                         checkNativeHandlesDataEquality(reference, result);
2371 
2372                         // Original FDs should be dup'd
2373                         int resultFd = result->data[0];
2374                         EXPECT_NE(reference->data[0], resultFd);
2375 
2376                         EXPECT_TRUE(android::base::WriteStringToFd(testStrings[i], resultFd));
2377                         EXPECT_EQ(0, fsync(resultFd));
2378                     }
2379                 }));
2380         }));
2381 
2382     std::string result;
2383     lseek(fd, 0, SEEK_SET);
2384 
2385     EXPECT_TRUE(android::base::ReadFdToString(fd, &result));
2386     EXPECT_EQ(goldenResult, result);
2387 
2388     native_handle_delete(h);
2389     EXPECT_EQ(0, close(fd));
2390     EXPECT_EQ(0, remove(testFileName.c_str()));
2391 }
2392 
TEST_F(HidlTest,SafeUnionHandleWithMultipleFdsTest)2393 TEST_F(HidlTest, SafeUnionHandleWithMultipleFdsTest) {
2394     const std::vector<std::string> testStrings{"This ", "is ", "so ", "much ", "data!\n"};
2395     const std::string testFileName = "/data/local/tmp/SafeUnionHandleWithMultipleFdsTest";
2396     const std::array<int, 6> testData{2, -32, 10, -4329454, 11, 24};
2397     ASSERT_EQ(sizeof(testData), testData.size() * sizeof(int));
2398 
2399     const std::string goldenResult = std::accumulate(testStrings.begin(),
2400                                                      testStrings.end(),
2401                                                      std::string());
2402 
2403     int fd = open(testFileName.c_str(), (O_RDWR | O_TRUNC | O_CREAT), (S_IRUSR | S_IWUSR));
2404     ASSERT_TRUE(fd >= 0);
2405 
2406     const int numFds = testStrings.size();
2407     native_handle* h = native_handle_create(numFds, testData.size() /* numInts */);
2408     std::memcpy(&(h->data[numFds]), testData.data(), sizeof(testData));
2409     for (size_t i = 0; i < numFds; i++) {
2410         h->data[i] = fd;
2411     }
2412 
2413     hidl_handle testHandle;
2414     testHandle.setTo(h, false /* shouldOwn */);
2415 
2416     EXPECT_OK(
2417         safeunionInterface->newHandleTypeSafeUnion([&](const HandleTypeSafeUnion& safeUnion) {
2418             EXPECT_OK(safeunionInterface->setHandleA(
2419                 safeUnion, testHandle, [&](const HandleTypeSafeUnion& safeUnion) {
2420                     EXPECT_EQ(HandleTypeSafeUnion::hidl_discriminator::a,
2421                               safeUnion.getDiscriminator());
2422 
2423                     const native_handle_t* result = safeUnion.a().getNativeHandle();
2424                     checkNativeHandlesDataEquality(h, result);
2425 
2426                     for (size_t i = 0; i < result->numFds; i++) {
2427                         // Original FDs should be dup'd
2428                         int resultFd = result->data[i];
2429                         EXPECT_NE(h->data[i], resultFd);
2430 
2431                         EXPECT_TRUE(android::base::WriteStringToFd(testStrings[i], resultFd));
2432                         EXPECT_EQ(0, fsync(resultFd));
2433                     }
2434                 }));
2435         }));
2436 
2437     std::string result;
2438     lseek(fd, 0, SEEK_SET);
2439 
2440     EXPECT_TRUE(android::base::ReadFdToString(fd, &result));
2441     EXPECT_EQ(goldenResult, result);
2442 
2443     native_handle_delete(h);
2444     EXPECT_EQ(0, close(fd));
2445     EXPECT_EQ(0, remove(testFileName.c_str()));
2446 }
2447 
TEST_F(HidlTest,SafeUnionEqualityTest)2448 TEST_F(HidlTest, SafeUnionEqualityTest) {
2449     EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& one) {
2450         EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& two) {
2451             EXPECT_TRUE(one == two);
2452             EXPECT_FALSE(one != two);
2453         }));
2454 
2455         EXPECT_OK(safeunionInterface->setA(one, 1, [&](const LargeSafeUnion& one) {
2456             EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& two) {
2457                 EXPECT_FALSE(one == two);
2458                 EXPECT_TRUE(one != two);
2459             }));
2460 
2461             EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& two) {
2462                 EXPECT_OK(safeunionInterface->setB(two, 1, [&](const LargeSafeUnion& two) {
2463                     EXPECT_FALSE(one == two);
2464                     EXPECT_TRUE(one != two);
2465                 }));
2466             }));
2467 
2468             EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& two) {
2469                 EXPECT_OK(safeunionInterface->setA(two, 2, [&](const LargeSafeUnion& two) {
2470                     EXPECT_FALSE(one == two);
2471                     EXPECT_TRUE(one != two);
2472                 }));
2473             }));
2474 
2475             EXPECT_OK(safeunionInterface->newLargeSafeUnion([&](const LargeSafeUnion& two) {
2476                 EXPECT_OK(safeunionInterface->setA(two, 1, [&](const LargeSafeUnion& two) {
2477                     EXPECT_TRUE(one == two);
2478                     EXPECT_FALSE(one != two);
2479                 }));
2480             }));
2481         }));
2482     }));
2483 }
2484 
TEST_F(HidlTest,SafeUnionSimpleDestructorTest)2485 TEST_F(HidlTest, SafeUnionSimpleDestructorTest) {
2486     sp<SimpleChild> otherInterface = new SimpleChild();
2487     ASSERT_EQ(1, otherInterface->getStrongCount());
2488 
2489     {
2490         InterfaceTypeSafeUnion safeUnion;
2491         safeUnion.c(otherInterface);
2492         EXPECT_EQ(2, otherInterface->getStrongCount());
2493     }
2494 
2495     EXPECT_EQ(1, otherInterface->getStrongCount());
2496 }
2497 
TEST_F(HidlTest,SafeUnionSwitchActiveComponentsDestructorTest)2498 TEST_F(HidlTest, SafeUnionSwitchActiveComponentsDestructorTest) {
2499     sp<SimpleChild> otherInterface = new SimpleChild();
2500     ASSERT_EQ(1, otherInterface->getStrongCount());
2501 
2502     InterfaceTypeSafeUnion safeUnion;
2503     safeUnion.c(otherInterface);
2504     EXPECT_EQ(2, otherInterface->getStrongCount());
2505 
2506     safeUnion.a(1);
2507     EXPECT_EQ(1, otherInterface->getStrongCount());
2508 }
2509 
TEST_F(HidlTest,SafeUnionCppSpecificTest)2510 TEST_F(HidlTest, SafeUnionCppSpecificTest) {
2511     ICppSafeUnion::PointerFmqSafeUnion pointerFmqSafeUnion;
2512     pointerFmqSafeUnion.fmqSync({std::vector<GrantorDescriptor>(), native_handle_create(0, 1), 5});
2513 
2514     EXPECT_OK(cppSafeunionInterface->repeatPointerFmqSafeUnion(
2515         pointerFmqSafeUnion, [&](const ICppSafeUnion::PointerFmqSafeUnion& fmq) {
2516             ASSERT_EQ(pointerFmqSafeUnion.getDiscriminator(), fmq.getDiscriminator());
2517             checkMQDescriptorEquality(pointerFmqSafeUnion.fmqSync(), fmq.fmqSync());
2518         }));
2519 
2520     ICppSafeUnion::FmqSafeUnion fmqSafeUnion;
2521     fmqSafeUnion.fmqUnsync({std::vector<GrantorDescriptor>(), native_handle_create(0, 1), 5});
2522 
2523     EXPECT_OK(cppSafeunionInterface->repeatFmqSafeUnion(
2524         fmqSafeUnion, [&](const ICppSafeUnion::FmqSafeUnion& fmq) {
2525             ASSERT_EQ(fmqSafeUnion.getDiscriminator(), fmq.getDiscriminator());
2526             checkMQDescriptorEquality(fmqSafeUnion.fmqUnsync(), fmq.fmqUnsync());
2527         }));
2528 }
2529 
2530 class HidlMultithreadTest : public ::testing::Test {
2531    public:
2532     sp<IMultithread> multithreadInterface;
2533     TestMode mode = TestMode::PASSTHROUGH;
2534 
SetUp()2535     void SetUp() override {
2536         ALOGI("Test setup beginning...");
2537         multithreadInterface = gHidlEnvironment->multithreadInterface;
2538         mode = gHidlEnvironment->mode;
2539         ALOGI("Test setup complete");
2540     }
2541 
test_multithread(int maxThreads,int numThreads)2542     void test_multithread(int maxThreads, int numThreads) {
2543         LOG(INFO) << "CLIENT call setNumThreads("
2544                   << maxThreads << ", " << numThreads << ")";
2545         EXPECT_OK(multithreadInterface->setNumThreads(maxThreads, numThreads));
2546 
2547         std::vector<std::future<bool>> threads;
2548 
2549         for (int i = 0; i != numThreads; ++i) {
2550             LOG(INFO) << "CLIENT call runNewThread";
2551             threads.emplace_back(std::async(
2552                 std::launch::async, [&]() { return (bool)multithreadInterface->runNewThread(); }));
2553         }
2554 
2555         bool noTimeout = std::all_of(threads.begin(), threads.end(),
2556                                      [](std::future<bool>& thread) { return thread.get(); });
2557         EXPECT_EQ(noTimeout, maxThreads >= numThreads || mode == PASSTHROUGH);
2558     }
2559 };
2560 
2561 // If it fails first try to increment timeout duration at
2562 // hardware/interfaces/tests/multithread/1.0/default
TEST_F(HidlMultithreadTest,MultithreadTest)2563 TEST_F(HidlMultithreadTest, MultithreadTest) {
2564     // configureRpcThreadpool doesn't stop threads,
2565     // so maxThreads should not decrease
2566     test_multithread(1, 1);
2567     test_multithread(2, 1);
2568     test_multithread(2, 2);
2569     test_multithread(2, 3);
2570     test_multithread(10, 5);
2571     test_multithread(10, 10);
2572     test_multithread(10, 15);
2573     test_multithread(20, 30);
2574     test_multithread(20, 20);
2575     test_multithread(20, 10);
2576 }
2577 
2578 template <class T>
2579 struct WaitForServer {
runWaitForServer2580     static void run(const std::string& serviceName) {
2581         ::android::hardware::details::waitForHwService(T::descriptor, serviceName);
2582     }
2583 };
2584 
forkAndRunTests(TestMode mode,bool enableDelayMeasurementTests)2585 int forkAndRunTests(TestMode mode, bool enableDelayMeasurementTests) {
2586     pid_t child;
2587     int status;
2588 
2589     const char* modeText = (mode == BINDERIZED) ? "BINDERIZED" : "PASSTHROUGH";
2590     ALOGI("Start running tests in %s mode...", modeText);
2591     fprintf(stdout, "Start running tests in %s mode...\n", modeText);
2592     fflush(stdout);
2593 
2594     if ((child = fork()) == 0) {
2595         gHidlEnvironment = static_cast<HidlEnvironment *>(
2596                 ::testing::AddGlobalTestEnvironment(new HidlEnvironment(
2597                         mode, enableDelayMeasurementTests)));
2598         int testStatus = RUN_ALL_TESTS();
2599         if(testStatus == 0) {
2600             exit(0);
2601         }
2602         int failed = ::testing::UnitTest::GetInstance()->failed_test_count();
2603         if (failed == 0) {
2604             exit(-testStatus);
2605         }
2606         exit(failed);
2607     }
2608     waitpid(child, &status, 0 /* options */);
2609     ALOGI("All tests finished in %s mode.", modeText);
2610     fprintf(stdout, "All tests finished in %s mode.\n", modeText);
2611     fflush(stdout);
2612     return status;
2613 }
2614 
handleStatus(int status,const char * mode)2615 void handleStatus(int status, const char *mode) {
2616     if (status != 0) {
2617         if (WIFEXITED(status)) {
2618             status = WEXITSTATUS(status);
2619             if (status < 0) {
2620                 fprintf(stdout, "    RUN_ALL_TESTS returns %d for %s mode.\n", -status, mode);
2621             } else {
2622                 fprintf(stdout, "    %d test(s) failed for %s mode.\n", status, mode);
2623             }
2624         } else {
2625             fprintf(stdout, "    ERROR: %s child process exited abnormally with %d\n", mode, status);
2626         }
2627     }
2628 }
2629 
usage(const char * me)2630 static void usage(const char *me) {
2631     fprintf(stderr,
2632             "usage: %s [-b] [-p] [-d] [GTEST_OPTIONS]\n",
2633             me);
2634 
2635     fprintf(stderr, "         -b binderized mode only\n");
2636     fprintf(stderr, "         -p passthrough mode only\n");
2637     fprintf(stderr, "            (if -b and -p are both missing or both present, "
2638                                  "both modes are tested.)\n");
2639     fprintf(stderr, "         -d Enable delay measurement tests\n");
2640 }
2641 
main(int argc,char ** argv)2642 int main(int argc, char **argv) {
2643     android::hardware::details::setTrebleTestingOverride(true);
2644 
2645     const char *me = argv[0];
2646     bool b = false;
2647     bool p = false;
2648     bool d = false;
2649     struct option longopts[] = {{nullptr,0,nullptr,0}};
2650     int res;
2651     while ((res = getopt_long(argc, argv, "hbpd", longopts, nullptr)) >= 0) {
2652         switch (res) {
2653             case 'h': {
2654                 usage(me);
2655                 exit(1);
2656             } break;
2657 
2658             case 'b': {
2659                 b = true;
2660             } break;
2661 
2662             case 'p': {
2663                 p = true;
2664             } break;
2665 
2666             case 'd': {
2667                 d = true;
2668             } break;
2669 
2670             case '?':
2671             default: {
2672                 // ignore. pass to gTest.
2673             } break;
2674         }
2675     }
2676     if (!b && !p) {
2677         b = p = true;
2678     }
2679 
2680     ::testing::InitGoogleTest(&argc, argv);
2681     // put test in child process because RUN_ALL_TESTS
2682     // should not be run twice.
2683     int pStatus = p ? forkAndRunTests(PASSTHROUGH, d) : 0;
2684     int bStatus = b ? forkAndRunTests(BINDERIZED, d)  : 0;
2685 
2686     fprintf(stdout, "\n=========================================================\n\n"
2687                     "    Summary:\n\n");
2688     if (p) {
2689         ALOGI("PASSTHROUGH Test result = %d", pStatus);
2690         handleStatus(pStatus, "PASSTHROUGH");
2691     }
2692     if (b) {
2693         runOnEachServer<WaitForServer>();
2694         ALOGI("BINDERIZED Test result = %d", bStatus);
2695         handleStatus(bStatus, "BINDERIZED ");
2696     }
2697 
2698     if (pStatus == 0 && bStatus == 0) {
2699         fprintf(stdout, "    Hooray! All tests passed.\n");
2700     }
2701     fprintf(stdout, "\n=========================================================\n\n");
2702 
2703     return pStatus + bStatus != 0;
2704 }
2705