Re: [PATCH v3 12/13] rust: sync: reduce stack usage of `UniqueArc::try_new_uninit`

From: Benno Lossin
Date: Thu Mar 30 2023 - 11:36:38 EST


On 30.03.23 16:58, David Laight wrote:
> From: y86-dev@xxxxxxxxxxxxxx
>> Sent: 29 March 2023 23:34
>>
>> `UniqueArc::try_new_uninit` calls `Arc::try_new(MaybeUninit::uninit())`.
>> This results in the uninitialized memory being placed on the stack,
>> which may be arbitrarily large due to the generic `T` and thus could
>> cause a stack overflow for large types.
>
> Does that mean rust is using (the equivalent of) alloca() ?

No, the compiler knows the size of `T` statically (this is a requirement
for calling `MaybeUninit::uninit()`). It would simply reserve stack
space for a stack variable (like the C compiler would also do) and since
the type is generic and user-specified, it could be larger than the
stack size. The problem is that the Rust compiler does not optimize the
stack variable away. This fix avoids creating a stack variable in the
first place.

--
Cheers,
Benno


>
> That is banned for C code in the kernel for any sizes.
>
> David
>
> -
> Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK
> Registration No: 1397386 (Wales)