mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH] rust: check type of `$ptr` in `container_of!`
@ 2025-04-11 14:31 Tamir Duberstein
  2025-04-11 14:36 ` Alice Ryhl
  2025-05-29 13:28 ` Miguel Ojeda
  0 siblings, 2 replies; 7+ messages in thread
From: Tamir Duberstein @ 2025-04-11 14:31 UTC (permalink / raw)
  To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich
  Cc: rust-for-linux, linux-kernel, Tamir Duberstein

Add a compile-time check that `*$ptr` is of the type of `$type->$($f)*`.

Suggested-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/all/CAH5fLgh6gmqGBhPMi2SKn7mCmMWfOSiS0WP5wBuGPYh9ZTAiww@mail.gmail.com/
Signed-off-by: Tamir Duberstein <tamird@gmail.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@gmail.com>


^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2025-05-29 13:28 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2025-04-11 14:31 [PATCH] rust: check type of `$ptr` in `container_of!` Tamir Duberstein
2025-04-11 14:36 ` Alice Ryhl
2025-04-11 15:41   ` Tamir Duberstein
2025-04-11 21:11     ` Benno Lossin
2025-04-11 21:39       ` Tamir Duberstein
2025-04-12  9:43         ` Benno Lossin
2025-05-29 13:28 ` Miguel Ojeda

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®