rust: Add `container_of` and `offset_of` macros
PATCH 1/1 rust: Add `container_of` and `offset_of` macros
From: Asahi Lina <[email protected]>
Add Rust counterparts to these C macros. container_of is useful for C struct subtyping, to recover the original pointer to the container structure. offset_of is useful for struct-relative addressing.
Co-authored:by: Léo Lanteri Thauvin <[email protected]>
---
Hi,
container_of is a essential macro to build any sort of driver in the Linux Kernel. Therefore, we need a good and reliable implementation of this macro for the Rust abstractions.
Although I checked the version sent by Matt [1], I don't really like the fact that such an essential part of the foundation of any driver would be an unsafe macro. Therefore, I propose this alternative to Matt's implementation, which is Lina's implementation that it is actually safe.
container_of is a dependency for the rustgem driver and this is part of my current efforts to upstream the driver.
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
Best Regards,
- Maíra
rust/kernel/lib.rs | 69 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+)
rust/kernel/lib.rs +69 -0
@@ -103,3 +103,72 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! {// SAFETY: FFI call. unsafe { bindings::BUG () }; } + +/// Calculates the offset of a field from the beginning of the struct it belongs to. +/// +/// # Examples +/// +/// ```rust +/// use kernel::prelude::*; +/// use kernel::offset_of; +/// struct Test { +/// a: u64, +/// b: u32, +/// } +/// +/// assert_eq!(offset_of!(Test, b), 8); +/// ``` +#[macro_export] +macro_rules! offset_of { + ($type:ty, $($f:tt)*) => {{ +let tmp = core::mem::MaybeUninit ::<$type>::uninit (); +let outer = tmp.as_ptr (); +// To avoid warnings when nesting `unsafe` blocks. +#[allow(unused_unsafe)] +// SAFETY: The pointer is valid and aligned, just not initialised; `addr_of` ensures that +// we don't actually read from `outer` (which would be UB) nor create an intermediate +// reference. +let inner =unsafe { core::ptr::addr_of!((*outer).$($f)*) }as *const u8 ; +// To avoid warnings when nesting `unsafe` blocks. +#[allow(unused_unsafe)] +// SAFETY: The two pointers are within the same allocation block. +unsafe { inner.offset_from (outeras *const u8 ) } + }} +} + +/// Produces a pointer to an object from a pointer to one of its fields. +/// +/// # Safety +/// +/// Callers must ensure that the pointer to the field is in fact a pointer to the specified field, +/// as opposed to a pointer to another object of the same type. If this condition is not met, +/// any dereference of the resulting pointer is UB. +/// +/// # Examples +/// +/// ```rust +/// use kernel::container_of; +/// struct Test { +/// a: u64, +/// b: u32, +/// } +/// +/// let test = Test { a: 10, b: 20 }; +/// let b_ptr = &test.b; +/// let test_alias = container_of!(b_ptr, Test, b); +/// assert!(core::ptr::eq(&test, test_alias)); +/// ``` +#[macro_export] +macro_rules! container_of { + ($ptr:expr, $type:ty, $($f:tt)*) => {{ +let ptr = $ptras *const _ as *const u8 ; +let offset = $crate::offset_of!($type , $($f)*); +let outer = ptr.wrapping_offset (-offset)as *const $type; +// SAFETY: The pointer is valid and aligned, just not initialised; `addr_of` ensures that +// we don't actually read from `outer` (which would be UB) nor create an intermediate +// reference. The two pointers are within the same allocation block. +let inner =unsafe { core::ptr::addr_of!((*outer).$($f)*) }; +build_assert! (inner == $ptr); + outer + }} +}
--
2.43.0
Quoted 6 lines · Maíra Canal
From: Asahi Lina <[email protected]>
Add Rust counterparts to these C macros.
container_ofis useful for C struct subtyping, to recover the original pointer to the container structure.offset_ofis useful for struct-relative addressing.
Quoted 8 lines
Co-authored-by Miguel Ojeda <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>Co-authored:by: Léo Lanteri Thauvin <[email protected]>
Signed-off-by Léo Lanteri Thauvin <[email protected]>Co-authored-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Asahi Lina <[email protected]>Signed-off-by Maíra Canal <[email protected]>
A handful of authors? So then, it would be sensible to list their contributions to the patch, though, it could be done when merged.
Quoted 4 lines
[...]
rust/kernel/lib.rs +3
-0+/// Calculates the offset of a field from the beginning of the struct it belongs to. +/// +/// # Examples
rust/kernel/lib.rs fn panic(info: &core::panic::PanicInfo<'_>) -> ! { · line 119
Quoted 10 lines
rust/kernel/lib.rs +10
-0+/// +/// ```rust +/// use kernel::prelude::*; +/// use kernel::offset_of; +/// struct Test { +/// a: u64, +/// b: u32, +/// } +/// +/// assert_eq!(offset_of!(Test, b), 8);
Would've added a check for field a, but that's my personal preference.
rust/kernel/lib.rs fn panic(info: &core::panic::PanicInfo<'_>) -> ! { · line 131
Quoted 12 lines
rust/kernel/lib.rs +12
-0+/// ``` +#[macro_export] +macro_rules! offset_of { + ($type:ty, $($f:tt)*) => {{ +let tmp = core::mem::MaybeUninit ::<$type>::uninit (); +let outer = tmp.as_ptr (); +// To avoid warnings when nesting `unsafe` blocks. +#[allow(unused_unsafe)] +// SAFETY: The pointer is valid and aligned, just not initialised; `addr_of` ensures that +// we don't actually read from `outer` (which would be UB) nor create an intermediate +// reference. +let inner =unsafe { core::ptr::addr_of!((*outer).$($f)*) }as *const u8 ;
Curiously enough, you can get the offset of a member of a field struct per what addr_of! does, i.e. if we have a type Foo that contains a struct field Bar which has member qux, then offset_of!(Foo, bar.qux) will give out an offset too. I don't know if this applies for container_of!. Just saying.
Quoted 1 line
[...]
Alice Ryhl
reviewerQuoted 19 lines · Maíra Canal
From: Asahi Lina <[email protected]>
Add Rust counterparts to these C macros.
container_ofis useful for C struct subtyping, to recover the original pointer to the container structure.offset_ofis useful for struct-relative addressing.Co-authored-by Miguel Ojeda <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>Co-authored:by: Léo Lanteri Thauvin <[email protected]>
Signed-off-by Léo Lanteri Thauvin <[email protected]>Co-authored-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Asahi Lina <[email protected]>Signed-off-by Maíra Canal <[email protected]>---
Hi,
Quoted 8 lines
container_ofis a essential macro to build any sort of driver in the Linux Kernel. Therefore, we need a good and reliable implementation of this macro for the Rust abstractions.Although I checked the version sent by Matt [1], I don't really like the fact that such an essential part of the foundation of any driver would be an unsafe macro. Therefore, I propose this alternative to Matt's implementation, which is Lina's implementation that it is actually safe.
Well, the addr_of macro in the standard library, which performs the opposite operation is also unsafe. So I don't think that having it be unsafe is that unreasonable.
Quoted 41 lines
container_ofis a dependency for the rustgem driver and this is part of my current efforts to upstream the driver.[1] https://lore.kernel.org/rust-for-linux/[email protected]/
Best Regards,
- Maírarust/kernel/lib.rs | 69 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+)rust/kernel/lib.rs +22
-0@@ -103,3 +103,72 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! {// SAFETY: FFI call. unsafe { bindings::BUG () }; } + +/// Calculates the offset of a field from the beginning of the struct it belongs to. +/// +/// # Examples +/// +/// ```rust +/// use kernel::prelude::*; +/// use kernel::offset_of; +/// struct Test { +/// a: u64, +/// b: u32, +/// } +/// +/// assert_eq!(offset_of!(Test, b), 8); +/// ``` +#[macro_export] +macro_rules! offset_of { + ($type:ty, $($f:tt)*) => {{ +let tmp = core::mem::MaybeUninit ::<$type>::uninit (); +let outer = tmp.as_ptr (); +// To avoid warnings when nesting `unsafe` blocks. +#[allow(unused_unsafe)]
rust/kernel/lib.rs fn panic(info: &core::panic::PanicInfo<'_>) -> ! { · line 137
Quoted 10 lines
rust/kernel/lib.rs +10
-0+// SAFETY: The pointer is valid and aligned, just not initialised; `addr_of` ensures that +// we don't actually read from `outer` (which would be UB) nor create an intermediate +// reference. +let inner =unsafe { core::ptr::addr_of!((*outer).$($f)*) }as *const u8 ; +// To avoid warnings when nesting `unsafe` blocks. +#[allow(unused_unsafe)] +// SAFETY: The two pointers are within the same allocation block. +unsafe { inner.offset_from (outeras *const u8 ) } + }} +}
The offset_of macro is already available through the standard library. You do not need to add it here.
Quoted 22 lines
rust/kernel/lib.rs +22
-0+/// Produces a pointer to an object from a pointer to one of its fields. +/// +/// # Safety +/// +/// Callers must ensure that the pointer to the field is in fact a pointer to the specified field, +/// as opposed to a pointer to another object of the same type. If this condition is not met, +/// any dereference of the resulting pointer is UB. +/// +/// # Examples +/// +/// ```rust +/// use kernel::container_of; +/// struct Test { +/// a: u64, +/// b: u32, +/// } +/// +/// let test = Test { a: 10, b: 20 }; +/// let b_ptr = &test.b; +/// let test_alias = container_of!(b_ptr, Test, b); +/// assert!(core::ptr::eq(&test, test_alias)); +/// ```
rust/kernel/lib.rs fn panic(info: &core::panic::PanicInfo<'_>) -> ! { · line 170
Quoted 10 lines
rust/kernel/lib.rs +10
-0+#[macro_export] +macro_rules! container_of { + ($ptr:expr, $type:ty, $($f:tt)*) => {{ +let ptr = $ptras *const _ as *const u8 ; +let offset = $crate::offset_of!($type , $($f)*); +let outer = ptr.wrapping_offset (-offset)as *const $type; +// SAFETY: The pointer is valid and aligned, just not initialised; `addr_of` ensures that +// we don't actually read from `outer` (which would be UB) nor create an intermediate +// reference. The two pointers are within the same allocation block. +let inner =unsafe { core::ptr::addr_of!((*outer).$($f)*) };
If your macro is not unsafe, then this line is incorrect. I could call container_of! with some random dangling pointer, and then it would use addr_of! on that pointer, which is not okay because addr_of assumes that the pointer is in-bounds of an allocation both before and after the offset operation.
Alice
Hi Alice,
Quoted 118 lines · Alice Ryhl
Quoted 19 lines · Maíra Canal
From: Asahi Lina <[email protected]>
Add Rust counterparts to these C macros.
container_ofis useful for C struct subtyping, to recover the original pointer to the container structure.offset_ofis useful for struct-relative addressing.Co-authored-by Miguel Ojeda <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>Co-authored:by: Léo Lanteri Thauvin <[email protected]>
Signed-off-by Léo Lanteri Thauvin <[email protected]>Co-authored-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Asahi Lina <[email protected]>Signed-off-by Maíra Canal <[email protected]>---
Hi,
Quoted 8 lines
container_ofis a essential macro to build any sort of driver in the Linux Kernel. Therefore, we need a good and reliable implementation of this macro for the Rust abstractions.Although I checked the version sent by Matt [1], I don't really like the fact that such an essential part of the foundation of any driver would be an unsafe macro. Therefore, I propose this alternative to Matt's implementation, which is Lina's implementation that it is actually safe.
Well, the
addr_ofmacro in the standard library, which performs the opposite operation is also unsafe. So I don't think that having it be unsafe is that unreasonable.Quoted 41 lines
container_ofis a dependency for the rustgem driver and this is part of my current efforts to upstream the driver.[1] https://lore.kernel.org/rust-for-linux/[email protected]/
Best Regards,
- Maírarust/kernel/lib.rs | 69 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+)rust/kernel/lib.rs +22
-0@@ -103,3 +103,72 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! {// SAFETY: FFI call. unsafe { bindings::BUG () }; } + +/// Calculates the offset of a field from the beginning of the struct it belongs to. +/// +/// # Examples +/// +/// ```rust +/// use kernel::prelude::*; +/// use kernel::offset_of; +/// struct Test { +/// a: u64, +/// b: u32, +/// } +/// +/// assert_eq!(offset_of!(Test, b), 8); +/// ``` +#[macro_export] +macro_rules! offset_of { + ($type:ty, $($f:tt)*) => {{ +let tmp = core::mem::MaybeUninit ::<$type>::uninit (); +let outer = tmp.as_ptr (); +// To avoid warnings when nesting `unsafe` blocks. +#[allow(unused_unsafe)] rust/kernel/lib.rs fn panic(info: &core::panic::PanicInfo<'_>) -> ! { · line 137
Quoted 10 lines
rust/kernel/lib.rs +10
-0+// SAFETY: The pointer is valid and aligned, just not initialised; `addr_of` ensures that +// we don't actually read from `outer` (which would be UB) nor create an intermediate +// reference. +let inner =unsafe { core::ptr::addr_of!((*outer).$($f)*) }as *const u8 ; +// To avoid warnings when nesting `unsafe` blocks. +#[allow(unused_unsafe)] +// SAFETY: The two pointers are within the same allocation block. +unsafe { inner.offset_from (outeras *const u8 ) } + }} +}The
offset_ofmacro is already available through the standard library. You do not need to add it here.Quoted 30 lines
rust/kernel/lib.rs +30
-0+/// Produces a pointer to an object from a pointer to one of its fields. +/// +/// # Safety +/// +/// Callers must ensure that the pointer to the field is in fact a pointer to the specified field, +/// as opposed to a pointer to another object of the same type. If this condition is not met, +/// any dereference of the resulting pointer is UB. +/// +/// # Examples +/// +/// ```rust +/// use kernel::container_of; +/// struct Test { +/// a: u64, +/// b: u32, +/// } +/// +/// let test = Test { a: 10, b: 20 }; +/// let b_ptr = &test.b; +/// let test_alias = container_of!(b_ptr, Test, b); +/// assert!(core::ptr::eq(&test, test_alias)); +/// ``` +#[macro_export] +macro_rules! container_of { + ($ptr:expr, $type:ty, $($f:tt)*) => {{ +let ptr = $ptras *const _ as *const u8 ; +let offset = $crate::offset_of!($type , $($f)*); +let outer = ptr.wrapping_offset (-offset)as *const $type; +// SAFETY: The pointer is valid and aligned, just not initialised; `addr_of` ensures that +// we don't actually read from `outer` (which would be UB) nor create an intermediate
Quoted 9 lines
rust/kernel/lib.rs fn panic(info: &core::panic::PanicInfo<'_>) -> ! { · line 170
Quoted 2 lines
rust/kernel/lib.rs +2
-0+// reference. The two pointers are within the same allocation block. +let inner =unsafe { core::ptr::addr_of!((*outer).$($f)*) };If your macro is not unsafe, then this line is incorrect. I could call
container_of!with some random dangling pointer, and then it would useaddr_of! on that pointer, which is not okay becauseaddr_ofassumes that the pointer is in-bounds of an allocation both before and after the offset operation.
Thanks for your explanation, I haven't thought through this point of
view. Anyway, any chance we could land the container_of! patch as soon
as possible? It would be nice to have a common understanding of this fundamental macro. I would like to send some patches with the DMA fences abstraction, but I would need container_of!.
Best Regards,
- Maíra
Quoted 1 line
Alice
Quoted 142 lines · Maíra Canal
Hi Alice,
Quoted 129 lines · Alice Ryhl
Quoted 19 lines · Maíra Canal
From: Asahi Lina <[email protected]>
Add Rust counterparts to these C macros.
container_ofis useful for C struct subtyping, to recover the original pointer to the container structure.offset_ofis useful for struct-relative addressing.Co-authored-by Miguel Ojeda <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>Co-authored:by: Léo Lanteri Thauvin <[email protected]>
Signed-off-by Léo Lanteri Thauvin <[email protected]>Co-authored-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Asahi Lina <[email protected]>Signed-off-by Maíra Canal <[email protected]>---
Hi,
Quoted 8 lines
container_ofis a essential macro to build any sort of driver in the Linux Kernel. Therefore, we need a good and reliable implementation of this macro for the Rust abstractions.Although I checked the version sent by Matt [1], I don't really like the fact that such an essential part of the foundation of any driver would be an unsafe macro. Therefore, I propose this alternative to Matt's implementation, which is Lina's implementation that it is actually safe.
Well, the
addr_ofmacro in the standard library, which performs the opposite operation is also unsafe. So I don't think that having it be unsafe is that unreasonable.Quoted 48 lines
container_ofis a dependency for the rustgem driver and this is part of my current efforts to upstream the driver.[1] https://lore.kernel.org/rust-for-linux/[email protected]/
Best Regards,
- Maíra
rust/kernel/lib.rs| 69 ++++++++++++++++++++++++++++++++++++++++++++++1 file changed, 69 insertions(+)rust/kernel/lib.rs +2
-0@@ -103,3 +103,72 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! { // SAFETY: FFI call. unsafe { bindings::BUG() }; } + +/// Calculates the offset of a field from the beginning of the struct it belongs to.
rust/kernel/lib.rs +21
-0+/// +/// # Examples +/// +/// ```rust +/// use kernel::prelude::*; +/// use kernel::offset_of; +/// struct Test { +/// a: u64, +/// b: u32, +/// } +/// +/// assert_eq!(offset_of!(Test, b), 8); +/// ``` +#[macro_export] +macro_rules! offset_of { + ($type:ty, $($f:tt)*) => {{ + let tmp = core::mem::MaybeUninit::<$type>::uninit(); + let outer = tmp.as_ptr(); + // To avoid warnings when nesting `unsafe` blocks. + #[allow(unused_unsafe)] + // SAFETY: The pointer is valid and aligned, just notinitialised;
addr_ofensures that
+ // we don't actually read fromouter(which would be UB) nor create an intermediate
+ // reference.
+ let inner = unsafe { core::ptr::addr_of!((*outer).$($f)*) }Quoted 8 lines
as *const u8;
+ // To avoid warnings when nestingunsafeblocks. + #[allow(unused_unsafe)]
+ // SAFETY: The two pointers are within the same allocation block.
+ unsafe {inner.offset_from(outer as *const u8)} + }}
+}The
offset_ofmacro is already available through the standard library. You do not need to add it here.Quoted 36 lines
+/// Produces a pointer to an object from a pointer to one of its fields.
rust/kernel/lib.rs +4
-0+/// +/// # Safety +/// +/// Callers must ensure that the pointer to the field is in fact a pointer to the specified field,
+/// as opposed to a pointer to another object of the same type. If this condition is not met,rust/kernel/lib.rs +23
-0+/// any dereference of the resulting pointer is UB. +/// +/// # Examples +/// +/// ```rust +/// use kernel::container_of; +/// struct Test { +/// a: u64, +/// b: u32, +/// } +/// +/// let test = Test { a: 10, b: 20 }; +/// let b_ptr = &test.b; +/// let test_alias = container_of!(b_ptr, Test, b); +/// assert!(core::ptr::eq(&test, test_alias)); +/// ``` +#[macro_export] +macro_rules! container_of { + ($ptr:expr, $type:ty, $($f:tt)*) => {{ + let ptr = $ptr as *const _ as *const u8; + let offset = $crate::offset_of!($type, $($f)*); + let outer = ptr.wrapping_offset(-offset) as *const $type; + // SAFETY: The pointer is valid and aligned, just notinitialised;
addr_ofensures that
+ // we don't actually read fromouter(which would be UB) nor create an intermediate
+ // reference. The two pointers are within the sameQuoted 9 lines
Quoted 2 lines
allocation block.
+ let inner = unsafe { core::ptr::addr_of!((*outer).$($f)*) };If your macro is not unsafe, then this line is incorrect. I could call
container_of!with some random dangling pointer, and then it would useaddr_of! on that pointer, which is not okay becauseaddr_ofassumes that the pointer is in-bounds of an allocation both before and after the offset operation.
Quoted 4 lines
Thanks for your explanation, I haven't thought through this point of
view. Anyway, any chance we could land thecontainer_of!patch as soon
as possible? It would be nice to have a common understanding of this fundamental macro. I would like to send some patches with the DMA fences abstraction, but I would needcontainer_of!.
When you send a patchset, you can just state in the coverletter that it depends on the container_of patch in the rbtree patchset. Then Miguel will know that he needs to take that before he can take your patchset.
Of course, if Miguel can take it soon, that's even better.
Alice
Quoted 6 lines · Maíra Canal
Thanks for your explanation, I haven't thought through this point of view. Anyway, any chance we could land the
container_of!patch as soon as possible? It would be nice to have a common understanding of this fundamental macro. I would like to send some patches with the DMA fences abstraction, but I would needcontainer_of!.
Would you be OK with their version? If so, I could take that one; and if not, we can discuss what to do.
But, in any case, as Alice mentioned, please feel free to send your series even before that. It is anyway a very small dependency that will soon go in.
Cheers,
Miguel
Hi Miguel,
Quoted 10 lines · Miguel Ojeda
Quoted 6 lines · Maíra Canal
Thanks for your explanation, I haven't thought through this point of view. Anyway, any chance we could land the
container_of!patch as soon as possible? It would be nice to have a common understanding of this fundamental macro. I would like to send some patches with the DMA fences abstraction, but I would needcontainer_of!.Would you be OK with their version? If so, I could take that one; and if not, we can discuss what to do.
Considering Alice's points, I'm OK with their version.
Best Regards,
- Maíra
Quoted 7 lines
But, in any case, as Alice mentioned, please feel free to send your series even before that. It is anyway a very small dependency that will soon go in.
Cheers,
Miguel
Quoted 2 lines · Maíra Canal
Considering Alice's points, I'm OK with their version.
Thanks! Their version is in rust-next now.
Cheers,
Miguel
Hi Maira,
Quoted 22 lines · Maíra Canal
From: Asahi Lina <[email protected]>
Add Rust counterparts to these C macros.
container_ofis useful for C struct subtyping, to recover the original pointer to the container structure.offset_ofis useful for struct-relative addressing.Co-authored-by Miguel Ojeda <[email protected]>Signed-off-by Miguel Ojeda <[email protected]>Co-authored:by: Léo Lanteri Thauvin <[email protected]>
Signed-off-by Léo Lanteri Thauvin <[email protected]>Co-authored-by Wedson Almeida Filho <[email protected]>Signed-off-by Wedson Almeida Filho <[email protected]>Signed-off-by Asahi Lina <[email protected]>Signed-off-by Maíra Canal <[email protected]>---
Hi,
container_ofis a essential macro to build any sort of driver in the Linux Kernel. Therefore, we need a good and reliable implementation of this macro for the Rust abstractions.
Quoted 8 lines
Although I checked the version sent by Matt [1], I don't really like the fact that such an essential part of the foundation of any driver would be an unsafe macro. Therefore, I propose this alternative to Matt's implementation, which is Lina's implementation that it is actually safe.
container_ofis a dependency for the rustgem driver and this is part of my current efforts to upstream the driver.
offset_of!() is available as core::mem::offset_of!() under unstable feature gate, which is currently enabled and used in the workqueue abstractions. So at least that macro is not required.
Best regards,
Andreas