Re: [PATCH 03/82] overflow: Introduce add_wrap()

From: Rasmus Villemoes
Date: Tue Jan 23 2024 - 03:14:59 EST


On 23/01/2024 01.26, Kees Cook wrote:
> Provide a helper that will perform wrapping addition without tripping
> the arithmetic wrap-around sanitizers.
>
> Cc: "Gustavo A. R. Silva" <gustavoars@xxxxxxxxxx>
> Cc: linux-hardening@xxxxxxxxxxxxxxx
> Signed-off-by: Kees Cook <keescook@xxxxxxxxxxxx>
> ---
> include/linux/overflow.h | 16 ++++++++++++++++
> 1 file changed, 16 insertions(+)
>
> diff --git a/include/linux/overflow.h b/include/linux/overflow.h
> index ac088f73e0fd..30779905a77a 100644
> --- a/include/linux/overflow.h
> +++ b/include/linux/overflow.h
> @@ -124,6 +124,22 @@ static inline bool __must_check __must_check_overflow(bool overflow)
> check_add_overflow(a, b, &__result);\
> }))
>
> +/**
> + * add_wrap() - Intentionally perform a wrapping addition
> + * @a: first addend
> + * @b: second addend
> + *
> + * Return the potentially wrapped-around addition without
> + * tripping any overflow sanitizers that may be enabled.
> + */
> +#define add_wrap(a, b) \
> + ({ \
> + typeof(a) __sum; \
> + if (check_add_overflow(a, b, &__sum)) \
> + /* do nothing */; \
> + __sum; \
> + })
> +

I don't know where this is supposed to be used, but at first glance this
seems to introduce a footgun. This is not symmetric in a and b, so both
the type and value of the result may differ between add_wrap(a, b) and
add_wrap(b, a). That seems dangerous.

Rasmus