On Mon, Jan 29, 2024 at 09:16:36PM +0100, Rasmus Villemoes wrote:
> 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 <[email protected]>
> > Cc: Mark Rutland <[email protected]>
> > Cc: "Gustavo A. R. Silva" <[email protected]>
> > Cc: [email protected]
> > Signed-off-by: Kees Cook <[email protected]>
> > ---
> >  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

Thanks, fixed.

> 
> > + * @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.

I am normally defensive about this, but due to @a normally being an
lvalue, I lacked the imagination to think of other side-effects, but
you've set me straight below.

> 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.

Yeah, an index-fetch is a great example that would get lost here. I've
updated these to be defined in terms of add/sub_wrap() and to use your
pointer typing method to avoid side-effects.

-- 
Kees Cook

Reply via email to