rust-lang / rust-lang/rust-clippy

Suggested lint: avoid passing `&mut _` to `core::ptr::from_ref` and `core::ptr::NonNull::from_ref`

Open
#12,883 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

See #12882 and https://github.com/rust-lang/rust/pull/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();

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the related issue #12882 and pull request #125897, then use the examples here to identify how the suggested lint should distinguish mutable references passed to from_ref and NonNull::from_ref. Done means the lint recommends from_mut(r).const_cast() for the mutable-reference case and avoids the unsafe conversion described in the issue.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.