rust-lang / rust-lang/reference
UB inconsistency when derefing a place in a closure
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 1.6k
- Forks
- 607
- PR merge metrics
- PR metrics pending
Description
This was initially reported as a Miri bug: https://github.com/rust-lang/miri/issues/4258
Under Miri, these two uses of **r report inconsistent UB:
use std::mem::transmute;
fn main() {
let r: &&u32 = unsafe {
let x = 42;
transmute(&&x)
};
// no UB detected
let f = || { let _ = **r; };
f();
// UB due to the inner deref
let _ = **r;
}
The closure capture rules consider the whole of **r to be a capture path, and says that "Closures only capture data that needs to be read". Given the rest of that section, it's fair to interpret the usage above as not reading data hence not requiring a capture. This is what the compiler does today.
But in the actual MIR lowering of the second case, we consider that the double-deref does constitute a read of the inner &u32, which triggers UB.
There's a tension here: the read of the inner &u32 doesn't matter in safe code, so I see why closure capture rules would consider that it doesn't matter. But this does introduce a surprising behavior difference. Can we resolve this somehow?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the Rust Reference closure capture rules section linked in the issue, then compare its interpretation of **r with the MIR-lowering behavior and the original Miri issue #4258. Done means reaching and documenting a clear resolution for the inconsistent UB behavior, including any required reference or compiler changes.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 30/100