Skip to content

Conversation

@RalfJung
Copy link
Member

@RalfJung RalfJung commented Nov 9, 2025

Reference PR:

This check rejects code that is not necessarily UB, e.g. a mutable ref to a static mut that is very carefully used correctly. That led to us having to describe it in the Reference, which uncovered just how ad-hoc this check is (rust-lang/reference#2074).

Even without this check, we still reject things like

const C: &mut i32 = &mut 0;

This is rejected by const checking -- the part of the frontend that looks at the source code and says whether it is allowed in const context. In the Reference, this restriction is explained here.

So, the check during validation is just a safety net. And it is already a safety net with gaping holes since we only check &mut T, not &UnsafeCell<T>, due to the fact that we promote some immutable values that have !Freeze type so &!Freeze actually can occur in the final value of a const.

So... it may be time for me to acknowledge that the "mutable ref in final value of const" check is a cure that's worth than the disease. Nobody asked for that check, I just added it because I was worried about soundness issues when we allow mutable references in constants. Originally it was much stricter, but I had to slowly relax it to its current form to prevent t from firing on code we intend to allow. In the end there are only 3 tests left that trigger this error, and they are all just constants containing references to mutable statics -- not the safest code in the world, but also not so bad that we have to spend a lot of time devising a core language limitation and associated Reference wording to prevent it from ever happening.

So... @rust-lang/wg-const-eval @rust-lang/lang I propose that we allow code like this

static mut S: i32 = 3;
const C2: &'static mut i32 = unsafe { &mut * &raw mut S };

@theemathas would be great if you could try to poke a hole into this. ;)

@rustbot
Copy link
Collaborator

rustbot commented Nov 9, 2025

Some changes occurred to the CTFE machinery

cc @RalfJung, @oli-obk, @lcnr

Some changes occurred to the CTFE / Miri interpreter

cc @rust-lang/miri, @RalfJung, @oli-obk, @lcnr

Some changes occurred to the CTFE / Miri interpreter

cc @rust-lang/miri

@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 Nov 9, 2025
@rustbot
Copy link
Collaborator

rustbot commented Nov 9, 2025

r? @davidtwco

rustbot has assigned @davidtwco.
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

@theemathas
Copy link
Contributor

theemathas commented Nov 9, 2025

In the end there are only 3 tests left that trigger this error, and they are all just constants containing references to mutable statics

All code that this PR newly allows involves &mut pointing to statics, right?

@theemathas
Copy link
Contributor

With this PR, Miri detects no UB in this code. Is this intended?

use std::ptr;
static mut X: i32 = 1;
const Y: &mut i32 = unsafe { &mut *&raw mut X };
fn main() {
    let a = &Y;
    let b = &Y;
    println!("{a}");
    println!("{b}");
    unsafe {
        *ptr::from_ref(a).read() = 2;
        *ptr::from_ref(b).read() = 3;
        *ptr::from_ref(a).read() = 4;
        *ptr::from_ref(b).read() = 5;
    }
}

@theemathas
Copy link
Contributor

However, Miri detects UB in the following code:

use std::ptr;
static mut X: i32 = 1;
const Y: &mut i32 = unsafe { &mut *&raw mut X };
fn main() {
    let a = &std::convert::identity(Y);
    let b = &Y;
    unsafe {
        *ptr::from_ref(b).read() = 3;
        *ptr::from_ref(a).read() = 4;
    }
}
error: Undefined Behavior: trying to retag from <287> for Unique permission at alloc1[0x0], but that tag does not exist in the borrow stack for this location       
  --> src\main.rs:10:10
   |
10 |         *ptr::from_ref(a).read() = 4;
   |          ^^^^^^^^^^^^^^^^^^^^^^^ this error occurs as part of retag at alloc1[0x0..0x4]
   |
   = help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental       
   = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information
help: <287> was created by a Unique retag at offsets [0x0..0x4]
  --> src\main.rs:5:14
   |
 5 |     let a = &std::convert::identity(Y);
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^
help: <287> was later invalidated at offsets [0x0..0x4] by a Unique retag
  --> src\main.rs:9:10
   |
 9 |         *ptr::from_ref(b).read() = 3;
   |          ^^^^^^^^^^^^^^^^^^^^^^^

note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace

@RalfJung
Copy link
Member Author

RalfJung commented Nov 9, 2025

All code that this PR newly allows involves &mut pointing to statics, right?

That should be the case, yes. The only other thing an &mut could point to is a temporary, and then either that gets lifetime extended and we should reject it during const checking, or it does not get lifetime extended and then this becomes a dangling reference that we detect.

With this PR, Miri detects no UB in this code. Is this intended?

We can't run the aliasing model when evaluating constants, so all pointers coming from constants are "equivalent" to Miri. These &Y get promoted so the values of a and b come from constants and Miri can't tell them apart.

The 2nd example passes Y around by-value, which leads to it being retagged, and then Miri's aliasing checks kick in.

@theemathas
Copy link
Contributor

theemathas commented Nov 9, 2025

all pointers coming from constants are "equivalent" to Miri

Even if those are two aliasing &mut references being stored at different addresses?

@RalfJung
Copy link
Member Author

RalfJung commented Nov 9, 2025

If the address they are stored at is "global" memory (i.e. the memory backing a const or static), then yes. All pointers stored in global memory are considered to be "root" pointers for the aliasing model in Miri.

@theemathas
Copy link
Contributor

I couldn't find any other unusual behavior with this PR.

(I tried to use a const containing a &mut in a pattern, but for &mut pointing to 1 or more bytes of memory, rust won't let me use that pattern, due to the const referencing mutable memory.)

@traviscross traviscross added I-lang-nominated Nominated for discussion during a lang team meeting. P-lang-drag-1 Lang team prioritization drag level 1. https://rust-lang.zulipchat.com/#narrow/channel/410516-t-lang T-lang Relevant to the language team and removed T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Nov 10, 2025
@traviscross
Copy link
Contributor

Sounds right to me. Always good when we can delete hairy text from the Reference.

@rfcbot fcp merge

@traviscross

This comment was marked as duplicate.

@traviscross traviscross added S-waiting-on-documentation Status: Waiting on approved PRs to documentation before merging needs-fcp This change is insta-stable, or significant enough to need a team FCP to proceed. labels Nov 10, 2025
@traviscross

This comment was marked as duplicate.

@Mark-Simulacrum

This comment was marked as duplicate.

1 similar comment
@traviscross

This comment was marked as duplicate.

@traviscross
Copy link
Contributor

@rfcbot fcp merge

@rust-rfcbot
Copy link
Collaborator

rust-rfcbot commented Nov 11, 2025

Team member @traviscross has proposed to merge this. The next step is review by the rest of the tagged team members:

No concerns currently listed.

Once a majority of reviewers approve (and at most 2 approvals are outstanding), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up!

cc @rust-lang/lang-advisors: FCP proposed for lang, please feel free to register concerns.
See this document for info about what commands tagged team members can give me.

@rust-rfcbot rust-rfcbot added proposed-final-comment-period Proposed to merge/close by relevant subteam, see T-<team> label. Will enter FCP once signed off. disposition-merge This issue / PR is in PFCP or FCP with a disposition to merge it. labels Nov 11, 2025
Copy link
Member

@davidtwco davidtwco left a comment

Choose a reason for hiding this comment

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

Implementation LGTM, r=me once t-lang FCP finishes

View changes since this review

@nikomatsakis
Copy link
Contributor

@rfcbot reviewed

@rust-rfcbot rust-rfcbot added final-comment-period In the final comment period and will be merged soon unless new substantive objections are raised. and removed proposed-final-comment-period Proposed to merge/close by relevant subteam, see T-<team> label. Will enter FCP once signed off. labels Nov 19, 2025
@rust-rfcbot
Copy link
Collaborator

🔔 This is now entering its final comment period, as per the review above. 🔔

@tmandry
Copy link
Member

tmandry commented Nov 19, 2025

@rfcbot reviewed

@traviscross traviscross added I-lang-radar Items that are on lang's radar and will need eventual work or consideration. and removed I-lang-nominated Nominated for discussion during a lang team meeting. P-lang-drag-1 Lang team prioritization drag level 1. https://rust-lang.zulipchat.com/#narrow/channel/410516-t-lang labels Nov 20, 2025
@rust-rfcbot rust-rfcbot added finished-final-comment-period The final comment period is finished for this PR / Issue. to-announce Announce this issue on triage meeting and removed final-comment-period In the final comment period and will be merged soon unless new substantive objections are raised. labels Nov 29, 2025
@rust-rfcbot
Copy link
Collaborator

The final comment period, with a disposition to merge, as per the review above, is now complete.

As the automated representative of the governance process, I would like to thank the author for their work and everyone else who contributed.

@RalfJung
Copy link
Member Author

@bors r=davidtwco

@bors
Copy link
Collaborator

bors commented Nov 29, 2025

📌 Commit 3d7c9bd has been approved by davidtwco

It is now in the queue for this repository.

@bors bors 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 Nov 29, 2025
bors added a commit that referenced this pull request Nov 29, 2025
Rollup of 3 pull requests

Successful merges:

 - #148746 (const validation: remove check for mutable refs in final value of const)
 - #148765 (std: split up the `thread` module)
 - #149454 (resolve: Identifier resolution refactorings)

r? `@ghost`
`@rustbot` modify labels: rollup
@bors bors merged commit 8e4c70f into rust-lang:main Nov 29, 2025
11 checks passed
@rustbot rustbot added this to the 1.93.0 milestone Nov 29, 2025
rust-timer added a commit that referenced this pull request Nov 29, 2025
Rollup merge of #148746 - RalfJung:mutable-ref-in-const, r=davidtwco

const validation: remove check for mutable refs in final value of const

This check rejects code that is not necessarily UB, e.g. a mutable ref to a `static mut` that is very carefully used correctly. That led to us having to describe it in the Reference, which uncovered just how ad-hoc this check is (rust-lang/reference#2074).

Even without this check, we still reject things like
```rust
const C: &mut i32 = &mut 0;
```
This is rejected by const checking -- the part of the frontend that looks at the source code and says whether it is allowed in const context. In the Reference, this restriction is explained [here](https://doc.rust-lang.org/nightly/reference/const_eval.html#r-const-eval.const-expr.borrows).

So, the check during validation is just a safety net. And it is already a safety net with gaping holes since we only check `&mut T`, not `&UnsafeCell<T>`, due to the fact that we promote some immutable values that have `!Freeze` type so `&!Freeze` actually can occur in the final value of a const.

So... it may be time for me to acknowledge that the "mutable ref in final value of const" check is a cure that's worth than the disease. Nobody asked for that check, I just added it because I was worried about soundness issues when we allow mutable references in constants. Originally it was much stricter, but I had to slowly relax it to its current form to prevent t from firing on code we intend to allow. In the end there are only 3 tests left that trigger this error, and they are all just constants containing references to mutable statics -- not the safest code in the world, but also not so bad that we have to spend a lot of time devising a core language limitation and associated Reference wording to prevent it from ever happening.

So... `@rust-lang/wg-const-eval` `@rust-lang/lang`  I propose that we allow code like this
```rust
static mut S: i32 = 3;
const C2: &'static mut i32 = unsafe { &mut * &raw mut S };
```
`@theemathas` would be great if you could try to poke a hole into this. ;)
@traviscross traviscross removed the S-waiting-on-documentation Status: Waiting on approved PRs to documentation before merging label Nov 30, 2025
github-actions bot pushed a commit to rust-lang/miri that referenced this pull request Nov 30, 2025
Rollup of 3 pull requests

Successful merges:

 - rust-lang/rust#148746 (const validation: remove check for mutable refs in final value of const)
 - rust-lang/rust#148765 (std: split up the `thread` module)
 - rust-lang/rust#149454 (resolve: Identifier resolution refactorings)

r? `@ghost`
`@rustbot` modify labels: rollup
@RalfJung RalfJung deleted the mutable-ref-in-const branch November 30, 2025 09:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

disposition-merge This issue / PR is in PFCP or FCP with a disposition to merge it. finished-final-comment-period The final comment period is finished for this PR / Issue. I-lang-radar Items that are on lang's radar and will need eventual work or consideration. needs-fcp This change is insta-stable, or significant enough to need a team FCP to proceed. S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-lang Relevant to the language team to-announce Announce this issue on triage meeting

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants