Tests & stronger guarantees for hidl_* pads.

- Test that pads are zero (for future proofing, also ran tests
  on original implementation and bugfix).
- Use -Wpadded so that compiler guarantees there aren't padding
  bits hiding elsewhere (there aren't)

Bug: 131356202
Test: libhidl_test
  (without fixes, with fixes, and with this CL)

Change-Id: Ib52a16015b0393c104cd984376328cb0da888b03
Merged-In: Ib52a16015b0393c104cd984376328cb0da888b03
diff --git a/test_main.cpp b/test_main.cpp
index 7b6781a..083cee4 100644
--- a/test_main.cpp
+++ b/test_main.cpp
@@ -16,11 +16,16 @@
 
 #define LOG_TAG "LibHidlTest"
 
+#pragma clang diagnostic push
+#pragma clang diagnostic fatal "-Wpadded"
+#include <hidl/HidlInternal.h>
+#include <hidl/HidlSupport.h>
+#pragma clang diagnostic pop
+
 #include <android-base/logging.h>
 #include <android/hidl/memory/1.0/IMemory.h>
 #include <gmock/gmock.h>
 #include <gtest/gtest.h>
-#include <hidl/HidlSupport.h>
 #include <hidl/ServiceManagement.h>
 #include <hidl/Status.h>
 #include <hidl/TaskRunner.h>
@@ -570,6 +575,51 @@
     EXPECT_TRUE(isLibraryOpen(kLib));
 }
 
+template <typename T, size_t start, size_t end>
+static void assertZeroInRange(const T* t) {
+    static_assert(start < sizeof(T));
+    static_assert(end <= sizeof(T));
+
+    const uint8_t* ptr = reinterpret_cast<const uint8_t*>(t);
+
+    for (size_t i = start; i < end; i++) {
+        EXPECT_EQ(0, ptr[i]);
+    }
+}
+
+template <typename T, size_t start, size_t end>
+static void uninitTest() {
+    uint8_t buf[sizeof(T)];
+    memset(buf, 0xFF, sizeof(T));
+
+    T* type = new (buf) T;
+    assertZeroInRange<T, start, end>(type);
+    type->~T();
+}
+
+TEST_F(LibHidlTest, HidlVecUninit) {
+    using ::android::hardware::hidl_vec;
+    struct SomeType {};
+    static_assert(sizeof(hidl_vec<SomeType>) == 16);
+
+    // padding after mOwnsBuffer
+    uninitTest<hidl_vec<SomeType>, 13, 16>();
+}
+TEST_F(LibHidlTest, HidlHandleUninit) {
+    using ::android::hardware::hidl_handle;
+    static_assert(sizeof(hidl_handle) == 16);
+
+    // padding after mOwnsHandle
+    uninitTest<hidl_handle, 9, 16>();
+}
+TEST_F(LibHidlTest, HidlStringUninit) {
+    using ::android::hardware::hidl_string;
+    static_assert(sizeof(hidl_string) == 16);
+
+    // padding after mOwnsBuffer
+    uninitTest<hidl_string, 13, 16>();
+}
+
 int main(int argc, char **argv) {
     ::testing::InitGoogleTest(&argc, argv);
     return RUN_ALL_TESTS();