Re: [+externe Mail+] RE: [PATCH] compiler.h: Explain how __is_constexpr() works

From: Uecker, Martin
Date: Fri Mar 01 2024 - 08:24:16 EST



BTW my main email addess is now: uecker@xxxxxxxxx

My suggestion would also to limit explanation. Nobody should
write such code and if you need to, you can find explanations
all over the internet.

Finally, I still think the motivation for this macro (removing
VLAs) is misguided if security is the goal because VLAs provide
precise bounds and larger worst-case fixed-size arrays do not.  

It would be better to use the compiler options that detect
possibly use of VLAs of unbounded size and if there a problems
with this, improve this on the compiler side.

Martin


Am Freitag, dem 01.03.2024 um 09:32 +0000 schrieb David Laight:
> From: Kees Cook
> > Sent: 01 March 2024 04:45
> > To: Rasmus Villemoes <linux@xxxxxxxxxxxxxxxxxx>
> >
> > The __is_constexpr() macro is dark magic. Shed some light on it with
> > a comment to explain how and why it works.
>
> All the 8s don't help...
>
> I don't think you need that much explanation.
>
> Perhaps just saying that the type of ?: depends on the types
> of the values and is independent of the condition.
> The type of (0 ? (void *)p : (foo *)q) is normally 'void *'
> (so that both values can be assigned to it).
> But if 'p' is 'an integer constant expression with value 0'
> then (void *)p is NULL and the type is 'foo *'.
>
> The type can then be checked to find out it 'p' is constant 0.
> A non-zero constant 'p' can be multiples by 0.
>
> I need to replace the definition with (the more portable):
> #define __if_constexpr(cond, if_const, if_not_const) \
> _Generic(0 ? (void *)((long)(cond) * 0) : (char *)0, \
> char *: (if_const), \
> void *: (if_not_const))
> which is arguably less cryptic.
>
> #define __is_constexpr(cond) __if_constexpr(cond, 1, 0)
>
> So that I can write:
> #define is_non_neg_const(x) (__if_constexpr(x, x , -1) >= 0)
> and avoid the compiler bleating about some comparisons
> in unreachable code.
>
> David
>
> -
> Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK
> Registration No: 1397386 (Wales)
>