From 6fb44164ecdb2227be73344724be10eb9b50a6e1 Mon Sep 17 00:00:00 2001 From: Richard Braun Date: Wed, 28 Mar 2018 00:28:34 +0200 Subject: hash: fix undefined behavior in hash_str Reported by Laurent Dufresne. --- src/hash.h | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/hash.h b/src/hash.h index a5b1de0..0013830 100644 --- a/src/hash.h +++ b/src/hash.h @@ -48,6 +48,7 @@ #define HASH_H #include +#include #include #ifdef __LP64__ @@ -59,11 +60,19 @@ static_assert(sizeof(long) == 4, "unsupported data model"); #define hash_long(n, bits) hash_int32(n, bits) #endif +static inline bool +hash_bits_valid(unsigned int bits) +{ + return (bits != 0) && (bits <= HASH_ALLBITS); +} + static inline uint32_t hash_int32(uint32_t n, unsigned int bits) { uint32_t hash; + assert(hash_bits_valid(bits)); + hash = n; hash = ~hash + (hash << 15); hash ^= (hash >> 12); @@ -80,6 +89,8 @@ hash_int64(uint64_t n, unsigned int bits) { uint64_t hash; + assert(hash_bits_valid(bits)); + hash = n; hash = ~hash + (hash << 21); hash ^= (hash >> 24); @@ -105,9 +116,11 @@ hash_ptr(const void *ptr, unsigned int bits) static inline unsigned long hash_str(const char *str, unsigned int bits) { - unsigned long hash; + unsigned long hash, mask; char c; + assert(hash_bits_valid(bits)); + for (hash = 0; /* no condition */; str++) { c = *str; @@ -118,7 +131,13 @@ hash_str(const char *str, unsigned int bits) hash = ((hash << 5) - hash) + c; } - return hash & ((1UL << bits) - 1); + /* + * This mask construction avoids the undefined behavior that would + * result from directly shifting by the number of bits, if that number + * is equal to the width of the hash. + */ + mask = (~0UL >> (HASH_ALLBITS - bits)); + return hash & mask; } #endif /* HASH_H */ -- cgit v1.2.3