Re: [PATCH v2] rust: check type of `$ptr` in `container_of!`
From: Benno Lossin
Date: Mon Apr 14 2025 - 08:17:32 EST
On Sat Apr 12, 2025 at 8:16 PM CEST, Tamir Duberstein wrote:
> Add a compile-time check that `*$ptr` is of the type of `$type->$($f)*`.
>
> Given the incorrect usage:
>
> ; diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs
> ; index 8d978c896747..6a7089149878 100644
> ; --- a/rust/kernel/rbtree.rs
> ; +++ b/rust/kernel/rbtree.rs
> ; @@ -329,7 +329,7 @@ fn raw_entry(&mut self, key: &K) -> RawEntry<'_, K, V> {
> ; while !(*child_field_of_parent).is_null() {
> ; let curr = *child_field_of_parent;
> ; // SAFETY: All links fields we create are in a `Node<K, V>`.
> ; - let node = unsafe { container_of!(curr, Node<K, V>, links) };
> ; + let node = unsafe { container_of!(curr, Node<K, V>, key) };
> ;
> ; // SAFETY: `node` is a non-null node so it is valid by the type invariants.
> ; match key.cmp(unsafe { &(*node).key }) {
>
> this patch produces the compilation error:
>
> ; error[E0308]: mismatched types
> ; --> rust/kernel/lib.rs:206:26
> ; |
> ; 206 | [$field_ptr, field_ptr]; // typeof(`$ptr_to_field`) == typeof(`$Container.$($fields)*`)
> ; | ^^^^^^^^^ expected `*mut rb_node`, found `*mut K`
> ; |
> ; ::: rust/kernel/rbtree.rs:270:6
> ; |
> ; 270 | impl<K, V> RBTree<K, V>
> ; | - found this type parameter
> ; ...
> ; 332 | let node = unsafe { container_of!(curr, Node<K, V>, key) };
> ; | ------------------------------------ in this macro invocation
> ; |
> ; = note: expected raw pointer `*mut bindings::rb_node`
> ; found raw pointer `*mut K`
> ; = note: this error originates in the macro `container_of` (in Nightly builds, run with -Z macro-backtrace for more info)
> ;
> ; error: aborting due to 1 previous error
>
> Suggested-by: Alice Ryhl <aliceryhl@xxxxxxxxxx>
> Link: https://lore.kernel.org/all/CAH5fLgh6gmqGBhPMi2SKn7mCmMWfOSiS0WP5wBuGPYh9ZTAiww@xxxxxxxxxxxxxx/
> Signed-off-by: Tamir Duberstein <tamird@xxxxxxxxx>
Reviewed-by: Benno Lossin <benno.lossin@xxxxxxxxx>
> ---
> I also considered an implementation using a function, but the resulting
> compilation error was not as concise:
Thanks for checking :)
---
Cheers,
Benno