rust: macros: provide correct provenance when constructing THIS_MODULE
Subsystems (2)
PATCH 1/1 rust: macros: provide correct provenance when constructing THIS_MODULE
commit a5a3c952e82c1ada12bf8c55b73af26f1a454bd2 upstream.
Currently while defining THIS_MODULE symbol in module!(), the pointer used to construct ThisModule is derived from an immutable reference of __this_module, which means the pointer doesn't have the provenance for writing, and that means any write to that pointer is UB regardless of data races or not. However, the usage of THIS_MODULE includes passing this pointer to functions that may write to it (probably in unsafe code), and this will create soundness issues.
One way to fix this is using addr_of_mut!() but that requires the unstable feature "const_mut_refs". So instead of addr_of_mut()!, an extern static Opaque is used here: since Opaque<T> is transparent to T, an extern static Opaque will just wrap the C symbol (defined in a C compile unit) in an Opaque, which provides a pointer with writable provenance via Opaque::get(). This fix the potential UBs because of pointer provenance unmatched.
[ Boqun: Use UnsafeCell since Opaque is not in v6.1, as suggested by
Gary Guo, UnsafeCell also suffices for this particular case because __this_module is only used to create THIS_MODULE, no other Rust code will touch it. ]
---
Backports for 6.6+ are already done automatically, we have to do a special backport for 6.1 because of lacking an API.
I've tested it on x86 with the rust_minimal module based on 6.1.112
rust/macros/module.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
rust/macros/module.rs +5 -1
@@ -183,7 +183,11 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {// freed until the module is unloaded. #[cfg( MODULE )] static THIS_MODULE : kernel::ThisModule =unsafe {{ - kernel::ThisModule ::from_ptr (&kernel::bindings::__this_moduleas *const _ as *mut _ ) + extern \"C\" {{ +static __this_module: core::cell::UnsafeCell <kernel::bindings::module >; + }} + + kernel::ThisModule ::from_ptr (__this_module.get ()) }};#[cfg(not( MODULE ))] static THIS_MODULE : kernel::ThisModule =unsafe {{
Signature · 1 line
2.45.2