Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggested lint: avoid passing &mut _ to core::ptr::from_ref #12883

Open
briansmith opened this issue Jun 3, 2024 · 1 comment
Open

Suggested lint: avoid passing &mut _ to core::ptr::from_ref #12883

briansmith opened this issue Jun 3, 2024 · 1 comment
Labels
A-lint Area: New lints

Comments

@briansmith
Copy link

What it does

See #12882 and rust-lang/rust#125897. When r: &mut T, from_ref(r) is equivalent to from_ref(r as &T). Thus, it will no longer be safe to later cast the resultant *const T into a *mut T. Instead, when r: &mut T, the user should use from_mut(r).const_cast() to get a *const T.

Granted, it usually doesn't matter, as we usualy don't cast *const T to *mut T, but when we do, it matters a lot.

Advantage

This is safe:

let p = ptr::from_mut(r).const_cast();
...
let mut_p = p as *mut T;

Whereas this may not be safe:

let p = ptr::from_ref(r);
let mut_p = p as *mut T;

Drawbacks

None that I'm aware of.

Example

Original code:

use core::ptr;

fn main() {
    let mut x = 123u8;
    let r = &mut x;
    let p = ptr::from_ref(r);
    let p_mut = p as *mut T; // Potential UB from this point.
}

Improved code:

-    let p = ptr::from_ref(r);
+    let p = ptr::from_mut(r).const_cast();
@briansmith briansmith added the A-lint Area: New lints label Jun 3, 2024
@briansmith briansmith changed the title Suggested lint: avoid passing '&mut _ to core::ptr::from_ref` Suggested lint: avoid passing &mut _ to core::ptr::from_ref Jun 3, 2024
@lolbinarycat
Copy link

This is safe:

nitpick: the word for well-behaved unsafe code is "sound" (specifically unsafe code that cannot be made to invoke undefined behavior by any safe code is considered "sound")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

No branches or pull requests

2 participants