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