From e5f69206add92991f6766ea9a1ecd9fe9e88f7f2 Mon Sep 17 00:00:00 2001 From: Marian Buschsieweke Date: Wed, 31 Jan 2024 07:55:26 +0100 Subject: [PATCH] sys/libc/endian.h: fix magic constants The constants BIG_ENDIAN etc. were not consistently defined. This bug was not caught by the unit tests, as the preprocessor would treat undefined macros as being `0` in numeric comparisons, hence the following test did select the correct implementation: ```C #if BYTE_ORDER == LITTLE_ENDIAN /* correct implementation for all currently supported boards */ #endif ``` This adds now an explicit test to the unit tests to ensure that the magic numbers are consistently the correct values. Hence, this bug should no longer be able to sneak in. Co-authored-by: Teufelchen <9516484+Teufelchen1@users.noreply.github.com> --- sys/libc/include/endian.h | 14 +++++++------- tests/unittests/tests-libc/tests-libc.c | 5 +++++ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/sys/libc/include/endian.h b/sys/libc/include/endian.h index ca90d3b128..d4a8de3866 100644 --- a/sys/libc/include/endian.h +++ b/sys/libc/include/endian.h @@ -30,17 +30,17 @@ extern "C" { /** * @brief A numeric constant representing little endian byte order */ -#define LITTLE_ENDIAN implementation_defined +#define LITTLE_ENDIAN magic-number /** * @brief A numeric constant representing big endian byte order */ -#define BIG_ENDIAN implementation_defined +#define BIG_ENDIAN magic-number /** * @brief A numeric constant representing PDP endian byte order */ -#define PDP_ENDIAN implementation_defined +#define PDP_ENDIAN magic-number /** * @brief The byte order of this machines indicated by the constant @@ -69,10 +69,10 @@ uint64_t le64toh(uint64_t little_endian_64bits);/**< little endian to host, 64 b #else /* DOXYGEN */ -#define LITTLE_ENDIAN _LITTLE_ENDIAN -#define BIG_ENDIAN _BIG_ENDIAN -#define PDP_ENDIAN _PDP_ENDIAN -#define BYTE_ORDER _BYTE_ORDER +#define LITTLE_ENDIAN 1234 +#define BIG_ENDIAN 4321 +#define PDP_ENDIAN 3412 +#define BYTE_ORDER __BYTE_ORDER__ #if BYTE_ORDER == LITTLE_ENDIAN # define htobe16(_x) __builtin_bswap16(_x) diff --git a/tests/unittests/tests-libc/tests-libc.c b/tests/unittests/tests-libc/tests-libc.c index 82796c312c..9fa8f10c20 100644 --- a/tests/unittests/tests-libc/tests-libc.c +++ b/tests/unittests/tests-libc/tests-libc.c @@ -89,6 +89,11 @@ static void test_libc_endian(void) TEST_ASSERT_EQUAL_INT(le32toh(u32_le.as_number), u32_host); TEST_ASSERT_EQUAL_INT(be64toh(u64_be.as_number), u64_host); TEST_ASSERT_EQUAL_INT(le64toh(u64_le.as_number), u64_host); + + /* check that magic numbers in the constants are what is commonly expected */ + TEST_ASSERT_EQUAL_INT(LITTLE_ENDIAN, 1234); + TEST_ASSERT_EQUAL_INT(BIG_ENDIAN, 4321); + TEST_ASSERT_EQUAL_INT(PDP_ENDIAN, 3412); } /** @} */