Re: [PATCH] rust: check type of `$ptr` in `container_of!`
From: Benno Lossin
Date: Sat Apr 12 2025 - 05:43:48 EST
On Fri Apr 11, 2025 at 11:39 PM CEST, Tamir Duberstein wrote:
> On Fri, Apr 11, 2025 at 5:12 PM Benno Lossin <benno.lossin@xxxxxxxxx> wrote:
>>
>> On Fri Apr 11, 2025 at 5:41 PM CEST, Tamir Duberstein wrote:
>> > On Fri, Apr 11, 2025 at 10:36 AM Alice Ryhl <aliceryhl@xxxxxxxxxx> wrote:
>> >>
>> >> On Fri, Apr 11, 2025 at 4:31 PM Tamir Duberstein <tamird@xxxxxxxxx> wrote:
>> >> >
>> >> > Add a compile-time check that `*$ptr` is of the type of `$type->$($f)*`.
>> >> >
>> >> > Suggested-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>
>> >> > Link: https://lore.kernel.org/all/CAH5fLgh6gmqGBhPMi2SKn7mCmMWfOSiS0WP5wBuGPYh9ZTAiww@xxxxxxxxxxxxxx/
>> >> > Signed-off-by: Tamir Duberstein <tamird@xxxxxxxxx>
>> >> > ---
>> >> > rust/kernel/lib.rs | 5 ++++-
>> >> > 1 file changed, 4 insertions(+), 1 deletion(-)
>> >> >
>> >> > diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
>> >> > index 1df11156302a..da9e36aa7967 100644
>> >> > --- a/rust/kernel/lib.rs
>> >> > +++ b/rust/kernel/lib.rs
>> >> > @@ -200,7 +200,10 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
>> >> > macro_rules! container_of {
>> >> > ($ptr:expr, $type:ty, $($f:tt)*) => {{
>> >> > let offset: usize = ::core::mem::offset_of!($type, $($f)*);
>> >> > - $ptr.byte_sub(offset).cast::<$type>()
>> >> > + let container = $ptr.byte_sub(offset).cast::<$type>();
>> >> > + fn assert_same_type<T>(_: T, _: T) {}
>> >> > + assert_same_type($ptr, ::core::mem::addr_of!((*container).$($f)*).cast_mut());
>> >
>> > I noticed I accidentally sent `::core::mem::addr_of` instead of
>> > `::core::ptr::addr_of`; will fix once we agree below.
>> >
>> >> Perhaps it would be better to wrap the type check in an `if false` to
>> >> avoid evaluating the expressions at runtime?
>> >
>> > It's optimized out at O1: https://godbolt.org/z/44Go5xnWr. Is it worth it?
>>
>> Wrapping in `if false` definitely doesn't hurt, since we get better
>> debug perf.
>
> How's this?
>
> if false { [$ptr, ::core::ptr::addr_of!((*container).$($f)*).cast_mut()]; }
How does the error look like if you use the wrong input pointer? I'd
prefer we use the variant that creates the best error report for the
user. I could imagine that the function gives a better error, but I
haven't checked.
---
Cheers,
Benno