[<prev] [next>] [<thread-prev] [day] [month] [year] [list]
Message-ID: <01aa8bd408d04031941073b026f171fb@AcuMS.aculab.com>
Date: Wed, 11 Sep 2024 10:22:44 +0000
From: David Laight <David.Laight@...LAB.COM>
To: 'Vincent Mailhol' <mailhol.vincent@...adoo.fr>, Kees Cook
<kees@...nel.org>
CC: "Gustavo A . R . Silva" <gustavoars@...nel.org>,
"linux-hardening@...r.kernel.org" <linux-hardening@...r.kernel.org>,
"linux-kernel@...r.kernel.org" <linux-kernel@...r.kernel.org>
Subject: RE: [PATCH v2] overflow: optimize struct_size() calculation
From: Vincent Mailhol
> Sent: 10 September 2024 03:50
>
> If the offsetof() of a given flexible array member (fam) is smaller
> than the sizeof() of the containing struct, then the struct_size()
> macro reports a size which is too big.
>
> This occurs when the two conditions below are met:
>
> - there are padding bytes after the penultimate member (the member
> preceding the fam)
> - the alignment of the fam is less than or equal to the penultimate
> member's alignment
>
> In that case, the fam overlaps with the padding bytes of the
> penultimate member. This behaviour is not captured in the current
> struct_size() macro, potentially resulting in an overestimated size.
...
> Change struct_size() from this pseudo code logic:
>
> sizeof(struct s) + sizeof(*s.fam) * s.count
>
> to that pseudo code logic:
>
> max(sizeof(struct s), offsetof(struct s, fam) + sizeof(*s.fam) * s.count)
You are adding a third comparison [1] to every call - even though most don't
need it and the memory saving is marginal at best.
The total code size increase could easily exceed any savings.
With care you only do the max() when sizeof(struct) != offsetof() but I doubt
the complexity is worth it.
[1] Both the '+' and '*' have extra code to detect overflow and return
a 'big' value that will cause kmalloc() to return NULL.
I've not looked at the generated code but it is likely to be horrid
(especially the check for multiply overflowing).
In this case there are enough constants that the alternative check:
if (count > (MAX_SIZE - sizeof (*s)) / sizeof (s->member))
size = MAX_SIZE;
else
size = sizeof (*s) + count * sizeof (s->member);
is fine and only has one conditional in it.
In some cases the compiler may already know that the count is small enough.
David
-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK
Registration No: 1397386 (Wales)
Powered by blists - more mailing lists