Re: [PATCH v2] rust: check type of `$ptr` in `container_of!`
From: Tamir Duberstein
Date: Sat Apr 12 2025 - 14:20:25 EST
On Sat, Apr 12, 2025 at 2:16 PM Tamir Duberstein <tamird@xxxxxxxxx> wrote:
>
> [...]
>
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index 1df11156302a..6fbd4cc5afff 100644
> --- a/rust/kernel/lib.rs
> +++ b/rust/kernel/lib.rs
> @@ -198,9 +198,14 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
> /// ```
> #[macro_export]
> 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>()
> + ($field_ptr:expr, $Container:ty, $($fields:tt)*) => {{
> + let offset: usize = ::core::mem::offset_of!($Container, $($fields)*);
> + let container_ptr = $field_ptr.byte_sub(offset).cast::<$Container>();
> + if false {
> + let field_ptr = ::core::ptr::addr_of!((*container_ptr).$($fields)*).cast_mut();
> + [$field_ptr, field_ptr]; // typeof(`$ptr_to_field`) == typeof(`$Container.$($fields)*`)
The comment here should be s/ptr_to_field/field_ptr/. I missed this
when renaming this placeholder for clarity.
> + }
> + container_ptr
> }}
> }