UB inconsistency when derefing a place in a closure

Open
#2,121 11 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
30/100
Issue type
Bug
Clarity
Needs clarification
Activity status
Stale
Tech stack
rust
Domain
compilers

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.

Description

I-lang-nominated I-lang-radar P-lang-drag-3

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?

Dominant language
Rust
Stars
1.6k
Forks
607
Avg merge
1d 1h
Merged PRs (30d)
12

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.

More from rust-lang/reference

All issues in rust-lang/reference

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.