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