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