Skip to content

Allow UnsafeCell content access without get in invalid_reference_casting lint - #159960

Merged
rust-bors[bot] merged 1 commit into
rust-lang:mainfrom
Urgau:invalid_ref-safe-interior-mut
Jul 28, 2026
Merged

Allow UnsafeCell content access without get in invalid_reference_casting lint#159960
rust-bors[bot] merged 1 commit into
rust-lang:mainfrom
Urgau:invalid_ref-safe-interior-mut

Conversation

@Urgau

@Urgau Urgau commented Jul 26, 2026

Copy link
Copy Markdown
Member

#159730 relaxed the rules so that it's no longer necessary to use UnsafeCell::raw_get or UnsafeCell::get to access the content of an unsafe cell.

As a consequence this means that code this like is no longer invalid:

use std::cell::UnsafeCell;

unsafe fn get_mut_unchecked<T>(ptr: &UnsafeCell<T>) -> &mut T {
    let t = ptr as *const UnsafeCell<T> as *mut T;
    unsafe { &mut *t }
}

Fixes #159915
cc @RalfJung

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Jul 26, 2026
@rustbot

rustbot commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator

r? @mejrs

rustbot has assigned @mejrs.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

Why was this reviewer chosen?

The reviewer was selected based on:

  • Owners of files modified in this PR: compiler
  • compiler expanded to 74 candidates
  • Random selection from 15 candidates

Comment on lines +289 to +323
// make sure we don't ICE on it when trying to
// determine if we should lint on it or not.
*((&std::cell::UnsafeCell::new(0)) as *const _ as *mut i32) = 5;

let cell = &std::cell::UnsafeCell::new(0);
let _num = &mut *(cell.get() as *mut i32);
let _num = &mut *(cell as *const _ as *mut i32);

fn safe_as_mut<T>(x: &std::cell::UnsafeCell<T>) -> &mut T {
unsafe fn get_mut_unchecked<T>(x: &std::cell::UnsafeCell<T>) -> &mut T {
unsafe { &mut *std::cell::UnsafeCell::raw_get(x as *const _ as *const _) }
}

fn cell_as_mut(x: &std::cell::Cell<i32>) -> &mut i32 {
unsafe fn get_mut_unchecked2<T>(ptr: &std::cell::UnsafeCell<T>) -> &mut T {
let t = ptr as *const std::cell::UnsafeCell<T> as *mut T;
unsafe { &mut *t }
}

unsafe fn cell_as_mut(x: &std::cell::Cell<i32>) -> &mut i32 {
unsafe { &mut *std::cell::UnsafeCell::raw_get(x as *const _ as *const _) }
}

unsafe fn cell_as_mut2(x: &std::cell::Cell<i32>) -> &mut i32 {
unsafe { &mut *(x as *const std::cell::Cell<i32> as *mut i32) }
}

#[repr(transparent)]
struct DoesContainUnsafeCell(std::cell::UnsafeCell<i32>);
fn safe_as_mut2(x: &DoesContainUnsafeCell) -> &mut DoesContainUnsafeCell {

unsafe fn get_mut_unchecked3(x: &DoesContainUnsafeCell) -> &mut DoesContainUnsafeCell {
unsafe { &mut *std::cell::UnsafeCell::raw_get(x as *const _ as *const _) }
}

unsafe fn get_mut_unchecked4(x: &DoesContainUnsafeCell) -> &mut DoesContainUnsafeCell {
unsafe { &mut *(x as *const DoesContainUnsafeCell as *mut _) }
}

@Urgau Urgau Jul 26, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@RalfJung could you double-check and confirm that all of those casts are now fine.

View changes since the review

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Depends on what you mean by "fine". ;)

They are not immediate UB. But getting a reference into a Cell is still incredibly dangerous. Just as dangerous as Cell::as_ptr though.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, by "fine" I mean no longer immediate UB, it can still be very UB. Thanks for checking.

@RalfJung

Copy link
Copy Markdown
Member

Wow that was fast ❤️

@Urgau
Urgau force-pushed the invalid_ref-safe-interior-mut branch from 714e85a to 3e3ab53 Compare July 26, 2026 11:33
@rustbot

rustbot commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator

This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed.

Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers.

@mejrs

mejrs commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

Are these casts valid? The lint, as implemented here, does not lint on them.

use std::cell::UnsafeCell;
use std::marker::PhantomData;

#[repr(transparent)]
struct MyUnsafeCell<T> {
    data: T,
    _p: PhantomData<UnsafeCell<T>>,
}

unsafe fn cast<T>(ptr: &MyUnsafeCell<T>) -> &mut T {
    let t = ptr as *const MyUnsafeCell<T> as *mut T;
    unsafe { &mut *t }
}

and

unsafe fn cast<T>(ptr: &UnsafeCell<T>) -> &mut UnsafeCell<T> {
    let t = ptr as *const _ as *mut _;
    unsafe { &mut *t }
}

@RalfJung

Copy link
Copy Markdown
Member

Those casts are both dangerous but not immediate UB.

@Morgane55440

Copy link
Copy Markdown

Those casts are both dangerous but not immediate UB.

@RalfJung are you sure ? the first one triggers miri instantaneously.

use std::cell::UnsafeCell;
use std::marker::PhantomData;

#[repr(transparent)]
struct MyUnsafeCell<T> {
    data: T,
    _p: PhantomData<UnsafeCell<T>>,
}

#[allow(invalid_reference_casting)]
unsafe fn cast<T>(ptr: &MyUnsafeCell<T>) -> &mut T {
    let t = ptr as *const MyUnsafeCell<T> as *mut T;
    unsafe { &mut *t }
}

fn main() {
    let mut c : MyUnsafeCell<u8> = MyUnsafeCell { data : 2, _p : PhantomData };
    unsafe {cast(&mut c) };
}
Undefined Behavior: trying to retag from <367> for Unique permission at alloc194[0x0], but that tag only grants SharedReadOnly permission for this location
  --> src/main.rs:19:14
   |
19 |     unsafe { &mut *t }
   |              ^^^^^^^ this error occurs as part of retag at alloc194[0x0..0x1]

@RalfJung

RalfJung commented Jul 27, 2026

Copy link
Copy Markdown
Member

Oh wait I didn't read the example properly. I thought you were asking about what cast does to an unsafe cell, not about a weird custom type. What is that MyUnsafeCell type doing? That indeed makes no sense.

Please always give context for questions like this to make it more likely I look at the right parts of the code. Dumping an uncommented piece of code with weird corner cases without even mentioning the thought process that lead to the example isn't a good way to ask a question. Unfortunately I am often in a rush so I only dig deeper when there's some clear indication where to dig. Sorry for that.

OTOH the lint is not expected to find all UB so not linting on these is not necessarily a problem.

@mejrs

mejrs commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Please always give context for questions like this

My apologies, I was also a bit in a rush myself 😅

Anyway, my mental model of interior mutability is that you always have to go through/pierce/peel/unwrap (what's the precise language for this?) UnsafeCell. Whether that is by using get or casting away the UnsafeCell, you must "peel away" a UnsafeCell wrapper.

But in the second example:

unsafe fn cast<T>(ptr: &UnsafeCell<T>) -> &mut UnsafeCell<T> {
    let t = ptr as *const _ as *mut _;
    unsafe { &mut *t }
}

...we cast the UnsafeCell itself, we don't peel it away Is that also OK?

OTOH the lint is not expected to find all UB so not linting on these is not necessarily a problem.

That's true, it doesn't have to be perfect. However what I see occasionally is:

  • a (often very inexperienced in Rust) programmer will trigger a ub related lint
  • they'll rationalize to themselves that their code is actually ok (this works in C, my program is single threaded, etc)
  • they'll reshape their code without changing the semantics but in a way that the lint no longer understands
  • they move on

It would be nice to make them jump a little bit higher.

@mejrs mejrs left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regardless, the impl looks good to me so no need to block on anything.

@Urgau up to you if you want to make the lint smarter, either here or in a followup

r=me (after nits) if not

View changes since this review

Comment thread compiler/rustc_lint/src/reference_casting.rs Outdated
Comment thread compiler/rustc_lint/src/reference_casting.rs
@RalfJung

RalfJung commented Jul 27, 2026

Copy link
Copy Markdown
Member

Anyway, my mental model of interior mutability is that you always have to go through/pierce/peel/unwrap (what's the precise language for this?) UnsafeCell

That's not quite right. It's more that UnsafeCell "punches a hole" in the immutability requirement of &. So if you have &(i32, Cell<i32>, i32) (if we assume a linear layout) then & enforces immutability of bytes 0..4 and 8..12, but does not enforce anything for bytes 4..8. That's why you can mutate those bytes but not the others. It does not matter if you go "through" an UnsafeCell, you just have to ensure that all of the live shared references pointing to this memory have an UnsafeCell on the bytes you mutate.

That's why the 2nd example is okay.

@Urgau
Urgau force-pushed the invalid_ref-safe-interior-mut branch from 3e3ab53 to 6b0ea30 Compare July 27, 2026 19:23
@Urgau

Urgau commented Jul 27, 2026

Copy link
Copy Markdown
Member Author

@bors r=mejrs

@rust-bors

rust-bors Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

📌 Commit 6b0ea30 has been approved by mejrs

It is now in the queue for this repository.

🌲 The tree is currently closed for pull requests below priority 100. This pull request will be tested once the tree is reopened.

Reason for tree closure: spurious failures

@rust-bors rust-bors Bot added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jul 27, 2026
jhpratt added a commit to jhpratt/rust that referenced this pull request Jul 28, 2026
…t, r=mejrs

Allow `UnsafeCell` content access without `get` in `invalid_reference_casting` lint

rust-lang#159730 relaxed the rules so that it's no longer necessary to use `UnsafeCell::raw_get` or `UnsafeCell::get` to access the content of an unsafe cell.

As a consequence this means that code this like is no longer invalid:
```rust
use std::cell::UnsafeCell;

unsafe fn get_mut_unchecked<T>(ptr: &UnsafeCell<T>) -> &mut T {
    let t = ptr as *const UnsafeCell<T> as *mut T;
    unsafe { &mut *t }
}
```

Fixes rust-lang#159915
cc @RalfJung
rust-bors Bot pushed a commit that referenced this pull request Jul 28, 2026
Rollup of 9 pull requests

Successful merges:

 - #153563 (Lint against iterator functions that panic when `N` is zero )
 - #159960 (Allow `UnsafeCell` content access without `get` in `invalid_reference_casting` lint)
 - #158893 (Clarify preconditions of raw size/align methods)
 - #159220 (Don't optimize across storage markers in SimplifyComparisonIntegral)
 - #159309 (Move tests batch 18)
 - #159450 (Add codegen test for enum clone)
 - #160017 (Make BorrowSet methods public again)
 - #160022 (Refactor rustc_hir re-exports)
 - #160041 (Correct tracking issue for `casefold` feature)
@rust-bors
rust-bors Bot merged commit 1b03eec into rust-lang:main Jul 28, 2026
13 checks passed
@rustbot rustbot added this to the 1.99.0 milestone Jul 28, 2026
rust-timer added a commit that referenced this pull request Jul 28, 2026
Rollup merge of #159960 - Urgau:invalid_ref-safe-interior-mut, r=mejrs

Allow `UnsafeCell` content access without `get` in `invalid_reference_casting` lint

#159730 relaxed the rules so that it's no longer necessary to use `UnsafeCell::raw_get` or `UnsafeCell::get` to access the content of an unsafe cell.

As a consequence this means that code this like is no longer invalid:
```rust
use std::cell::UnsafeCell;

unsafe fn get_mut_unchecked<T>(ptr: &UnsafeCell<T>) -> &mut T {
    let t = ptr as *const UnsafeCell<T> as *mut T;
    unsafe { &mut *t }
}
```

Fixes #159915
cc @RalfJung
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

invalid_reference_casting fires for correct usage of UnsafeCell

5 participants