Skip to content

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

Open
@briansmith

Description

@briansmith

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();

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions