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