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