From bbf881053d1801a7cbf22edfc534e7291a3fa300 Mon Sep 17 00:00:00 2001 From: Dave Rodgman Date: Fri, 21 Apr 2023 12:54:40 +0100 Subject: [PATCH] Document undefined case. Clarify test code. Signed-off-by: Dave Rodgman --- library/bignum_core.c | 13 ++++++++++--- tests/suites/test_suite_bignum_core.function | 15 +++++++++------ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/library/bignum_core.c b/library/bignum_core.c index 1f3a57c05..998c06c8f 100644 --- a/library/bignum_core.c +++ b/library/bignum_core.c @@ -33,11 +33,18 @@ #include "bn_mul.h" #include "constant_time_internal.h" +/** + * \brief Count leading zeros + * + * \warning The result is undefined if \p a == 0 + * + * \param a The value to operate on + * + * \return The number of leading zeros, if \p a != 0. If \p a == 0, the result + * is undefined. + */ inline size_t mbedtls_mpi_core_clz(mbedtls_mpi_uint a) { - /* Note: the result is undefined for a == 0 - * (because this is the behaviour of __builtin_clz). - */ #if defined(__has_builtin) #if __has_builtin(__builtin_clz) if (sizeof(mbedtls_mpi_uint) == sizeof(unsigned int)) { diff --git a/tests/suites/test_suite_bignum_core.function b/tests/suites/test_suite_bignum_core.function index 6f810ff72..53aa002ce 100644 --- a/tests/suites/test_suite_bignum_core.function +++ b/tests/suites/test_suite_bignum_core.function @@ -311,25 +311,28 @@ exit: /* BEGIN_CASE */ -void mpi_core_clz(int lz, int tz) +void mpi_core_clz(int leading_zeros, int trailing_zeros) { - if ((size_t) (lz + tz) >= (sizeof(mbedtls_mpi_uint) * 8)) { + if ((size_t) (leading_zeros + trailing_zeros) >= (sizeof(mbedtls_mpi_uint) * 8)) { // can't fit required number of leading and trailing zeros - skip test goto exit; } + // Construct a test input value where the count of leading zeros and + // trailing zeros is given in the test case, and we add ones to fill + // the gap. mbedtls_mpi_uint x; - if ((lz + tz) > 0) { + if ((leading_zeros + trailing_zeros) > 0) { // some zero bits - uint32_t s = (sizeof(mbedtls_mpi_uint) * 8 - lz - tz); - x = ((((mbedtls_mpi_uint) 1) << s) - 1) << tz; + uint32_t s = (sizeof(mbedtls_mpi_uint) * 8 - leading_zeros - trailing_zeros); + x = ((((mbedtls_mpi_uint) 1) << s) - 1) << trailing_zeros; } else { // all bits set x = ~((mbedtls_mpi_uint) 0); } size_t n = mbedtls_mpi_core_clz(x); - TEST_EQUAL(n, lz); + TEST_EQUAL(n, leading_zeros); exit: ; }