1 #define LOG_TAG "hidl_test_client"
2 
3 #include "FooCallback.h"
4 
5 #include <android-base/logging.h>
6 
7 #include <android/hidl/manager/1.0/IServiceManager.h>
8 #include <android/hidl/manager/1.0/IServiceNotification.h>
9 
10 #include <android/hidl/allocator/1.0/IAllocator.h>
11 #include <android/hidl/memory/1.0/IMemory.h>
12 
13 #include <android/hidl/token/1.0/ITokenManager.h>
14 
15 #include <android/hardware/tests/foo/1.0/IFoo.h>
16 #include <android/hardware/tests/foo/1.0/BnHwSimple.h>
17 #include <android/hardware/tests/foo/1.0/BsSimple.h>
18 #include <android/hardware/tests/foo/1.0/BpHwSimple.h>
19 #include <android/hardware/tests/bar/1.0/IBar.h>
20 #include <android/hardware/tests/bar/1.0/BpHwBar.h>
21 #include <android/hardware/tests/bar/1.0/BnHwBar.h>
22 #include <android/hardware/tests/bar/1.0/IComplicated.h>
23 #include <android/hardware/tests/bar/1.0/IImportRules.h>
24 #include <android/hardware/tests/baz/1.0/IBaz.h>
25 #include <android/hardware/tests/hash/1.0/IHash.h>
26 #include <android/hardware/tests/inheritance/1.0/IFetcher.h>
27 #include <android/hardware/tests/inheritance/1.0/IGrandparent.h>
28 #include <android/hardware/tests/inheritance/1.0/IParent.h>
29 #include <android/hardware/tests/inheritance/1.0/IChild.h>
30 #include <android/hardware/tests/memory/1.0/IMemoryTest.h>
31 #include <android/hardware/tests/pointer/1.0/IGraph.h>
32 #include <android/hardware/tests/pointer/1.0/IPointer.h>
33 
34 #include <gtest/gtest.h>
35 #if GTEST_IS_THREADSAFE
36 #include <sys/types.h>
37 #include <sys/wait.h>
38 #include <signal.h>
39 #include <errno.h>
40 #include <pthread.h>
41 #else
42 #error "GTest did not detect pthread library."
43 #endif
44 
45 #include <algorithm>
46 #include <condition_variable>
47 #include <getopt.h>
48 #include <inttypes.h>
49 #include <mutex>
50 #include <set>
51 #include <sstream>
52 #include <utility>
53 #include <vector>
54 
55 #include <hidl-test/FooHelper.h>
56 #include <hidl-test/PointerHelper.h>
57 
58 #include <hidl/Status.h>
59 #include <hidlmemory/mapping.h>
60 
61 #include <utils/Condition.h>
62 #include <utils/Timers.h>
63 
64 #define EXPECT_OK(__ret__) EXPECT_TRUE(isOk(__ret__))
65 #define EXPECT_FAIL(__ret__) EXPECT_FALSE(isOk(__ret__))
66 #define EXPECT_ARRAYEQ(__a1__, __a2__, __size__) EXPECT_TRUE(isArrayEqual(__a1__, __a2__, __size__))
67 
68 // TODO uncomment this when kernel is patched with pointer changes.
69 //#define HIDL_RUN_POINTER_TESTS 1
70 
71 // forward declarations.
72 class HidlEnvironment;
73 
74 // static storage
75 enum TestMode {
76     BINDERIZED,
77     PASSTHROUGH
78 };
79 
80 static HidlEnvironment *gHidlEnvironment = nullptr;
81 
82 using ::android::hardware::tests::foo::V1_0::Abc;
83 using ::android::hardware::tests::foo::V1_0::IFoo;
84 using ::android::hardware::tests::foo::V1_0::IFooCallback;
85 using ::android::hardware::tests::foo::V1_0::ISimple;
86 using ::android::hardware::tests::foo::V1_0::implementation::FooCallback;
87 using ::android::hardware::tests::bar::V1_0::IBar;
88 using ::android::hardware::tests::bar::V1_0::IComplicated;
89 using ::android::hardware::tests::baz::V1_0::IBaz;
90 using ::android::hardware::tests::hash::V1_0::IHash;
91 using ::android::hardware::tests::inheritance::V1_0::IFetcher;
92 using ::android::hardware::tests::inheritance::V1_0::IGrandparent;
93 using ::android::hardware::tests::inheritance::V1_0::IParent;
94 using ::android::hardware::tests::inheritance::V1_0::IChild;
95 using ::android::hardware::tests::pointer::V1_0::IGraph;
96 using ::android::hardware::tests::pointer::V1_0::IPointer;
97 using ::android::hardware::tests::memory::V1_0::IMemoryTest;
98 using ::android::hardware::Return;
99 using ::android::hardware::Void;
100 using ::android::hardware::hidl_array;
101 using ::android::hardware::hidl_death_recipient;
102 using ::android::hardware::hidl_memory;
103 using ::android::hardware::hidl_string;
104 using ::android::hardware::hidl_vec;
105 using ::android::hidl::allocator::V1_0::IAllocator;
106 using ::android::hidl::base::V1_0::IBase;
107 using ::android::hidl::manager::V1_0::IServiceManager;
108 using ::android::hidl::manager::V1_0::IServiceNotification;
109 using ::android::hidl::memory::V1_0::IMemory;
110 using ::android::hidl::token::V1_0::ITokenManager;
111 using ::android::sp;
112 using ::android::wp;
113 using ::android::to_string;
114 using ::android::Mutex;
115 using ::android::MultiDimensionalToString;
116 using ::android::Condition;
117 using ::android::DELAY_S;
118 using ::android::DELAY_NS;
119 using ::android::TOLERANCE_NS;
120 using ::android::ONEWAY_TOLERANCE_NS;
121 using std::to_string;
122 
123 template <typename T>
isOk(const::android::hardware::Return<T> & ret)124 static inline ::testing::AssertionResult isOk(const ::android::hardware::Return<T> &ret) {
125     return ret.isOk()
126         ? (::testing::AssertionSuccess() << ret.description())
127         : (::testing::AssertionFailure() << ret.description());
128 }
129 
130 template<typename T, typename S>
isArrayEqual(const T arr1,const S arr2,size_t size)131 static inline bool isArrayEqual(const T arr1, const S arr2, size_t size) {
132     for(size_t i = 0; i < size; i++)
133         if(arr1[i] != arr2[i])
134             return false;
135     return true;
136 }
137 
138 template<typename T>
to_string(std::set<T> set)139 std::string to_string(std::set<T> set) {
140     std::stringstream ss;
141     ss << "{";
142 
143     bool first = true;
144     for (const T &item : set) {
145         if (first) {
146             first = false;
147         } else {
148             ss << ", ";
149         }
150 
151         ss << to_string(item);
152     }
153 
154     ss << "}";
155 
156     return ss.str();
157 }
158 
159 struct Simple : public ISimple {
SimpleSimple160     Simple(int32_t cookie)
161         : mCookie(cookie) {
162     }
163 
getCookieSimple164     Return<int32_t> getCookie() override {
165         return mCookie;
166     }
167 
customVecIntSimple168     Return<void> customVecInt(customVecInt_cb _cb) override {
169         _cb(hidl_vec<int32_t>());
170         return Void();
171     }
172 
customVecStrSimple173     Return<void> customVecStr(customVecStr_cb _cb) override {
174         hidl_vec<hidl_string> vec;
175         vec.resize(2);
176         _cb(vec);
177         return Void();
178     }
179 
mystrSimple180     Return<void> mystr(mystr_cb _cb) override {
181         _cb(hidl_string());
182         return Void();
183     }
184 
myhandleSimple185     Return<void> myhandle(myhandle_cb _cb) override {
186         auto h = native_handle_create(0, 1);
187         _cb(h);
188         native_handle_delete(h);
189         return Void();
190     }
191 
192 private:
193     int32_t mCookie;
194 };
195 
196 struct SimpleParent : public IParent {
doGrandparentSimpleParent197     Return<void> doGrandparent() override {
198         return Void();
199     }
doParentSimpleParent200     Return<void> doParent() override {
201         return Void();
202     }
203 };
204 
205 struct SimpleChild : public IChild {
doGrandparentSimpleChild206     Return<void> doGrandparent() override {
207         return Void();
208     }
doParentSimpleChild209     Return <void> doParent() override {
210         return Void();
211     }
doChildSimpleChild212     Return <void> doChild() override {
213         return Void();
214     }
215 };
216 
217 struct Complicated : public IComplicated {
ComplicatedComplicated218     Complicated(int32_t cookie)
219         : mCookie(cookie) {
220     }
221 
getCookieComplicated222     Return<int32_t> getCookie() override {
223         return mCookie;
224     }
225 
customVecIntComplicated226     Return<void> customVecInt(customVecInt_cb _cb) override {
227         _cb(hidl_vec<int32_t>());
228         return Void();
229     }
customVecStrComplicated230     Return<void> customVecStr(customVecStr_cb _cb) override {
231         hidl_vec<hidl_string> vec;
232         vec.resize(2);
233         _cb(vec);
234         return Void();
235     }
236 
mystrComplicated237     Return<void> mystr(mystr_cb _cb) override {
238         _cb(hidl_string());
239         return Void();
240     }
241 
myhandleComplicated242     Return<void> myhandle(myhandle_cb _cb) override {
243         auto h = native_handle_create(0, 1);
244         _cb(h);
245         native_handle_delete(h);
246         return Void();
247     }
248 
249 private:
250     int32_t mCookie;
251 };
252 
253 // Ensure (statically) that the types in IImportRules resolves to the correct types by
254 // overriding the methods with fully namespaced types as arguments.
255 struct MyImportRules : public ::android::hardware::tests::bar::V1_0::IImportRules {
rule0aMyImportRules256     Return<void> rule0a(
257             const ::android::hardware::tests::bar::V1_0::IImportRules::Outer&) override {
258         return Void();
259     }
260 
rule0a1MyImportRules261     Return<void> rule0a1(
262             const ::android::hardware::tests::bar::V1_0::IImportRules::Outer&) override {
263         return Void();
264     }
265 
rule0bMyImportRules266     Return<void> rule0b(
267             const ::android::hardware::tests::bar::V1_0::IImportRules::Outer&) override {
268         return Void();
269     }
270 
rule0cMyImportRules271     Return<void> rule0c(const ::android::hardware::tests::foo::V1_0::Outer&) override {
272         return Void();
273     }
274 
rule0dMyImportRules275     Return<void> rule0d(const ::android::hardware::tests::foo::V1_0::Outer&) override {
276         return Void();
277     }
278 
rule0eMyImportRules279     Return<void> rule0e(
280             const ::android::hardware::tests::bar::V1_0::IImportRules::Outer::Inner&) override {
281         return Void();
282     }
283 
rule0fMyImportRules284     Return<void> rule0f(
285             const ::android::hardware::tests::bar::V1_0::IImportRules::Outer::Inner&) override {
286         return Void();
287     }
288 
rule0gMyImportRules289     Return<void> rule0g(const ::android::hardware::tests::foo::V1_0::Outer::Inner&) override {
290         return Void();
291     }
292 
rule0hMyImportRules293     Return<void> rule0h(const ::android::hardware::tests::foo::V1_0::Outer::Inner&) override {
294         return Void();
295     }
296 
rule1aMyImportRules297     Return<void> rule1a(const ::android::hardware::tests::bar::V1_0::Def&) override {
298         return Void();
299     }
300 
rule1bMyImportRules301     Return<void> rule1b(const ::android::hardware::tests::foo::V1_0::Def&) override {
302         return Void();
303     }
304 
rule2aMyImportRules305     Return<void> rule2a(const ::android::hardware::tests::foo::V1_0::Unrelated&) override {
306         return Void();
307     }
308 
rule2bMyImportRules309     Return<void> rule2b(const sp<::android::hardware::tests::foo::V1_0::IFooCallback>&) override {
310         return Void();
311     }
312 };
313 
314 struct ServiceNotification : public IServiceNotification {
315     std::mutex mutex;
316     std::condition_variable condition;
317 
onRegistrationServiceNotification318     Return<void> onRegistration(const hidl_string &fqName,
319                                 const hidl_string &name,
320                                 bool preexisting) override {
321         if (preexisting) {
322             // not interested in things registered from previous runs of hidl_test
323             return Void();
324         }
325 
326         std::unique_lock<std::mutex> lock(mutex);
327 
328         mRegistered.push_back(std::string(fqName.c_str()) + "/" + name.c_str());
329 
330         lock.unlock();
331         condition.notify_one();
332 
333         return Void();
334     }
335 
getRegistrationsServiceNotification336     const std::vector<std::string> &getRegistrations() const {
337         return mRegistered;
338     }
339 
340 private:
341     std::vector<std::string> mRegistered{};
342 };
343 
344 class HidlEnvironment : public ::testing::Environment {
345 public:
346     sp<IServiceManager> manager;
347     sp<ITokenManager> tokenManager;
348     sp<IAllocator> ashmemAllocator;
349     sp<IMemoryTest> memoryTest;
350     sp<IFetcher> fetcher;
351     sp<IFoo> foo;
352     sp<IBaz> dyingBaz;
353     sp<IBar> bar;
354     sp<IGraph> graphInterface;
355     sp<IPointer> pointerInterface;
356     sp<IPointer> validationPointerInterface;
357     TestMode mode;
358     bool enableDelayMeasurementTests;
HidlEnvironment(TestMode mode,bool enableDelayMeasurementTests)359     HidlEnvironment(TestMode mode, bool enableDelayMeasurementTests) :
360         mode(mode), enableDelayMeasurementTests(enableDelayMeasurementTests) {};
361 
getServices()362     void getServices() {
363         manager = IServiceManager::getService();
364 
365         // alternatively:
366         // manager = defaultServiceManager()
367 
368         ASSERT_NE(manager, nullptr);
369         ASSERT_TRUE(manager->isRemote()); // manager is always remote
370 
371         tokenManager = ITokenManager::getService();
372         ASSERT_NE(tokenManager, nullptr);
373         ASSERT_TRUE(tokenManager->isRemote()); // tokenManager is always remote
374 
375         ashmemAllocator = IAllocator::getService("ashmem");
376         ASSERT_NE(ashmemAllocator, nullptr);
377         ASSERT_TRUE(ashmemAllocator->isRemote()); // allocator is always remote
378 
379         // getStub is true if we are in passthrough mode to skip checking
380         // binderized server, false for binderized mode.
381 
382         memoryTest = IMemoryTest::getService("memory", mode == PASSTHROUGH /* getStub */);
383         ASSERT_NE(memoryTest, nullptr);
384         ASSERT_EQ(memoryTest->isRemote(), mode == BINDERIZED);
385 
386         fetcher = IFetcher::getService("fetcher", mode == PASSTHROUGH /* getStub */);
387         ASSERT_NE(fetcher, nullptr);
388         ASSERT_EQ(fetcher->isRemote(), mode == BINDERIZED);
389 
390         foo = IFoo::getService("foo", mode == PASSTHROUGH /* getStub */);
391         ASSERT_NE(foo, nullptr);
392         ASSERT_EQ(foo->isRemote(), mode == BINDERIZED);
393 
394         dyingBaz = IBaz::getService("dyingBaz", mode == PASSTHROUGH /* getStub */);
395         ASSERT_NE(foo, nullptr);
396         ASSERT_EQ(foo->isRemote(), mode == BINDERIZED);
397 
398         bar = IBar::getService("foo", mode == PASSTHROUGH /* getStub */);
399         ASSERT_NE(bar, nullptr);
400         ASSERT_EQ(bar->isRemote(), mode == BINDERIZED);
401 
402         graphInterface = IGraph::getService("graph", mode == PASSTHROUGH /* getStub */);
403         ASSERT_NE(graphInterface, nullptr);
404         ASSERT_EQ(graphInterface->isRemote(), mode == BINDERIZED);
405 
406         pointerInterface = IPointer::getService("pointer", mode == PASSTHROUGH /* getStub */);
407         ASSERT_NE(pointerInterface, nullptr);
408         ASSERT_EQ(pointerInterface->isRemote(), mode == BINDERIZED);
409 
410         // use passthrough mode as the validation object.
411         validationPointerInterface = IPointer::getService("pointer", true /* getStub */);
412         ASSERT_NE(validationPointerInterface, nullptr);
413     }
414 
SetUp()415     virtual void SetUp() {
416         ALOGI("Environment setup beginning...");
417         getServices();
418         ALOGI("Environment setup complete.");
419     }
420 };
421 
422 class HidlTest : public ::testing::Test {
423 public:
424     sp<IServiceManager> manager;
425     sp<ITokenManager> tokenManager;
426     sp<IAllocator> ashmemAllocator;
427     sp<IMemoryTest> memoryTest;
428     sp<IFetcher> fetcher;
429     sp<IFoo> foo;
430     sp<IBaz> dyingBaz;
431     sp<IBar> bar;
432     sp<IGraph> graphInterface;
433     sp<IPointer> pointerInterface;
434     sp<IPointer> validationPointerInterface;
435     TestMode mode = TestMode::PASSTHROUGH;
436 
SetUp()437     virtual void SetUp() override {
438         ALOGI("Test setup beginning...");
439         manager = gHidlEnvironment->manager;
440         tokenManager = gHidlEnvironment->tokenManager;
441         ashmemAllocator = gHidlEnvironment->ashmemAllocator;
442         memoryTest = gHidlEnvironment->memoryTest;
443         fetcher = gHidlEnvironment->fetcher;
444         foo = gHidlEnvironment->foo;
445         dyingBaz = gHidlEnvironment->dyingBaz;
446         bar = gHidlEnvironment->bar;
447         graphInterface = gHidlEnvironment->graphInterface;
448         pointerInterface = gHidlEnvironment->pointerInterface;
449         validationPointerInterface = gHidlEnvironment->validationPointerInterface;
450         mode = gHidlEnvironment->mode;
451         ALOGI("Test setup complete");
452     }
453 };
454 
TEST_F(HidlTest,ToStringTest)455 TEST_F(HidlTest, ToStringTest) {
456     using namespace android::hardware;
457 
458     LOG(INFO) << toString(IFoo::Everything{});
459 
460     // Note that handles don't need to be deleted because MQDescriptor takes ownership
461     // and deletes them when destructed.
462     auto handle = native_handle_create(0, 1);
463     auto handle2 = native_handle_create(0, 1);
464     handle->data[0] = 5;
465     handle2->data[0] = 6;
466     IFoo::Everything e {
467         .u = {.p = reinterpret_cast<void *>(0x5)},
468         .number = 10,
469         .h = handle,
470         .descSync = {std::vector<GrantorDescriptor>(), handle, 5},
471         .descUnsync = {std::vector<GrantorDescriptor>(), handle2, 6},
472         .mem = hidl_memory("mymem", handle, 5),
473         .p = reinterpret_cast<void *>(0x6),
474         .vs = {"hello", "world"},
475         .multidimArray = hidl_vec<hidl_string>{"hello", "great", "awesome", "nice"}.data(),
476         .sArray = hidl_vec<hidl_string>{"awesome", "thanks", "you're welcome"}.data(),
477         .anotherStruct = {.first = "first", .last = "last"},
478         .bf = IFoo::BitField::V0 | IFoo::BitField::V2
479     };
480     LOG(INFO) << toString(e);
481     LOG(INFO) << toString(foo);
482     // toString is for debugging purposes only; no good EXPECT
483     // statement can be written here.
484 }
485 
TEST_F(HidlTest,PassthroughLookupTest)486 TEST_F(HidlTest, PassthroughLookupTest) {
487     // IFoo is special because it returns an interface no matter
488     //   what instance name is requested. In general, this is BAD!
489     EXPECT_NE(nullptr, IFoo::getService("", true /* getStub */).get());
490     EXPECT_NE(nullptr, IFoo::getService("a", true /* getStub */).get());
491     EXPECT_NE(nullptr, IFoo::getService("asdf", true /* getStub */).get());
492     EXPECT_NE(nullptr, IFoo::getService("::::::::", true /* getStub */).get());
493     EXPECT_NE(nullptr, IFoo::getService("/////", true /* getStub */).get());
494     EXPECT_NE(nullptr, IFoo::getService("\n", true /* getStub */).get());
495 }
496 
TEST_F(HidlTest,EnumToStringTest)497 TEST_F(HidlTest, EnumToStringTest) {
498     using namespace std::string_literals;
499     using ::android::hardware::tests::foo::V1_0::toString;
500     // toString for enum
501     EXPECT_EQ(toString(IFoo::BitField::V0), "V0"s);
502     EXPECT_EQ(toString(static_cast<IFoo::BitField>(0)), "0"s)
503             << "Invalid enum isn't stringified correctly.";
504     EXPECT_EQ(toString(static_cast<IFoo::BitField>(IFoo::BitField::V0 | IFoo::BitField::V2)), "0x5"s)
505             << "Invalid enum isn't stringified correctly.";
506     // dump bitfields
507     EXPECT_EQ(toString<IFoo::BitField>(0 | IFoo::BitField::V0), "V0 (0x1)"s);
508     EXPECT_EQ(toString<IFoo::BitField>(0 | IFoo::BitField::V0 | IFoo::BitField::V2), "V0 | V2 (0x5)"s);
509     EXPECT_EQ(toString<IFoo::BitField>(0xF), "V0 | V1 | V2 | V3 | VALL (0xf)"s);
510     EXPECT_EQ(toString<IFoo::BitField>(0xFF), "V0 | V1 | V2 | V3 | VALL | 0xf0 (0xff)"s);
511 }
512 
TEST_F(HidlTest,PingTest)513 TEST_F(HidlTest, PingTest) {
514     EXPECT_OK(manager->ping());
515 }
516 
TEST_F(HidlTest,TryGetServiceTest)517 TEST_F(HidlTest, TryGetServiceTest) {
518     sp<IServiceManager> dne = IServiceManager::tryGetService("boss");
519     ASSERT_EQ(dne, nullptr);
520 
521     sp<IServiceManager> manager = IServiceManager::tryGetService();
522     ASSERT_NE(manager, nullptr);
523 }
524 
TEST_F(HidlTest,HashTest)525 TEST_F(HidlTest, HashTest) {
526     uint8_t ihash[32] = {74,38,204,105,102,117,11,15,207,7,238,198,29,35,30,62,100,
527             216,131,182,3,61,162,241,215,211,6,20,251,143,125,161};
528     auto service = IHash::getService(mode == PASSTHROUGH /* getStub */);
529     EXPECT_OK(service->getHashChain([&] (const auto &chain) {
530         EXPECT_EQ(chain[0].size(), 32u);
531         EXPECT_ARRAYEQ(ihash, chain[0], 32);
532         EXPECT_OK(manager->getHashChain([&] (const auto &managerChain) {
533             EXPECT_EQ(chain[chain.size() - 1].size(), managerChain[managerChain.size() - 1].size());
534             EXPECT_ARRAYEQ(chain[chain.size() - 1], managerChain[managerChain.size() - 1],
535                     chain[chain.size() - 1].size()) << "Hash for IBase doesn't match!";
536         }));
537     }));
538 }
539 
TEST_F(HidlTest,ServiceListTest)540 TEST_F(HidlTest, ServiceListTest) {
541     static const std::set<std::string> binderizedSet = {
542         "android.hardware.tests.pointer@1.0::IPointer/pointer",
543         "android.hardware.tests.bar@1.0::IBar/foo",
544         "android.hardware.tests.inheritance@1.0::IFetcher/fetcher",
545         "android.hardware.tests.inheritance@1.0::IParent/parent",
546         "android.hardware.tests.inheritance@1.0::IParent/child",
547         "android.hardware.tests.inheritance@1.0::IChild/child",
548         "android.hardware.tests.pointer@1.0::IGraph/graph",
549         "android.hardware.tests.inheritance@1.0::IGrandparent/child",
550         "android.hardware.tests.foo@1.0::IFoo/foo",
551         "android.hidl.manager@1.0::IServiceManager/default",
552     };
553 
554     static const std::set<std::string> passthroughSet = {
555         "android.hidl.manager@1.0::IServiceManager/default"
556     };
557 
558     std::set<std::string> activeSet;
559 
560     switch(mode) {
561         case BINDERIZED: {
562             activeSet = binderizedSet;
563         } break;
564 
565         case PASSTHROUGH: {
566             activeSet = passthroughSet;
567         } break;
568         default:
569             EXPECT_TRUE(false) << "unrecognized mode";
570     }
571 
572     EXPECT_OK(manager->list([&activeSet](const hidl_vec<hidl_string> &registered){
573         std::set<std::string> registeredSet;
574 
575         for (size_t i = 0; i < registered.size(); i++) {
576             registeredSet.insert(registered[i]);
577         }
578 
579         std::set<std::string> difference;
580         std::set_difference(activeSet.begin(), activeSet.end(),
581                             registeredSet.begin(), registeredSet.end(),
582                             std::inserter(difference, difference.begin()));
583 
584         EXPECT_EQ(difference.size(), 0u) << "service(s) not registered " << to_string(difference);
585     }));
586 }
587 
588 // passthrough TODO(b/31959402)
TEST_F(HidlTest,ServiceListByInterfaceTest)589 TEST_F(HidlTest, ServiceListByInterfaceTest) {
590     if (mode == BINDERIZED) {
591         EXPECT_OK(manager->listByInterface(IParent::descriptor,
592             [](const hidl_vec<hidl_string> &registered) {
593                 std::set<std::string> registeredSet;
594 
595                 for (size_t i = 0; i < registered.size(); i++) {
596                     registeredSet.insert(registered[i]);
597                 }
598 
599                 std::set<std::string> activeSet = {
600                     "parent", "child"
601                 };
602                 std::set<std::string> difference;
603                 std::set_difference(activeSet.begin(), activeSet.end(),
604                                     registeredSet.begin(), registeredSet.end(),
605                                     std::inserter(difference, difference.begin()));
606 
607                 EXPECT_EQ(difference.size(), 0u) << "service(s) not registered " << to_string(difference);
608             }));
609     }
610 }
611 
612 // passthrough TODO(b/31959402)
TEST_F(HidlTest,ServiceParentTest)613 TEST_F(HidlTest, ServiceParentTest) {
614     if (mode == BINDERIZED) {
615         sp<IParent> parent = IParent::getService("child");
616 
617         EXPECT_NE(parent, nullptr);
618     }
619 }
620 
621 // passthrough TODO(b/31959402)
TEST_F(HidlTest,ServiceNotificationTest)622 TEST_F(HidlTest, ServiceNotificationTest) {
623     if (mode == BINDERIZED) {
624         ServiceNotification *notification = new ServiceNotification();
625 
626         std::string instanceName = "test-instance";
627         EXPECT_TRUE(IParent::registerForNotifications(instanceName, notification));
628 
629         EXPECT_EQ(::android::OK, (new SimpleChild())->registerAsService(instanceName));
630         EXPECT_EQ(::android::OK, (new SimpleParent())->registerAsService(instanceName));
631 
632         std::unique_lock<std::mutex> lock(notification->mutex);
633 
634         notification->condition.wait_for(
635                 lock,
636                 std::chrono::milliseconds(2),
637                 [&notification]() {
638                    return notification->getRegistrations().size() >= 2;
639                 });
640 
641         std::vector<std::string> registrations = notification->getRegistrations();
642 
643         EXPECT_EQ(registrations.size(), 2u);
644 
645         EXPECT_EQ(to_string(registrations.data(), registrations.size()),
646                   std::string("['") + IParent::descriptor + "/" + instanceName +
647                              "', '" + IParent::descriptor + "/" + instanceName + "']");
648     }
649 }
650 
651 // passthrough TODO(b/31959402)
TEST_F(HidlTest,ServiceAllNotificationTest)652 TEST_F(HidlTest, ServiceAllNotificationTest) {
653     if (mode == BINDERIZED) {
654         ServiceNotification *notification = new ServiceNotification();
655 
656         std::string instanceOne = "test-instance-one";
657         std::string instanceTwo = "test-instance-two";
658         EXPECT_TRUE(ISimple::registerForNotifications("", notification));
659 
660         Simple* instanceA = new Simple(1);
661         EXPECT_EQ(::android::OK, instanceA->registerAsService(instanceOne));
662         Simple* instanceB = new Simple(2);
663         EXPECT_EQ(::android::OK, instanceB->registerAsService(instanceTwo));
664 
665         std::unique_lock<std::mutex> lock(notification->mutex);
666 
667         notification->condition.wait_for(
668                 lock,
669                 std::chrono::milliseconds(2),
670                 [&notification]() {
671                    return notification->getRegistrations().size() >= 2;
672                 });
673 
674         std::vector<std::string> registrations = notification->getRegistrations();
675         std::sort(registrations.begin(), registrations.end());
676 
677         EXPECT_EQ(registrations.size(), 2u);
678 
679         std::string descriptor = ISimple::descriptor;
680 
681         EXPECT_EQ(to_string(registrations.data(), registrations.size()),
682                   "['" + descriptor + "/" + instanceOne + "', '"
683                        + descriptor + "/" + instanceTwo + "']");
684     }
685 }
686 
TEST_F(HidlTest,TestToken)687 TEST_F(HidlTest, TestToken) {
688     Return<void> ret = tokenManager->createToken(manager, [&] (const hidl_vec<uint8_t> &token) {
689         Return<sp<IBase>> retService = tokenManager->get(token);
690         EXPECT_OK(retService);
691         if (retService.isOk()) {
692             sp<IBase> service = retService;
693             EXPECT_NE(nullptr, service.get());
694             sp<IServiceManager> retManager = IServiceManager::castFrom(service);
695 
696             // TODO(b/33818800): should have only one Bp per process
697             // EXPECT_EQ(manager, retManager);
698 
699             EXPECT_NE(nullptr, retManager.get());
700         }
701 
702         Return<bool> unregisterRet = tokenManager->unregister(token);
703 
704         EXPECT_OK(unregisterRet);
705         if (unregisterRet.isOk()) {
706             EXPECT_TRUE(unregisterRet);
707         }
708     });
709     EXPECT_OK(ret);
710 }
711 
TEST_F(HidlTest,TestSharedMemory)712 TEST_F(HidlTest, TestSharedMemory) {
713     const uint8_t kValue = 0xCA;
714     hidl_memory mem_copy;
715     EXPECT_OK(ashmemAllocator->allocate(1024, [&](bool success, const hidl_memory& mem) {
716         EXPECT_EQ(success, true);
717 
718         sp<IMemory> memory = mapMemory(mem);
719 
720         EXPECT_NE(memory, nullptr);
721 
722         uint8_t* data = static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
723         EXPECT_NE(data, nullptr);
724 
725         EXPECT_EQ(memory->getSize(), mem.size());
726 
727         memory->update();
728         memset(data, 0, memory->getSize());
729         memory->commit();
730 
731         mem_copy = mem;
732         memoryTest->fillMemory(mem, kValue);
733 
734         memory->read();
735         for (size_t i = 0; i < mem.size(); i++) {
736             EXPECT_EQ(kValue, data[i]);
737         }
738         memory->commit();
739     }));
740 
741     // Test the memory persists after the call
742     sp<IMemory> memory = mapMemory(mem_copy);
743 
744     EXPECT_NE(memory, nullptr);
745 
746     uint8_t* data = static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
747     EXPECT_NE(data, nullptr);
748 
749     memory->read();
750     for (size_t i = 0; i < mem_copy.size(); i++) {
751         EXPECT_EQ(kValue, data[i]);
752     }
753     memory->commit();
754 
755     hidl_memory mem_move(std::move(mem_copy));
756     ASSERT_EQ(nullptr, mem_copy.handle());
757     ASSERT_EQ(0UL, mem_copy.size());
758     ASSERT_EQ("", mem_copy.name());
759 
760     memory.clear();
761     memory = mapMemory(mem_move);
762 
763     EXPECT_NE(memory, nullptr);
764 
765     data = static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
766     EXPECT_NE(data, nullptr);
767 
768     memory->read();
769     for (size_t i = 0; i < mem_move.size(); i++) {
770         EXPECT_EQ(kValue, data[i]);
771     }
772     memory->commit();
773 }
774 
TEST_F(HidlTest,BatchSharedMemory)775 TEST_F(HidlTest, BatchSharedMemory) {
776     const uint8_t kValue = 0xCA;
777     const uint64_t kBatchSize = 2;
778     hidl_vec<hidl_memory> batchCopy;
779 
780     EXPECT_OK(ashmemAllocator->batchAllocate(1024, kBatchSize,
781         [&](bool success, const hidl_vec<hidl_memory>& batch) {
782             ASSERT_TRUE(success);
783             EXPECT_EQ(kBatchSize, batch.size());
784 
785             for (uint64_t i = 0; i < batch.size(); i++) {
786                 sp<IMemory> memory = mapMemory(batch[i]);
787 
788                 EXPECT_NE(nullptr, memory.get());
789 
790                 uint8_t* data = static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
791                 EXPECT_NE(nullptr, data);
792 
793                 EXPECT_EQ(memory->getSize(), batch[i].size());
794 
795                 memory->update();
796                 memset(data, kValue, memory->getSize());
797                 memory->commit();
798             }
799 
800             batchCopy = batch;
801         }));
802 
803     for (uint64_t i = 0; i < batchCopy.size(); i++) {
804         // Test the memory persists after the call
805         sp<IMemory> memory = mapMemory(batchCopy[i]);
806 
807         EXPECT_NE(memory, nullptr);
808 
809         uint8_t* data = static_cast<uint8_t*>(static_cast<void*>(memory->getPointer()));
810         EXPECT_NE(data, nullptr);
811 
812         memory->read();
813         for (size_t i = 0; i < batchCopy[i].size(); i++) {
814             EXPECT_EQ(kValue, data[i]);
815         }
816         memory->commit();
817     }
818 }
819 
operator ""_GB(unsigned long long num)820 inline uint64_t operator""_GB(unsigned long long num) {
821     return num * 1024 * 1024 * 1024;
822 }
823 
TEST_F(HidlTest,FailedBatchSharedMemory)824 TEST_F(HidlTest, FailedBatchSharedMemory) {
825     EXPECT_OK(ashmemAllocator->batchAllocate(1024, UINT64_MAX, [&](bool success, const auto& v) {
826         EXPECT_FALSE(success);
827         EXPECT_EQ(0u, v.size());
828     }));
829     EXPECT_OK(ashmemAllocator->batchAllocate(1_GB, 1024, [&](bool success, const auto& v) {
830         EXPECT_FALSE(success);
831         EXPECT_EQ(0u, v.size());
832     }));
833 }
834 
TEST_F(HidlTest,NullSharedMemory)835 TEST_F(HidlTest, NullSharedMemory) {
836     hidl_memory memory{};
837 
838     EXPECT_EQ(nullptr, memory.handle());
839 
840     EXPECT_OK(memoryTest->haveSomeMemory(memory, [&](const hidl_memory &mem) {
841         EXPECT_EQ(nullptr, mem.handle());
842     }));
843 }
844 
TEST_F(HidlTest,FooGetDescriptorTest)845 TEST_F(HidlTest, FooGetDescriptorTest) {
846     EXPECT_OK(foo->interfaceDescriptor([&] (const auto &desc) {
847         EXPECT_EQ(desc, mode == BINDERIZED
848                 ? IBar::descriptor // service is actually IBar in binderized mode
849                 : IFoo::descriptor); // dlopened, so service is IFoo
850     }));
851 }
852 
TEST_F(HidlTest,FooDoThisTest)853 TEST_F(HidlTest, FooDoThisTest) {
854     ALOGI("CLIENT call doThis.");
855     EXPECT_OK(foo->doThis(1.0f));
856     ALOGI("CLIENT doThis returned.");
857 }
858 
TEST_F(HidlTest,FooDoThatAndReturnSomethingTest)859 TEST_F(HidlTest, FooDoThatAndReturnSomethingTest) {
860     ALOGI("CLIENT call doThatAndReturnSomething.");
861     int32_t result = foo->doThatAndReturnSomething(2.0f);
862     ALOGI("CLIENT doThatAndReturnSomething returned %d.", result);
863     EXPECT_EQ(result, 666);
864 }
865 
TEST_F(HidlTest,FooDoQuiteABitTest)866 TEST_F(HidlTest, FooDoQuiteABitTest) {
867     ALOGI("CLIENT call doQuiteABit");
868     double something = foo->doQuiteABit(1, 2, 3.0f, 4.0);
869     ALOGI("CLIENT doQuiteABit returned %f.", something);
870     EXPECT_DOUBLE_EQ(something, 666.5);
871 }
872 
TEST_F(HidlTest,FooDoSomethingElseTest)873 TEST_F(HidlTest, FooDoSomethingElseTest) {
874 
875     ALOGI("CLIENT call doSomethingElse");
876     hidl_array<int32_t, 15> param;
877     for (size_t i = 0; i < sizeof(param) / sizeof(param[0]); ++i) {
878         param[i] = i;
879     }
880     EXPECT_OK(foo->doSomethingElse(param, [&](const auto &something) {
881             ALOGI("CLIENT doSomethingElse returned %s.",
882                   to_string(something).c_str());
883             int32_t expect[] = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24,
884                 26, 28, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1, 2};
885             EXPECT_TRUE(isArrayEqual(something, expect, 32));
886         }));
887 }
888 
TEST_F(HidlTest,FooDoStuffAndReturnAStringTest)889 TEST_F(HidlTest, FooDoStuffAndReturnAStringTest) {
890     ALOGI("CLIENT call doStuffAndReturnAString");
891     EXPECT_OK(foo->doStuffAndReturnAString([&](const auto &something) {
892             ALOGI("CLIENT doStuffAndReturnAString returned '%s'.",
893                   something.c_str());
894             EXPECT_STREQ(something.c_str(), "Hello, world");
895             EXPECT_EQ(strlen("Hello, world"), something.size());
896         }));
897 }
898 
TEST_F(HidlTest,FooMapThisVectorTest)899 TEST_F(HidlTest, FooMapThisVectorTest) {
900     hidl_vec<int32_t> vecParam;
901     vecParam.resize(10);
902     for (size_t i = 0; i < 10; ++i) {
903         vecParam[i] = i;
904     }
905     EXPECT_OK(foo->mapThisVector(vecParam, [&](const auto &something) {
906             ALOGI("CLIENT mapThisVector returned %s.",
907                   to_string(something).c_str());
908             int32_t expect[] = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18};
909             EXPECT_TRUE(isArrayEqual(something, expect, something.size()));
910         }));
911 }
912 
TEST_F(HidlTest,WrapTest)913 TEST_F(HidlTest, WrapTest) {
914     if (!gHidlEnvironment->enableDelayMeasurementTests) {
915         return;
916     }
917 
918     using ::android::hardware::tests::foo::V1_0::BnHwSimple;
919     using ::android::hardware::tests::foo::V1_0::BsSimple;
920     using ::android::hardware::tests::foo::V1_0::BpHwSimple;
921     using ::android::hardware::details::HidlInstrumentor;
922     nsecs_t now;
923     int i = 0;
924 
925     now = systemTime();
926     new BnHwSimple(new Simple(1));
927     EXPECT_LT(systemTime() - now, 2000000) << "    for BnHwSimple(nonnull)";
928 
929     now = systemTime();
930     new BnHwSimple(nullptr);
931     EXPECT_LT(systemTime() - now, 2000000) << "    for BnHwSimple(null)";
932 
933     now = systemTime();
934     new BsSimple(new Simple(1));
935     EXPECT_LT(systemTime() - now, 2000000) << "    for BsSimple(nonnull)";
936 
937     now = systemTime();
938     new BsSimple(nullptr);
939     EXPECT_LT(systemTime() - now, 2000000) << "    for BsSimple(null)";
940 
941     now = systemTime();
942     new BpHwSimple(nullptr);
943     EXPECT_LT(systemTime() - now, 2000000) << "    for BpHwSimple(null)";
944 
945     now = systemTime();
946     new ::android::hardware::details::HidlInstrumentor("", "");
947     EXPECT_LT(systemTime() - now, 2000000) << "    for HidlInstrumentor";
948 
949     now = systemTime();
950     i++;
951     EXPECT_LT(systemTime() - now,    1000) << "    for nothing";
952 }
953 
TEST_F(HidlTest,FooCallMeTest)954 TEST_F(HidlTest, FooCallMeTest) {
955     if (!gHidlEnvironment->enableDelayMeasurementTests) {
956         return;
957     }
958     sp<IFooCallback> fooCb = new FooCallback();
959     ALOGI("CLIENT call callMe.");
960     // callMe is oneway, should return instantly.
961     nsecs_t now;
962     now = systemTime();
963     EXPECT_OK(foo->callMe(fooCb));
964     EXPECT_LT(systemTime() - now, ONEWAY_TOLERANCE_NS);
965     ALOGI("CLIENT callMe returned.");
966 
967     // Bar::callMe will invoke three methods on FooCallback; one will return
968     // right away (even though it is a two-way method); the second one will
969     // block Bar for DELAY_S seconds, and the third one will return
970     // to Bar right away (is oneway) but will itself block for DELAY_S seconds.
971     // We need a way to make sure that these three things have happened within
972     // 2*DELAY_S seconds plus some small tolerance.
973     //
974     // Method FooCallback::reportResults() takes a timeout parameter.  It blocks for
975     // that length of time, while waiting for the three methods above to
976     // complete.  It returns the information of whether each method was invoked,
977     // as well as how long the body of the method took to execute.  We verify
978     // the information returned by reportResults() against the timeout we pass (which
979     // is long enough for the method bodies to execute, plus tolerance), and
980     // verify that eachof them executed, as expected, and took the length of
981     // time to execute that we also expect.
982 
983     const nsecs_t waitNs =
984         3 * DELAY_NS + TOLERANCE_NS;
985     const nsecs_t reportResultsNs =
986         2 * DELAY_NS + TOLERANCE_NS;
987 
988     ALOGI("CLIENT: Waiting for up to %" PRId64 " seconds.",
989           nanoseconds_to_seconds(waitNs));
990 
991     fooCb->reportResults(waitNs,
992                 [&](int64_t timeLeftNs,
993                     const hidl_array<IFooCallback::InvokeInfo, 3> &invokeResults) {
994         ALOGI("CLIENT: FooCallback::reportResults() is returning data.");
995         ALOGI("CLIENT: Waited for %" PRId64 " milliseconds.",
996               nanoseconds_to_milliseconds(waitNs - timeLeftNs));
997 
998         EXPECT_LE(waitNs - timeLeftNs, reportResultsNs)
999                 << "waited for "
1000                 << (timeLeftNs >= 0 ? "" : "more than ")
1001                 << (timeLeftNs >= 0 ? (waitNs - timeLeftNs) : waitNs)
1002                 << "ns, expect to finish in "
1003                 << reportResultsNs << " ns";
1004 
1005         // two-way method, was supposed to return right away
1006         EXPECT_TRUE(invokeResults[0].invoked);
1007         EXPECT_LE(invokeResults[0].timeNs, invokeResults[0].callerBlockedNs);
1008         EXPECT_LE(invokeResults[0].callerBlockedNs, TOLERANCE_NS);
1009         // two-way method, was supposed to block caller for DELAY_NS
1010         EXPECT_TRUE(invokeResults[1].invoked);
1011         EXPECT_LE(invokeResults[1].timeNs, invokeResults[1].callerBlockedNs);
1012         EXPECT_LE(invokeResults[1].callerBlockedNs,
1013                     DELAY_NS + TOLERANCE_NS);
1014         // one-way method, do not block caller, but body was supposed to block for DELAY_NS
1015         EXPECT_TRUE(invokeResults[2].invoked);
1016         EXPECT_LE(invokeResults[2].callerBlockedNs, ONEWAY_TOLERANCE_NS);
1017         EXPECT_LE(invokeResults[2].timeNs, DELAY_NS + TOLERANCE_NS);
1018     });
1019 }
1020 
1021 
1022 
TEST_F(HidlTest,FooUseAnEnumTest)1023 TEST_F(HidlTest, FooUseAnEnumTest) {
1024     ALOGI("CLIENT call useAnEnum.");
1025     IFoo::SomeEnum sleepy = foo->useAnEnum(IFoo::SomeEnum::quux);
1026     ALOGI("CLIENT useAnEnum returned %u", (unsigned)sleepy);
1027     EXPECT_EQ(sleepy, IFoo::SomeEnum::goober);
1028 }
1029 
TEST_F(HidlTest,FooHaveAGooberTest)1030 TEST_F(HidlTest, FooHaveAGooberTest) {
1031     hidl_vec<IFoo::Goober> gooberVecParam;
1032     gooberVecParam.resize(2);
1033     gooberVecParam[0].name = "Hello";
1034     gooberVecParam[1].name = "World";
1035 
1036     ALOGI("CLIENT call haveAGooberVec.");
1037     EXPECT_OK(foo->haveAGooberVec(gooberVecParam));
1038     ALOGI("CLIENT haveAGooberVec returned.");
1039 
1040     ALOGI("CLIENT call haveaGoober.");
1041     EXPECT_OK(foo->haveAGoober(gooberVecParam[0]));
1042     ALOGI("CLIENT haveaGoober returned.");
1043 
1044     ALOGI("CLIENT call haveAGooberArray.");
1045     hidl_array<IFoo::Goober, 20> gooberArrayParam;
1046     EXPECT_OK(foo->haveAGooberArray(gooberArrayParam));
1047     ALOGI("CLIENT haveAGooberArray returned.");
1048 }
1049 
TEST_F(HidlTest,FooHaveATypeFromAnotherFileTest)1050 TEST_F(HidlTest, FooHaveATypeFromAnotherFileTest) {
1051     ALOGI("CLIENT call haveATypeFromAnotherFile.");
1052     Abc abcParam{};
1053     abcParam.x = "alphabet";
1054     abcParam.y = 3.14f;
1055     native_handle_t *handle = native_handle_create(0, 0);
1056     abcParam.z = handle;
1057     EXPECT_OK(foo->haveATypeFromAnotherFile(abcParam));
1058     ALOGI("CLIENT haveATypeFromAnotherFile returned.");
1059     native_handle_delete(handle);
1060     abcParam.z = NULL;
1061 }
1062 
TEST_F(HidlTest,FooHaveSomeStringsTest)1063 TEST_F(HidlTest, FooHaveSomeStringsTest) {
1064     ALOGI("CLIENT call haveSomeStrings.");
1065     hidl_array<hidl_string, 3> stringArrayParam;
1066     stringArrayParam[0] = "What";
1067     stringArrayParam[1] = "a";
1068     stringArrayParam[2] = "disaster";
1069     EXPECT_OK(foo->haveSomeStrings(
1070                 stringArrayParam,
1071                 [&](const auto &out) {
1072                     ALOGI("CLIENT haveSomeStrings returned %s.",
1073                           to_string(out).c_str());
1074 
1075                     EXPECT_EQ(to_string(out), "['Hello', 'World']");
1076                 }));
1077     ALOGI("CLIENT haveSomeStrings returned.");
1078 }
1079 
TEST_F(HidlTest,FooHaveAStringVecTest)1080 TEST_F(HidlTest, FooHaveAStringVecTest) {
1081     ALOGI("CLIENT call haveAStringVec.");
1082     hidl_vec<hidl_string> stringVecParam;
1083     stringVecParam.resize(3);
1084     stringVecParam[0] = "What";
1085     stringVecParam[1] = "a";
1086     stringVecParam[2] = "disaster";
1087     EXPECT_OK(foo->haveAStringVec(
1088                 stringVecParam,
1089                 [&](const auto &out) {
1090                     ALOGI("CLIENT haveAStringVec returned %s.",
1091                           to_string(out).c_str());
1092 
1093                     EXPECT_EQ(to_string(out), "['Hello', 'World']");
1094                 }));
1095     ALOGI("CLIENT haveAStringVec returned.");
1096 }
1097 
TEST_F(HidlTest,FooTransposeMeTest)1098 TEST_F(HidlTest, FooTransposeMeTest) {
1099     hidl_array<float, 3, 5> in;
1100     float k = 1.0f;
1101     for (size_t i = 0; i < 3; ++i) {
1102         for (size_t j = 0; j < 5; ++j, ++k) {
1103             in[i][j] = k;
1104         }
1105     }
1106 
1107     ALOGI("CLIENT call transposeMe(%s).", to_string(in).c_str());
1108 
1109     EXPECT_OK(foo->transposeMe(
1110                 in,
1111                 [&](const auto &out) {
1112                     ALOGI("CLIENT transposeMe returned %s.",
1113                           to_string(out).c_str());
1114 
1115                     for (size_t i = 0; i < 3; ++i) {
1116                         for (size_t j = 0; j < 5; ++j) {
1117                             EXPECT_EQ(out[j][i], in[i][j]);
1118                         }
1119                     }
1120                 }));
1121 }
1122 
TEST_F(HidlTest,FooCallingDrWhoTest)1123 TEST_F(HidlTest, FooCallingDrWhoTest) {
1124     IFoo::MultiDimensional in;
1125 
1126     size_t k = 0;
1127     for (size_t i = 0; i < 5; ++i) {
1128         for (size_t j = 0; j < 3; ++j, ++k) {
1129             in.quuxMatrix[i][j].first = ("First " + std::to_string(k)).c_str();
1130             in.quuxMatrix[i][j].last = ("Last " + std::to_string(15-k)).c_str();
1131         }
1132     }
1133 
1134     ALOGI("CLIENT call callingDrWho(%s).",
1135           MultiDimensionalToString(in).c_str());
1136 
1137     EXPECT_OK(foo->callingDrWho(
1138                 in,
1139                 [&](const auto &out) {
1140                     ALOGI("CLIENT callingDrWho returned %s.",
1141                           MultiDimensionalToString(out).c_str());
1142 
1143                     size_t k = 0;
1144                     for (size_t i = 0; i < 5; ++i) {
1145                         for (size_t j = 0; j < 3; ++j, ++k) {
1146                             EXPECT_STREQ(
1147                                 out.quuxMatrix[i][j].first.c_str(),
1148                                 in.quuxMatrix[4 - i][2 - j].last.c_str());
1149 
1150                             EXPECT_STREQ(
1151                                 out.quuxMatrix[i][j].last.c_str(),
1152                                 in.quuxMatrix[4 - i][2 - j].first.c_str());
1153                         }
1154                     }
1155                 }));
1156 }
1157 
numberToEnglish(int x)1158 static std::string numberToEnglish(int x) {
1159     static const char *const kDigits[] = {
1160         "zero",
1161         "one",
1162         "two",
1163         "three",
1164         "four",
1165         "five",
1166         "six",
1167         "seven",
1168         "eight",
1169         "nine",
1170     };
1171 
1172     if (x < 0) {
1173         return "negative " + numberToEnglish(-x);
1174     }
1175 
1176     if (x < 10) {
1177         return kDigits[x];
1178     }
1179 
1180     if (x <= 15) {
1181         static const char *const kSpecialTens[] = {
1182             "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
1183         };
1184 
1185         return kSpecialTens[x - 10];
1186     }
1187 
1188     if (x < 20) {
1189         return std::string(kDigits[x % 10]) + "teen";
1190     }
1191 
1192     if (x < 100) {
1193         static const char *const kDecades[] = {
1194             "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
1195             "eighty", "ninety",
1196         };
1197 
1198         return std::string(kDecades[x / 10 - 2]) + kDigits[x % 10];
1199     }
1200 
1201     return "positively huge!";
1202 }
1203 
TEST_F(HidlTest,FooTransposeTest)1204 TEST_F(HidlTest, FooTransposeTest) {
1205     IFoo::StringMatrix5x3 in;
1206 
1207     for (int i = 0; i < 5; ++i) {
1208         for (int j = 0; j < 3; ++j) {
1209             in.s[i][j] = numberToEnglish(3 * i + j + 1).c_str();
1210         }
1211     }
1212 
1213     EXPECT_OK(foo->transpose(
1214                 in,
1215                 [&](const auto &out) {
1216                     EXPECT_EQ(
1217                         to_string(out),
1218                         "[['one', 'four', 'seven', 'ten', 'thirteen'], "
1219                          "['two', 'five', 'eight', 'eleven', 'fourteen'], "
1220                          "['three', 'six', 'nine', 'twelve', 'fifteen']]");
1221                 }));
1222 }
1223 
TEST_F(HidlTest,FooTranspose2Test)1224 TEST_F(HidlTest, FooTranspose2Test) {
1225     hidl_array<hidl_string, 5, 3> in;
1226 
1227     for (int i = 0; i < 5; ++i) {
1228         for (int j = 0; j < 3; ++j) {
1229             in[i][j] = numberToEnglish(3 * i + j + 1).c_str();
1230         }
1231     }
1232 
1233     EXPECT_OK(foo->transpose2(
1234                 in,
1235                 [&](const auto &out) {
1236                     EXPECT_EQ(
1237                         to_string(out),
1238                         "[['one', 'four', 'seven', 'ten', 'thirteen'], "
1239                          "['two', 'five', 'eight', 'eleven', 'fourteen'], "
1240                          "['three', 'six', 'nine', 'twelve', 'fifteen']]");
1241                 }));
1242 }
1243 
TEST_F(HidlTest,FooNullNativeHandleTest)1244 TEST_F(HidlTest, FooNullNativeHandleTest) {
1245     Abc xyz;
1246     xyz.z = nullptr;
1247     EXPECT_OK(bar->expectNullHandle(nullptr, xyz, [](bool hIsNull, bool xyzHasNull) {
1248         EXPECT_TRUE(hIsNull);
1249         EXPECT_TRUE(xyzHasNull);
1250     }));
1251 }
1252 
TEST_F(HidlTest,FooNullCallbackTest)1253 TEST_F(HidlTest, FooNullCallbackTest) {
1254     EXPECT_OK(foo->echoNullInterface(nullptr,
1255                 [](const auto receivedNull, const auto &intf) {
1256                    EXPECT_TRUE(receivedNull);
1257                    EXPECT_EQ(intf, nullptr);
1258                 }));
1259 }
1260 
TEST_F(HidlTest,FooNonNullCallbackTest)1261 TEST_F(HidlTest, FooNonNullCallbackTest) {
1262     hidl_array<hidl_string, 5, 3> in;
1263 
1264     EXPECT_FAIL(foo->transpose2(in, nullptr /* _hidl_cb */));
1265 }
1266 
TEST_F(HidlTest,FooSendVecTest)1267 TEST_F(HidlTest, FooSendVecTest) {
1268     hidl_vec<uint8_t> in;
1269     in.resize(16);
1270     for (size_t i = 0; i < in.size(); ++i) {
1271         in[i] = i;
1272     }
1273 
1274     EXPECT_OK(foo->sendVec(
1275                 in,
1276                 [&](const auto &out) {
1277                     EXPECT_EQ(to_string(in), to_string(out));
1278                 }));
1279 }
1280 
TEST_F(HidlTest,FooSendEmptyVecTest)1281 TEST_F(HidlTest, FooSendEmptyVecTest) {
1282     hidl_vec<uint8_t> in;
1283     EXPECT_OK(foo->sendVec(
1284                 in,
1285                 [&](const auto &out) {
1286                     EXPECT_EQ(out.size(), 0u);
1287                     EXPECT_EQ(to_string(in), to_string(out));
1288                 }));
1289 }
1290 
TEST_F(HidlTest,FooHaveAVectorOfInterfacesTest)1291 TEST_F(HidlTest, FooHaveAVectorOfInterfacesTest) {
1292     hidl_vec<sp<ISimple> > in;
1293     in.resize(16);
1294     for (size_t i = 0; i < in.size(); ++i) {
1295         in[i] = new Simple(i);
1296     }
1297 
1298     EXPECT_OK(foo->haveAVectorOfInterfaces(
1299                 in,
1300                 [&](const auto &out) {
1301                     EXPECT_EQ(in.size(), out.size());
1302                     for (size_t i = 0; i < in.size(); ++i) {
1303                         int32_t inCookie = in[i]->getCookie();
1304                         int32_t outCookie = out[i]->getCookie();
1305                         EXPECT_EQ(inCookie, outCookie);
1306                     }
1307                 }));
1308 }
1309 
TEST_F(HidlTest,FooHaveAVectorOfGenericInterfacesTest)1310 TEST_F(HidlTest, FooHaveAVectorOfGenericInterfacesTest) {
1311 
1312     hidl_vec<sp<::android::hidl::base::V1_0::IBase> > in;
1313     in.resize(16);
1314     for (size_t i = 0; i < in.size(); ++i) {
1315         sp<ISimple> s = new Simple(i);
1316         in[i] = s;
1317     }
1318 
1319     EXPECT_OK(foo->haveAVectorOfGenericInterfaces(
1320                 in,
1321                 [&](const auto &out) {
1322                     EXPECT_EQ(in.size(), out.size());
1323 
1324                     EXPECT_OK(out[0]->interfaceDescriptor([](const auto &name) {
1325                         ASSERT_STREQ(name.c_str(), ISimple::descriptor);
1326                     }));
1327                     for (size_t i = 0; i < in.size(); ++i) {
1328                         sp<ISimple> inSimple = ISimple::castFrom(in[i]);
1329                         sp<ISimple> outSimple = ISimple::castFrom(out[i]);
1330 
1331                         ASSERT_NE(inSimple.get(), nullptr);
1332                         ASSERT_NE(outSimple.get(), nullptr);
1333                         EXPECT_EQ(in[i], inSimple.get()); // pointers must be equal!
1334                         int32_t inCookie = inSimple->getCookie();
1335                         int32_t outCookie = outSimple->getCookie();
1336                         EXPECT_EQ(inCookie, outCookie);
1337                     }
1338                 }));
1339 }
1340 
TEST_F(HidlTest,FooStructEmbeddedHandleTest)1341 TEST_F(HidlTest, FooStructEmbeddedHandleTest) {
1342     EXPECT_OK(foo->createMyHandle([&](const auto &myHandle) {
1343         EXPECT_EQ(myHandle.guard, 666);
1344         const native_handle_t* handle = myHandle.h.getNativeHandle();
1345         EXPECT_EQ(handle->numInts, 10);
1346         EXPECT_EQ(handle->numFds, 0);
1347         int data[] = {2,3,5,7,11,13,17,19,21,23};
1348         EXPECT_ARRAYEQ(handle->data, data, 10);
1349     }));
1350 
1351     EXPECT_OK(foo->closeHandles());
1352 }
1353 
TEST_F(HidlTest,FooHandleVecTest)1354 TEST_F(HidlTest, FooHandleVecTest) {
1355     EXPECT_OK(foo->createHandles(3, [&](const auto &handles) {
1356         EXPECT_EQ(handles.size(), 3ull);
1357         int data[] = {2,3,5,7,11,13,17,19,21,23};
1358         for (size_t i = 0; i < 3; i++) {
1359             const native_handle_t *h = handles[i];
1360             EXPECT_EQ(h->numInts, 10) << " for element " << i;
1361             EXPECT_EQ(h->numFds, 0) << " for element " << i;
1362             EXPECT_ARRAYEQ(h->data, data, 10);
1363         }
1364     }));
1365 
1366     EXPECT_OK(foo->closeHandles());
1367 }
1368 
1369 struct HidlDeathRecipient : hidl_death_recipient {
1370     std::mutex mutex;
1371     std::condition_variable condition;
1372     wp<IBase> who;
1373     bool fired = false;
1374     uint64_t cookie = 0;
1375 
serviceDiedHidlDeathRecipient1376     virtual void serviceDied(uint64_t cookie, const wp<IBase>& who) {
1377         std::unique_lock<std::mutex> lock(mutex);
1378         fired = true;
1379         this->cookie = cookie;
1380         this->who = who;
1381         condition.notify_one();
1382     };
1383 };
1384 
TEST_F(HidlTest,DeathRecipientTest)1385 TEST_F(HidlTest, DeathRecipientTest) {
1386     sp<HidlDeathRecipient> recipient = new HidlDeathRecipient();
1387     sp<HidlDeathRecipient> recipient2 = new HidlDeathRecipient();
1388 
1389     EXPECT_TRUE(dyingBaz->linkToDeath(recipient, 0x1481));
1390     EXPECT_TRUE(dyingBaz->linkToDeath(recipient2, 0x2592));
1391     EXPECT_TRUE(dyingBaz->unlinkToDeath(recipient2));
1392 
1393     if (mode != BINDERIZED) {
1394         // Passthrough doesn't fire, nor does it keep state of
1395         // registered death recipients (so it won't fail unlinking
1396         // the same recipient twice).
1397         return;
1398     }
1399 
1400     EXPECT_FALSE(dyingBaz->unlinkToDeath(recipient2));
1401     auto ret = dyingBaz->dieNow();
1402     if (!ret.isOk()) {
1403         //do nothing, this is expected
1404     }
1405 
1406     std::unique_lock<std::mutex> lock(recipient->mutex);
1407     recipient->condition.wait_for(lock, std::chrono::milliseconds(1000), [&recipient]() {
1408             return recipient->fired;
1409     });
1410     EXPECT_TRUE(recipient->fired);
1411     EXPECT_EQ(recipient->cookie, 0x1481u);
1412     EXPECT_EQ(recipient->who, dyingBaz);
1413     std::unique_lock<std::mutex> lock2(recipient2->mutex);
1414     recipient2->condition.wait_for(lock2, std::chrono::milliseconds(1000), [&recipient2]() {
1415             return recipient2->fired;
1416     });
1417     EXPECT_FALSE(recipient2->fired);
1418 
1419     // Verify servicemanager dropped its reference too
1420     sp<IBaz> deadBaz = IBaz::getService("dyingBaz", false);
1421     if (deadBaz != nullptr) {
1422         // Got a passthrough
1423         EXPECT_FALSE(deadBaz->isRemote());
1424     }
1425 }
1426 
TEST_F(HidlTest,BarThisIsNewTest)1427 TEST_F(HidlTest, BarThisIsNewTest) {
1428     // Now the tricky part, get access to the derived interface.
1429     ALOGI("CLIENT call thisIsNew.");
1430     EXPECT_OK(bar->thisIsNew());
1431     ALOGI("CLIENT thisIsNew returned.");
1432 }
1433 
expectGoodChild(const sp<IChild> & child)1434 static void expectGoodChild(const sp<IChild> &child) {
1435     ASSERT_NE(child.get(), nullptr);
1436     EXPECT_OK(child->doGrandparent());
1437     EXPECT_OK(child->doParent());
1438     EXPECT_OK(child->doChild());
1439 }
1440 
expectGoodParent(const sp<IParent> & parent)1441 static void expectGoodParent(const sp<IParent> &parent) {
1442     ASSERT_NE(parent.get(), nullptr);
1443     EXPECT_OK(parent->doGrandparent());
1444     EXPECT_OK(parent->doParent());
1445     sp<IChild> child = IChild::castFrom(parent);
1446     expectGoodChild(child);
1447 }
1448 
expectGoodGrandparent(const sp<IGrandparent> & grandparent)1449 static void expectGoodGrandparent(const sp<IGrandparent> &grandparent) {
1450     ASSERT_NE(grandparent.get(), nullptr);
1451     EXPECT_OK(grandparent->doGrandparent());
1452     sp<IParent> parent = IParent::castFrom(grandparent);
1453     expectGoodParent(parent);
1454 }
1455 
TEST_F(HidlTest,FooHaveAnInterfaceTest)1456 TEST_F(HidlTest, FooHaveAnInterfaceTest) {
1457 
1458     sp<ISimple> in = new Complicated(42);
1459     Return<sp<ISimple>> ret = bar->haveAInterface(in);
1460     EXPECT_OK(ret);
1461     sp<ISimple> out = ret;
1462     ASSERT_NE(out.get(), nullptr);
1463     EXPECT_EQ(out->getCookie(), 42);
1464     EXPECT_OK(out->customVecInt([](const auto &) { }));
1465     EXPECT_OK(out->customVecStr([](const auto &) { }));
1466     EXPECT_OK(out->ping());
1467     EXPECT_OK(out->mystr([](const auto &) { }));
1468     EXPECT_OK(out->myhandle([](const auto &) { }));
1469 }
1470 
TEST_F(HidlTest,InheritRemoteGrandparentTest)1471 TEST_F(HidlTest, InheritRemoteGrandparentTest) {
1472     Return<sp<IGrandparent>> ret = fetcher->getGrandparent(true);
1473     EXPECT_OK(ret);
1474     expectGoodGrandparent(ret);
1475 }
1476 
TEST_F(HidlTest,InheritLocalGrandparentTest)1477 TEST_F(HidlTest, InheritLocalGrandparentTest) {
1478     Return<sp<IGrandparent>> ret = fetcher->getGrandparent(false);
1479     EXPECT_OK(ret);
1480     expectGoodGrandparent(ret);
1481 }
1482 
TEST_F(HidlTest,InheritRemoteParentTest)1483 TEST_F(HidlTest, InheritRemoteParentTest) {
1484     Return<sp<IParent>> ret = fetcher->getParent(true);
1485     EXPECT_OK(ret);
1486     expectGoodParent(ret);
1487 }
1488 
TEST_F(HidlTest,InheritLocalParentTest)1489 TEST_F(HidlTest, InheritLocalParentTest) {
1490     Return<sp<IParent>> ret = fetcher->getParent(false);
1491     EXPECT_OK(ret);
1492     expectGoodParent(ret);
1493 }
1494 
TEST_F(HidlTest,InheritRemoteChildTest)1495 TEST_F(HidlTest, InheritRemoteChildTest) {
1496     Return<sp<IChild>> ret = fetcher->getChild(true);
1497     EXPECT_OK(ret);
1498     expectGoodChild(ret);
1499 }
1500 
TEST_F(HidlTest,InheritLocalChildTest)1501 TEST_F(HidlTest, InheritLocalChildTest) {
1502     Return<sp<IChild>> ret = fetcher->getChild(false);
1503     EXPECT_OK(ret);
1504     expectGoodChild(ret);
1505 }
1506 
TEST_F(HidlTest,TestArrayDimensionality)1507 TEST_F(HidlTest, TestArrayDimensionality) {
1508     hidl_array<int, 2> oneDim;
1509     hidl_array<int, 2, 3> twoDim;
1510     hidl_array<int, 2, 3, 4> threeDim;
1511 
1512     EXPECT_EQ(oneDim.size(), 2u);
1513     EXPECT_EQ(twoDim.size(), std::make_tuple(2u, 3u));
1514     EXPECT_EQ(threeDim.size(), std::make_tuple(2u, 3u, 4u));
1515 }
1516 
TEST_F(HidlTest,StructEqualTest)1517 TEST_F(HidlTest, StructEqualTest) {
1518     using G = IFoo::Goober;
1519     using F = IFoo::Fumble;
1520     G g1{
1521         .q = 42,
1522         .name = "The Ultimate Question of Life, the Universe, and Everything",
1523         .address = "North Pole",
1524         .numbers = std::array<double, 10>{ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} },
1525         .fumble = F{.data = {.data = 50}},
1526         .gumble = F{.data = {.data = 60}}
1527     };
1528     G g2{
1529         .q = 42,
1530         .name = "The Ultimate Question of Life, the Universe, and Everything",
1531         .address = "North Pole",
1532         .numbers = std::array<double, 10>{ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} },
1533         .fumble = F{.data = {.data = 50}},
1534         .gumble = F{.data = {.data = 60}}
1535     };
1536     G g3{
1537         .q = 42,
1538         .name = "The Ultimate Question of Life, the Universe, and Everything",
1539         .address = "North Pole",
1540         .numbers = std::array<double, 10>{ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} },
1541         .fumble = F{.data = {.data = 50}},
1542         .gumble = F{.data = {.data = 61}}
1543     };
1544     // explicitly invoke operator== here.
1545     EXPECT_TRUE(g1 == g2);
1546     EXPECT_TRUE(g1 != g3);
1547 }
1548 
TEST_F(HidlTest,EnumEqualTest)1549 TEST_F(HidlTest, EnumEqualTest) {
1550     using E = IFoo::SomeEnum;
1551     E e1 = E::quux;
1552     E e2 = E::quux;
1553     E e3 = E::goober;
1554     // explicitly invoke operator== here.
1555     EXPECT_TRUE(e1 == e2);
1556     EXPECT_TRUE(e1 != e3);
1557 }
1558 
TEST_F(HidlTest,InvalidTransactionTest)1559 TEST_F(HidlTest, InvalidTransactionTest) {
1560     using ::android::hardware::tests::bar::V1_0::BnHwBar;
1561     using ::android::hardware::tests::bar::V1_0::BpHwBar;
1562     using ::android::hardware::IBinder;
1563     using ::android::hardware::Parcel;
1564     using ::android::status_t;
1565     using ::android::OK;
1566 
1567     Parcel request, reply;
1568     sp<IBinder> binder;
1569     status_t status = request.writeInterfaceToken(::android::hardware::tests::bar::V1_0::IBar::descriptor);
1570 
1571     EXPECT_EQ(status, OK);
1572 
1573     if (mode == BINDERIZED) {
1574         EXPECT_TRUE(bar->isRemote());
1575         binder = ::android::hardware::toBinder<IBar, BpHwBar>(bar);
1576     } else {
1577         // For a local test, just wrap the implementation with a BnHwBar
1578         binder = new BnHwBar(bar);
1579     }
1580 
1581     status = binder->transact(1234, request, &reply);
1582 
1583     EXPECT_EQ(status, ::android::UNKNOWN_TRANSACTION);
1584     // Try another call, to make sure nothing is messed up
1585     EXPECT_OK(bar->thisIsNew());
1586 }
1587 
1588 #if HIDL_RUN_POINTER_TESTS
1589 
TEST_F(HidlTest,PassAGraphTest)1590 TEST_F(HidlTest, PassAGraphTest) {
1591     IGraph::Graph g;
1592     ::android::simpleGraph(g);
1593     ::android::logSimpleGraph("CLIENT", g);
1594     ALOGI("CLIENT call passAGraph");
1595     EXPECT_OK(graphInterface->passAGraph(g));
1596 }
1597 
TEST_F(HidlTest,GiveAGraphTest)1598 TEST_F(HidlTest, GiveAGraphTest) {
1599     EXPECT_OK(graphInterface->giveAGraph([&](const auto &newGraph) {
1600         ::android::logSimpleGraph("CLIENT", newGraph);
1601         EXPECT_TRUE(::android::isSimpleGraph(newGraph));
1602     }));
1603 }
TEST_F(HidlTest,PassANodeTest)1604 TEST_F(HidlTest, PassANodeTest) {
1605     IGraph::Node node; node.data = 10;
1606     EXPECT_OK(graphInterface->passANode(node));
1607 }
TEST_F(HidlTest,PassTwoGraphsTest)1608 TEST_F(HidlTest, PassTwoGraphsTest) {
1609     IGraph::Graph g;
1610     ::android::simpleGraph(g);
1611     EXPECT_OK(graphInterface->passTwoGraphs(&g, &g));
1612 }
TEST_F(HidlTest,PassAGammaTest)1613 TEST_F(HidlTest, PassAGammaTest) {
1614     IGraph::Theta s; s.data = 500;
1615     IGraph::Alpha a; a.s_ptr = &s;
1616     IGraph::Beta  b; b.s_ptr = &s;
1617     IGraph::Gamma c; c.a_ptr = &a; c.b_ptr = &b;
1618     ALOGI("CLIENT calling passAGamma: c.a = %p, c.b = %p, c.a->s = %p, c.b->s = %p",
1619         c.a_ptr, c.b_ptr, c.a_ptr->s_ptr, c.b_ptr->s_ptr);
1620     EXPECT_OK(graphInterface->passAGamma(c));
1621 }
TEST_F(HidlTest,PassNullTest)1622 TEST_F(HidlTest, PassNullTest) {
1623     IGraph::Gamma c;
1624     c.a_ptr = nullptr;
1625     c.b_ptr = nullptr;
1626     EXPECT_OK(graphInterface->passAGamma(c));
1627 }
TEST_F(HidlTest,PassASimpleRefTest)1628 TEST_F(HidlTest, PassASimpleRefTest) {
1629     IGraph::Theta s;
1630     s.data = 500;
1631     IGraph::Alpha a;
1632     a.s_ptr = &s;
1633     EXPECT_OK(graphInterface->passASimpleRef(&a));
1634 }
TEST_F(HidlTest,PassASimpleRefSTest)1635 TEST_F(HidlTest, PassASimpleRefSTest) {
1636     IGraph::Theta s;
1637     s.data = 500;
1638     ALOGI("CLIENT call passASimpleRefS with %p", &s);
1639     EXPECT_OK(graphInterface->passASimpleRefS(&s));
1640 }
TEST_F(HidlTest,GiveASimpleRefTest)1641 TEST_F(HidlTest, GiveASimpleRefTest) {
1642     EXPECT_OK(graphInterface->giveASimpleRef([&](const auto & a_ptr) {
1643         EXPECT_EQ(a_ptr->s_ptr->data, 500);
1644     }));
1645 }
TEST_F(HidlTest,GraphReportErrorsTest)1646 TEST_F(HidlTest, GraphReportErrorsTest) {
1647     Return<int32_t> ret = graphInterface->getErrors();
1648     EXPECT_OK(ret);
1649     EXPECT_EQ(int32_t(ret), 0);
1650 }
1651 
TEST_F(HidlTest,PointerPassOldBufferTest)1652 TEST_F(HidlTest, PointerPassOldBufferTest) {
1653     EXPECT_OK(validationPointerInterface->bar1([&](const auto& sptr, const auto& s) {
1654         EXPECT_OK(pointerInterface->foo1(sptr, s));
1655     }));
1656 }
TEST_F(HidlTest,PointerPassOldBufferTest2)1657 TEST_F(HidlTest, PointerPassOldBufferTest2) {
1658     EXPECT_OK(validationPointerInterface->bar2([&](const auto& s, const auto& a) {
1659         EXPECT_OK(pointerInterface->foo2(s, a));
1660     }));
1661 }
TEST_F(HidlTest,PointerPassSameOldBufferPointerTest)1662 TEST_F(HidlTest, PointerPassSameOldBufferPointerTest) {
1663     EXPECT_OK(validationPointerInterface->bar3([&](const auto& s, const auto& a, const auto& b) {
1664         EXPECT_OK(pointerInterface->foo3(s, a, b));
1665     }));
1666 }
TEST_F(HidlTest,PointerPassOnlyTest)1667 TEST_F(HidlTest, PointerPassOnlyTest) {
1668     EXPECT_OK(validationPointerInterface->bar4([&](const auto& s) {
1669         EXPECT_OK(pointerInterface->foo4(s));
1670     }));
1671 }
TEST_F(HidlTest,PointerPassTwoEmbeddedTest)1672 TEST_F(HidlTest, PointerPassTwoEmbeddedTest) {
1673     EXPECT_OK(validationPointerInterface->bar5([&](const auto& a, const auto& b) {
1674         EXPECT_OK(pointerInterface->foo5(a, b));
1675     }));
1676 }
TEST_F(HidlTest,PointerPassIndirectBufferHasDataTest)1677 TEST_F(HidlTest, PointerPassIndirectBufferHasDataTest) {
1678     EXPECT_OK(validationPointerInterface->bar6([&](const auto& a) {
1679         EXPECT_OK(pointerInterface->foo6(a));
1680     }));
1681 }
TEST_F(HidlTest,PointerPassTwoIndirectBufferTest)1682 TEST_F(HidlTest, PointerPassTwoIndirectBufferTest) {
1683     EXPECT_OK(validationPointerInterface->bar7([&](const auto& a, const auto& b) {
1684         EXPECT_OK(pointerInterface->foo7(a, b));
1685     }));
1686 }
TEST_F(HidlTest,PointerPassDeeplyIndirectTest)1687 TEST_F(HidlTest, PointerPassDeeplyIndirectTest) {
1688     EXPECT_OK(validationPointerInterface->bar8([&](const auto& d) {
1689         EXPECT_OK(pointerInterface->foo8(d));
1690     }));
1691 }
TEST_F(HidlTest,PointerPassStringRefTest)1692 TEST_F(HidlTest, PointerPassStringRefTest) {
1693     EXPECT_OK(validationPointerInterface->bar9([&](const auto& str) {
1694         EXPECT_OK(pointerInterface->foo9(str));
1695     }));
1696 }
TEST_F(HidlTest,PointerPassRefVecTest)1697 TEST_F(HidlTest, PointerPassRefVecTest) {
1698     EXPECT_OK(validationPointerInterface->bar10([&](const auto& v) {
1699         EXPECT_OK(pointerInterface->foo10(v));
1700     }));
1701 }
TEST_F(HidlTest,PointerPassVecRefTest)1702 TEST_F(HidlTest, PointerPassVecRefTest) {
1703     EXPECT_OK(validationPointerInterface->bar11([&](const auto& v) {
1704         EXPECT_OK(pointerInterface->foo11(v));
1705     }));
1706 }
TEST_F(HidlTest,PointerPassArrayRefTest)1707 TEST_F(HidlTest, PointerPassArrayRefTest) {
1708     EXPECT_OK(validationPointerInterface->bar12([&](const auto& array) {
1709         EXPECT_OK(pointerInterface->foo12(array));
1710     }));
1711 }
TEST_F(HidlTest,PointerPassRefArrayTest)1712 TEST_F(HidlTest, PointerPassRefArrayTest) {
1713     EXPECT_OK(validationPointerInterface->bar13([&](const auto& array) {
1714         EXPECT_OK(pointerInterface->foo13(array));
1715     }));
1716 }
TEST_F(HidlTest,PointerPass3RefTest)1717 TEST_F(HidlTest, PointerPass3RefTest) {
1718     EXPECT_OK(validationPointerInterface->bar14([&](const auto& p3) {
1719         EXPECT_OK(pointerInterface->foo14(p3));
1720     }));
1721 }
TEST_F(HidlTest,PointerPassInt3RefTest)1722 TEST_F(HidlTest, PointerPassInt3RefTest) {
1723     EXPECT_OK(validationPointerInterface->bar15([&](const auto& p3) {
1724         EXPECT_OK(pointerInterface->foo15(p3));
1725     }));
1726 }
TEST_F(HidlTest,PointerPassEmbeddedPointersTest)1727 TEST_F(HidlTest, PointerPassEmbeddedPointersTest) {
1728     EXPECT_OK(validationPointerInterface->bar16([&](const auto& p) {
1729         EXPECT_OK(pointerInterface->foo16(p));
1730     }));
1731 }
TEST_F(HidlTest,PointerPassEmbeddedPointers2Test)1732 TEST_F(HidlTest, PointerPassEmbeddedPointers2Test) {
1733     EXPECT_OK(validationPointerInterface->bar17([&](const auto& p) {
1734         EXPECT_OK(pointerInterface->foo17(p));
1735     }));
1736 }
TEST_F(HidlTest,PointerPassCopiedStringTest)1737 TEST_F(HidlTest, PointerPassCopiedStringTest) {
1738     EXPECT_OK(validationPointerInterface->bar18([&](const auto& str_ref, const auto& str_ref2, const auto& str) {
1739         EXPECT_OK(pointerInterface->foo18(str_ref, str_ref2, str));
1740     }));
1741 }
TEST_F(HidlTest,PointerPassCopiedVecTest)1742 TEST_F(HidlTest, PointerPassCopiedVecTest) {
1743     EXPECT_OK(validationPointerInterface->bar19([&](const auto& a_vec_ref, const auto& a_vec, const auto& a_vec_ref2) {
1744         EXPECT_OK(pointerInterface->foo19(a_vec_ref, a_vec, a_vec_ref2));
1745     }));
1746 }
TEST_F(HidlTest,PointerPassBigRefVecTest)1747 TEST_F(HidlTest, PointerPassBigRefVecTest) {
1748     EXPECT_OK(validationPointerInterface->bar20([&](const auto& v) {
1749         EXPECT_FAIL(pointerInterface->foo20(v));
1750     }));
1751 }
TEST_F(HidlTest,PointerPassMultidimArrayRefTest)1752 TEST_F(HidlTest, PointerPassMultidimArrayRefTest) {
1753     EXPECT_OK(validationPointerInterface->bar21([&](const auto& v) {
1754         EXPECT_OK(pointerInterface->foo21(v));
1755     }));
1756 }
TEST_F(HidlTest,PointerPassRefMultidimArrayTest)1757 TEST_F(HidlTest, PointerPassRefMultidimArrayTest) {
1758     EXPECT_OK(validationPointerInterface->bar22([&](const auto& v) {
1759         EXPECT_OK(pointerInterface->foo22(v));
1760     }));
1761 }
TEST_F(HidlTest,PointerGiveOldBufferTest)1762 TEST_F(HidlTest, PointerGiveOldBufferTest) {
1763     EXPECT_OK(pointerInterface->bar1([&](const auto& sptr, const auto& s) {
1764         EXPECT_OK(validationPointerInterface->foo1(sptr, s));
1765     }));
1766 }
TEST_F(HidlTest,PointerGiveOldBufferTest2)1767 TEST_F(HidlTest, PointerGiveOldBufferTest2) {
1768     EXPECT_OK(pointerInterface->bar2([&](const auto& s, const auto& a) {
1769         EXPECT_OK(validationPointerInterface->foo2(s, a));
1770     }));
1771 }
TEST_F(HidlTest,PointerGiveSameOldBufferPointerTest)1772 TEST_F(HidlTest, PointerGiveSameOldBufferPointerTest) {
1773     EXPECT_OK(pointerInterface->bar3([&](const auto& s, const auto& a, const auto& b) {
1774         EXPECT_OK(validationPointerInterface->foo3(s, a, b));
1775     }));
1776 }
TEST_F(HidlTest,PointerGiveOnlyTest)1777 TEST_F(HidlTest, PointerGiveOnlyTest) {
1778     EXPECT_OK(pointerInterface->bar4([&](const auto& s) {
1779         EXPECT_OK(validationPointerInterface->foo4(s));
1780     }));
1781 }
TEST_F(HidlTest,PointerGiveTwoEmbeddedTest)1782 TEST_F(HidlTest, PointerGiveTwoEmbeddedTest) {
1783     EXPECT_OK(pointerInterface->bar5([&](const auto& a, const auto& b) {
1784         EXPECT_OK(validationPointerInterface->foo5(a, b));
1785     }));
1786 }
TEST_F(HidlTest,PointerGiveIndirectBufferHasDataTest)1787 TEST_F(HidlTest, PointerGiveIndirectBufferHasDataTest) {
1788     EXPECT_OK(pointerInterface->bar6([&](const auto& a) {
1789         EXPECT_OK(validationPointerInterface->foo6(a));
1790     }));
1791 }
TEST_F(HidlTest,PointerGiveTwoIndirectBufferTest)1792 TEST_F(HidlTest, PointerGiveTwoIndirectBufferTest) {
1793     EXPECT_OK(pointerInterface->bar7([&](const auto& a, const auto& b) {
1794         EXPECT_OK(validationPointerInterface->foo7(a, b));
1795     }));
1796 }
TEST_F(HidlTest,PointerGiveDeeplyIndirectTest)1797 TEST_F(HidlTest, PointerGiveDeeplyIndirectTest) {
1798     EXPECT_OK(pointerInterface->bar8([&](const auto& d) {
1799         EXPECT_OK(validationPointerInterface->foo8(d));
1800     }));
1801 }
TEST_F(HidlTest,PointerGiveStringRefTest)1802 TEST_F(HidlTest, PointerGiveStringRefTest) {
1803     EXPECT_OK(pointerInterface->bar9([&](const auto& str) {
1804         EXPECT_OK(validationPointerInterface->foo9(str));
1805     }));
1806 }
TEST_F(HidlTest,PointerGiveRefVecTest)1807 TEST_F(HidlTest, PointerGiveRefVecTest) {
1808     EXPECT_OK(pointerInterface->bar10([&](const auto& v) {
1809         EXPECT_OK(validationPointerInterface->foo10(v));
1810     }));
1811 }
TEST_F(HidlTest,PointerGiveVecRefTest)1812 TEST_F(HidlTest, PointerGiveVecRefTest) {
1813     EXPECT_OK(pointerInterface->bar11([&](const auto& v) {
1814         EXPECT_OK(validationPointerInterface->foo11(v));
1815     }));
1816 }
TEST_F(HidlTest,PointerGiveArrayRefTest)1817 TEST_F(HidlTest, PointerGiveArrayRefTest) {
1818     EXPECT_OK(pointerInterface->bar12([&](const auto& array) {
1819         EXPECT_OK(validationPointerInterface->foo12(array));
1820     }));
1821 }
TEST_F(HidlTest,PointerGiveRefArrayTest)1822 TEST_F(HidlTest, PointerGiveRefArrayTest) {
1823     EXPECT_OK(pointerInterface->bar13([&](const auto& array) {
1824         EXPECT_OK(validationPointerInterface->foo13(array));
1825     }));
1826 }
TEST_F(HidlTest,PointerGive3RefTest)1827 TEST_F(HidlTest, PointerGive3RefTest) {
1828     EXPECT_OK(pointerInterface->bar14([&](const auto& p3) {
1829         EXPECT_OK(validationPointerInterface->foo14(p3));
1830     }));
1831 }
TEST_F(HidlTest,PointerGiveInt3RefTest)1832 TEST_F(HidlTest, PointerGiveInt3RefTest) {
1833     EXPECT_OK(pointerInterface->bar15([&](const auto& p3) {
1834         EXPECT_OK(validationPointerInterface->foo15(p3));
1835     }));
1836 }
TEST_F(HidlTest,PointerGiveEmbeddedPointersTest)1837 TEST_F(HidlTest, PointerGiveEmbeddedPointersTest) {
1838     EXPECT_OK(pointerInterface->bar16([&](const auto& p) {
1839         EXPECT_OK(validationPointerInterface->foo16(p));
1840     }));
1841 }
TEST_F(HidlTest,PointerGiveEmbeddedPointers2Test)1842 TEST_F(HidlTest, PointerGiveEmbeddedPointers2Test) {
1843     EXPECT_OK(pointerInterface->bar17([&](const auto& p) {
1844         EXPECT_OK(validationPointerInterface->foo17(p));
1845     }));
1846 }
TEST_F(HidlTest,PointerGiveCopiedStringTest)1847 TEST_F(HidlTest, PointerGiveCopiedStringTest) {
1848     EXPECT_OK(pointerInterface->bar18([&](const auto& str_ref, const auto& str_ref2, const auto& str) {
1849         EXPECT_OK(validationPointerInterface->foo18(str_ref, str_ref2, str));
1850     }));
1851 }
TEST_F(HidlTest,PointerGiveCopiedVecTest)1852 TEST_F(HidlTest, PointerGiveCopiedVecTest) {
1853     EXPECT_OK(pointerInterface->bar19([&](const auto& a_vec_ref, const auto& a_vec, const auto& a_vec_ref2) {
1854         EXPECT_OK(validationPointerInterface->foo19(a_vec_ref, a_vec, a_vec_ref2));
1855     }));
1856 }
1857 // This cannot be enabled until _hidl_error is not ignored when
1858 // the remote writeEmbeddedReferencesToParcel.
1859 // TEST_F(HidlTest, PointerGiveBigRefVecTest) {
1860 //     EXPECT_FAIL(pointerInterface->bar20([&](const auto& v) {
1861 //     }));
1862 // }
TEST_F(HidlTest,PointerGiveMultidimArrayRefTest)1863 TEST_F(HidlTest, PointerGiveMultidimArrayRefTest) {
1864     EXPECT_OK(pointerInterface->bar21([&](const auto& v) {
1865         EXPECT_OK(validationPointerInterface->foo21(v));
1866     }));
1867 }
TEST_F(HidlTest,PointerGiveRefMultidimArrayTest)1868 TEST_F(HidlTest, PointerGiveRefMultidimArrayTest) {
1869     EXPECT_OK(pointerInterface->bar22([&](const auto& v) {
1870         EXPECT_OK(validationPointerInterface->foo22(v));
1871     }));
1872 }
TEST_F(HidlTest,PointerReportErrorsTest)1873 TEST_F(HidlTest, PointerReportErrorsTest) {
1874     Return<int32_t> ret = pointerInterface->getErrors();
1875     EXPECT_OK(ret);
1876     EXPECT_EQ(int32_t(ret), 0);
1877 }
1878 #endif
1879 
forkAndRunTests(TestMode mode,bool enableDelayMeasurementTests)1880 int forkAndRunTests(TestMode mode, bool enableDelayMeasurementTests) {
1881     pid_t child;
1882     int status;
1883 
1884     const char* modeText = (mode == BINDERIZED) ? "BINDERIZED" : "PASSTHROUGH";
1885     ALOGI("Start running tests in %s mode...", modeText);
1886     fprintf(stdout, "Start running tests in %s mode...\n", modeText);
1887     fflush(stdout);
1888 
1889     if ((child = fork()) == 0) {
1890         gHidlEnvironment = static_cast<HidlEnvironment *>(
1891                 ::testing::AddGlobalTestEnvironment(new HidlEnvironment(
1892                         mode, enableDelayMeasurementTests)));
1893         int testStatus = RUN_ALL_TESTS();
1894         if(testStatus == 0) {
1895             exit(0);
1896         }
1897         int failed = ::testing::UnitTest::GetInstance()->failed_test_count();
1898         if (failed == 0) {
1899             exit(-testStatus);
1900         }
1901         exit(failed);
1902     }
1903     waitpid(child, &status, 0 /* options */);
1904     ALOGI("All tests finished in %s mode.", modeText);
1905     fprintf(stdout, "All tests finished in %s mode.\n", modeText);
1906     fflush(stdout);
1907     return status;
1908 }
1909 
handleStatus(int status,const char * mode)1910 void handleStatus(int status, const char *mode) {
1911     if (status != 0) {
1912         if (WIFEXITED(status)) {
1913             status = WEXITSTATUS(status);
1914             if (status < 0) {
1915                 fprintf(stdout, "    RUN_ALL_TESTS returns %d for %s mode.\n", -status, mode);
1916             } else {
1917                 fprintf(stdout, "    %d test(s) failed for %s mode.\n", status, mode);
1918             }
1919         } else {
1920             fprintf(stdout, "    ERROR: %s child process exited abnormally with %d\n", mode, status);
1921         }
1922     }
1923 }
1924 
usage(const char * me)1925 static void usage(const char *me) {
1926     fprintf(stderr,
1927             "usage: %s [-b] [-p] [-d] [GTEST_OPTIONS]\n",
1928             me);
1929 
1930     fprintf(stderr, "         -b binderized mode only\n");
1931     fprintf(stderr, "         -p passthrough mode only\n");
1932     fprintf(stderr, "            (if -b and -p are both missing or both present, "
1933                                  "both modes are tested.)\n");
1934     fprintf(stderr, "         -d Enable delay measurement tests\n");
1935 }
1936 
main(int argc,char ** argv)1937 int main(int argc, char **argv) {
1938     setenv("TREBLE_TESTING_OVERRIDE", "true", true);
1939 
1940     const char *me = argv[0];
1941     bool b = false;
1942     bool p = false;
1943     bool d = false;
1944     struct option longopts[] = {{0,0,0,0}};
1945     int res;
1946     while ((res = getopt_long(argc, argv, "hbpd", longopts, NULL)) >= 0) {
1947         switch (res) {
1948             case 'h': {
1949                 usage(me);
1950                 exit(1);
1951             } break;
1952 
1953             case 'b': {
1954                 b = true;
1955             } break;
1956 
1957             case 'p': {
1958                 p = true;
1959             } break;
1960 
1961             case 'd': {
1962                 d = true;
1963             } break;
1964 
1965             case '?':
1966             default: {
1967                 // ignore. pass to gTest.
1968             } break;
1969         }
1970     }
1971     if (!b && !p) {
1972         b = p = true;
1973     }
1974 
1975     ::testing::InitGoogleTest(&argc, argv);
1976     // put test in child process because RUN_ALL_TESTS
1977     // should not be run twice.
1978     int pStatus = p ? forkAndRunTests(PASSTHROUGH, d) : 0;
1979     int bStatus = b ? forkAndRunTests(BINDERIZED, d)  : 0;
1980 
1981     fprintf(stdout, "\n=========================================================\n\n"
1982                     "    Summary:\n\n");
1983     if (p) {
1984         ALOGI("PASSTHROUGH Test result = %d", pStatus);
1985         handleStatus(pStatus, "PASSTHROUGH");
1986     }
1987     if (b) {
1988         ALOGI("BINDERIZED Test result = %d", bStatus);
1989         handleStatus(bStatus, "BINDERIZED ");
1990     }
1991 
1992     if (pStatus == 0 && bStatus == 0) {
1993         fprintf(stdout, "    Hooray! All tests passed.\n");
1994     }
1995     fprintf(stdout, "\n=========================================================\n\n");
1996 
1997     return pStatus + bStatus != 0;
1998 }
1999