From: Emil Velikov Date: Mon, 30 Sep 2024 20:06:14 +0000 (+0100) Subject: shared: introduce uadd32_overflow() helper X-Git-Tag: v34~248 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=8808f0eeaaafee0e0e9e59671829c7fec55108a8;p=thirdparty%2Fkmod.git shared: introduce uadd32_overflow() helper We'll use it in the upcoming size_t variant. Signed-off-by: Emil Velikov Link: https://github.com/kmod-project/kmod/pull/169 Signed-off-by: Lucas De Marchi --- diff --git a/meson.build b/meson.build index 1c87fe0e..eb5cfadd 100644 --- a/meson.build +++ b/meson.build @@ -49,6 +49,7 @@ endforeach _builtins = [ ['__builtin_clz', '0', true], ['__builtin_types_compatible_p', 'int, int', true], + ['__builtin_uadd_overflow', '0U, 0U, (void*)0', false], ['__builtin_uaddl_overflow', '0UL, 0UL, (void*)0', false], ['__builtin_uaddll_overflow', '0ULL, 0ULL, (void*)0', false], ] diff --git a/shared/util.h b/shared/util.h index 6fa4bf43..87c72796 100644 --- a/shared/util.h +++ b/shared/util.h @@ -92,6 +92,16 @@ static inline void freep(void *p) } #define _cleanup_free_ _cleanup_(freep) +static inline bool uadd32_overflow(uint32_t a, uint32_t b, uint32_t *res) +{ +#if (HAVE___BUILTIN_UADD_OVERFLOW && __SIZEOF_INT__ == 4) + return __builtin_uadd_overflow(a, b, res); +#else + *res = a + b; + return UINT32_MAX - a < b; +#endif +} + static inline bool uadd64_overflow(uint64_t a, uint64_t b, uint64_t *res) { #if (HAVE___BUILTIN_UADDL_OVERFLOW && __SIZEOF_LONG__ == 8) diff --git a/testsuite/test-util.c b/testsuite/test-util.c index ce246d39..1f968606 100644 --- a/testsuite/test-util.c +++ b/testsuite/test-util.c @@ -191,6 +191,23 @@ DEFINE_TEST(test_write_str_safe, }, }); +static int test_uadd32_overflow(const struct test *t) +{ + uint32_t res; + bool overflow; + + overflow = uadd32_overflow(UINT32_MAX - 1, 1, &res); + assert_return(!overflow, EXIT_FAILURE); + assert_return(res == UINT32_MAX, EXIT_FAILURE); + + overflow = uadd32_overflow(UINT32_MAX, 1, &res); + assert_return(overflow, EXIT_FAILURE); + + return EXIT_SUCCESS; +} +DEFINE_TEST(test_uadd32_overflow, + .description = "check implementation of uadd32_overflow()") + static int test_uadd64_overflow(const struct test *t) { uint64_t res;