Re: [PATCH v5 2/4] slab: Introduce kmalloc_obj() and family

From: Kees Cook
Date: Mon Nov 24 2025 - 16:20:33 EST


On Mon, Nov 24, 2025 at 09:12:14PM +0000, Matthew Wilcox wrote:
> On Mon, Nov 24, 2025 at 12:38:57PM -0800, Kees Cook wrote:
> > For code like:
> >
> > u8 size;
> > ...
> > size = struct_size(ptr, flex_member, count);
> > ptr = kmalloc(size, gfp);
> >
> > While struct_size() is designed to deal with overflows beyond SIZE_MAX,
> > it can't do anything about truncation of its return value since it has
> > no visibility into the lvalue type. So this code pattern happily
> > truncates, allocates too little memory, and then usually does stuff like
> > runs a for-loop based on "count" instead of "size" and walks right off
> > the end of the heap allocation, clobbering whatever follows it.
>
> Have we investigated a compiler warning like
> -Wimplicit-arithmetic-truncation that would complain about this kind of
> thing and could be shut up by an explicit cast:
>
> size = (u8)struct_size(ptr, flex_member, count);
>
> or arithmetic that can be proven to not overflow:
> size = struct_size(ptr, flex_member, count) & 0xff;
>
> Maybe such a warning already exists and it's just too noisy to even
> start thinking about turning it on?

Yes, -Wconversion (W=3) is mind-blowingly noisy, unfortunately.

--
Kees Cook