Skip to content

Commit a5a3c95

Browse files
fbqojeda
authored andcommitted
rust: macros: provide correct provenance when constructing THIS_MODULE
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. Reported-by: Alice Ryhl <[email protected]> Signed-off-by: Boqun Feng <[email protected]> Reviewed-by: Alice Ryhl <[email protected]> Reviewed-by: Trevor Gross <[email protected]> Reviewed-by: Benno Lossin <[email protected]> Reviewed-by: Gary Guo <[email protected]> Closes: https://rust-for-linux.zulipchat.com/#narrow/stream/x/topic/x/near/465412664 Fixes: 1fbde52 ("rust: add `macros` crate") Cc: [email protected] # 6.6.x: be2ca1e: ("rust: types: Make Opaque::get const") Link: https://lore.kernel.org/r/[email protected] [ Fixed two typos, reworded title. - Miguel ] Signed-off-by: Miguel Ojeda <[email protected]>
1 parent 8e95e53 commit a5a3c95

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

rust/macros/module.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,11 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
217217
// freed until the module is unloaded.
218218
#[cfg(MODULE)]
219219
static THIS_MODULE: kernel::ThisModule = unsafe {{
220-
kernel::ThisModule::from_ptr(&kernel::bindings::__this_module as *const _ as *mut _)
220+
extern \"C\" {{
221+
static __this_module: kernel::types::Opaque<kernel::bindings::module>;
222+
}}
223+
224+
kernel::ThisModule::from_ptr(__this_module.get())
221225
}};
222226
#[cfg(not(MODULE))]
223227
static THIS_MODULE: kernel::ThisModule = unsafe {{

0 commit comments

Comments
 (0)