[xxHash] Don't trigger UB on empty StringRef
authorBenjamin Kramer <benny.kra@googlemail.com>
Wed, 8 Feb 2023 11:53:54 +0000 (12:53 +0100)
committerBenjamin Kramer <benny.kra@googlemail.com>
Wed, 8 Feb 2023 11:53:54 +0000 (12:53 +0100)
This is quite silly, but casting to uintptr_t seems like the easiest
option to quiet ubsan.

llvm/lib/Support/xxhash.cpp:107:12: runtime error: applying non-zero offset 8 to null pointer
    #0 0x7fe3660404c0 in llvm::xxHash64(llvm::StringRef) llvm/lib/Support/xxhash.cpp:107:12

llvm/lib/Support/xxhash.cpp
llvm/unittests/Support/xxhashTest.cpp

index 9a3f5fa..99b94a9 100644 (file)
@@ -104,14 +104,15 @@ uint64_t llvm::xxHash64(StringRef Data) {
 
   H64 += (uint64_t)Len;
 
-  while (P + 8 <= BEnd) {
+  while (reinterpret_cast<uintptr_t>(P) + 8 <=
+         reinterpret_cast<uintptr_t>(BEnd)) {
     uint64_t const K1 = round(0, endian::read64le(P));
     H64 ^= K1;
     H64 = rotl64(H64, 27) * PRIME64_1 + PRIME64_4;
     P += 8;
   }
 
-  if (P + 4 <= BEnd) {
+  if (reinterpret_cast<uintptr_t>(P) + 4 <= reinterpret_cast<uintptr_t>(BEnd)) {
     H64 ^= (uint64_t)(endian::read32le(P)) * PRIME64_1;
     H64 = rotl64(H64, 23) * PRIME64_2 + PRIME64_3;
     P += 4;
index 7dc7c40..f5c49e4 100644 (file)
@@ -12,6 +12,7 @@
 using namespace llvm;
 
 TEST(xxhashTest, Basic) {
+  EXPECT_EQ(0xef46db3751d8e999U, xxHash64(StringRef()));
   EXPECT_EQ(0x33bf00a859c4ba3fU, xxHash64("foo"));
   EXPECT_EQ(0x48a37c90ad27a659U, xxHash64("bar"));
   EXPECT_EQ(0x69196c1b3af0bff9U,