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