From 7202f9e091c4b2687e03af683ecc6346d044ab7c Mon Sep 17 00:00:00 2001 From: Matthew Parkinson Date: Tue, 6 Apr 2021 09:58:50 +0100 Subject: [PATCH] Handle UB that was not exercised originally. --- src/ds/bits.h | 7 ++++++- src/test/func/bits/bits.cc | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/ds/bits.h b/src/ds/bits.h index 1fc90e4..ec32e3c 100644 --- a/src/ds/bits.h +++ b/src/ds/bits.h @@ -55,6 +55,7 @@ namespace snmalloc SNMALLOC_FAST_PATH size_t clz(size_t x) { + SNMALLOC_ASSERT(x != 0); // Calling with 0 is UB on some implementations #if defined(_MSC_VER) # ifdef USE_LZCNT # ifdef SNMALLOC_VA_BITS_64 @@ -148,6 +149,8 @@ namespace snmalloc inline size_t ctz(size_t x) { + SNMALLOC_ASSERT(x != 0); // Calling with 0 is UB on some implementations + #if defined(_MSC_VER) # ifdef SNMALLOC_VA_BITS_64 return _tzcnt_u64(x); @@ -229,7 +232,9 @@ namespace snmalloc inline size_t next_pow2_bits(size_t x) { // Correct for numbers [1..MAX_SIZE]. - // Returns 64 for 0. Approximately 2 cycles. + if (x == 1) + return 0; + return BITS - clz(x - 1); } diff --git a/src/test/func/bits/bits.cc b/src/test/func/bits/bits.cc index 26c5ae7..f78be0b 100644 --- a/src/test/func/bits/bits.cc +++ b/src/test/func/bits/bits.cc @@ -2,8 +2,8 @@ * Unit tests for operations in bits.h */ -#include #include +#include #include void test_ctz()