Re: [PATCH 5/5] overflow: Introduce inc_wrap() and dec_wrap()

From: Rasmus Villemoes
Date: Mon Jan 29 2024 - 15:16:51 EST


On 29/01/2024 19.34, Kees Cook wrote:
> This allows replacements of the idioms "var += offset" and "var -= offset"
> with the inc_wrap() and dec_wrap() helpers respectively. They will avoid
> wrap-around sanitizer instrumentation.
>
> Cc: Rasmus Villemoes <rasmus.villemoes@xxxxxxxxx>
> Cc: Mark Rutland <mark.rutland@xxxxxxx>
> Cc: "Gustavo A. R. Silva" <gustavoars@xxxxxxxxxx>
> Cc: linux-hardening@xxxxxxxxxxxxxxx
> Signed-off-by: Kees Cook <keescook@xxxxxxxxxxxx>
> ---
> include/linux/overflow.h | 32 ++++++++++++++++++++++++++++++++
> 1 file changed, 32 insertions(+)
>
> diff --git a/include/linux/overflow.h b/include/linux/overflow.h
> index 4f945e9e7881..080b18b84498 100644
> --- a/include/linux/overflow.h
> +++ b/include/linux/overflow.h
> @@ -138,6 +138,22 @@ static inline bool __must_check __must_check_overflow(bool overflow)
> __sum; \
> })
>
> +/**
> + * add_wrap() - Intentionally perform a wrapping increment

inc_wrap

> + * @a: variable to be incremented
> + * @b: amount to add
> + *
> + * Increments @a by @b with wrap-around. Returns the resulting
> + * value of @a. Will not trip any wrap-around sanitizers.
> + */
> +#define inc_wrap(var, offset) \
> + ({ \
> + if (check_add_overflow(var, offset, &var)) { \
> + /* do nothing */ \
> + } \
> + var; \

Hm. I wonder if multiple evaluations of var could be a problem.
Obviously never if var is actually some automatic variable, nor if it is
some simple foo->bar expression. But nothing really prevents var from
being, say, foo[gimme_an_index()] or something similarly convoluted.

Does the compiler generate ok code if one does

typeof(var) *__pvar = &(var);
if (check_add_overflow(*__pvar, offset, __pvar)) {}
*__pvar;

[in fact, does it even generate code, i.e. does it compile?]

I dunno, maybe it's overkill to worry about.

Rasmus