Re: [PATCH 2/4] fortify: Explicitly check bounds are compile-time constants

From: Kees Cook
Date: Wed Sep 21 2022 - 23:46:59 EST


On Wed, Sep 21, 2022 at 07:48:44AM -0400, Siddhesh Poyarekar wrote:
> On 2022-09-20 15:22, Kees Cook wrote:
> > In preparation for replacing __builtin_object_size() with
> > __builtin_dynamic_object_size(), all the compile-time size checks need
> > to check that the bounds variables are, in fact, known at compile-time.
> > Enforce what was guaranteed with __bos(). In other words, since all uses
> > of __bos() were constant expressions, it was not required to test for
> > this. When these change to __bdos(), they _may_ be constant expressions,
> > and the checks are only valid when the prior condition holds. This
> > results in no binary differences.
> >
> > Signed-off-by: Kees Cook <keescook@xxxxxxxxxxxx>
> > ---
> > include/linux/fortify-string.h | 50 +++++++++++++++++++++-------------
> > 1 file changed, 31 insertions(+), 19 deletions(-)
> >
> > diff --git a/include/linux/fortify-string.h b/include/linux/fortify-string.h
> > index ff879efe94ed..71c0a432c638 100644
> > --- a/include/linux/fortify-string.h
> > +++ b/include/linux/fortify-string.h
> > @@ -80,6 +80,12 @@ extern char *__underlying_strncpy(char *p, const char *q, __kernel_size_t size)
> > #define POS __pass_object_size(1)
> > #define POS0 __pass_object_size(0)
> > +#define __compiletime_lessthan(bounds, length) ( \
> > + __builtin_constant_p(length) && \
> > + __builtin_constant_p(bounds) && \
> > + bounds < length \
> > +)
>
> So with the gcc ranger, the compiler has lately been quite successful at
> computing a constant `bounds < length` even though bounds and length are not
> constant. So perhaps this:
>
> #define __compiletime_lessthan (bounds, length) ( \
> __builtin_constant (bounds < length) && \
> bounds < length \
> )
>
> might succeed in a few more cases.

Oh, interesting! That's very cool -- I never considered tossing a full
expression into __bcp. Yeah, that seems to work just fine:
https://godbolt.org/z/xrchErEx1

--
Kees Cook