[<prev] [next>] [thread-next>] [day] [month] [year] [list]
Message-Id: <20250411-b4-container-of-type-check-v1-1-08262ef67c95@gmail.com>
Date: Fri, 11 Apr 2025 10:31:31 -0400
From: Tamir Duberstein <tamird@...il.com>
To: Miguel Ojeda <ojeda@...nel.org>, Alex Gaynor <alex.gaynor@...il.com>,
Boqun Feng <boqun.feng@...il.com>, Gary Guo <gary@...yguo.net>,
Björn Roy Baron <bjorn3_gh@...tonmail.com>,
Benno Lossin <benno.lossin@...ton.me>,
Andreas Hindborg <a.hindborg@...nel.org>, Alice Ryhl <aliceryhl@...gle.com>,
Trevor Gross <tmgross@...ch.edu>, Danilo Krummrich <dakr@...nel.org>
Cc: rust-for-linux@...r.kernel.org, linux-kernel@...r.kernel.org,
Tamir Duberstein <tamird@...il.com>
Subject: [PATCH] rust: check type of `$ptr` in `container_of!`
Add a compile-time check that `*$ptr` is of the type of `$type->$($f)*`.
Suggested-by: Alice Ryhl <aliceryhl@...gle.com>
Link: https://lore.kernel.org/all/CAH5fLgh6gmqGBhPMi2SKn7mCmMWfOSiS0WP5wBuGPYh9ZTAiww@mail.gmail.com/
Signed-off-by: Tamir Duberstein <tamird@...il.com>
---
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());
+ container
}}
}
---
base-commit: 0af2f6be1b4281385b618cb86ad946eded089ac8
change-id: 20250411-b4-container-of-type-check-06af1c204f59
prerequisite-change-id: 20250409-container-of-mutness-b153dab4388d:v1
prerequisite-patch-id: 53d5889db599267f87642bb0ae3063c29bc24863
Best regards,
--
Tamir Duberstein <tamird@...il.com>
Powered by blists - more mailing lists