Skip to content

GVN pass introduces UB by reborrowing from disabled reference #160004

Description

@RalfJung
fn fmt_mutref_string(s: & &mut String) {
    let _str = &**s;
}

fn main() {
    let mut s = String::from("hello");
    let ptr = &mut s as *mut String;

    let a = unsafe { &mut (*ptr) };
    a.push_str(" world");

    fmt_mutref_string(&a);
}

This program is fine according to both TB and SB, but if I run this with Miri with -Zmir-opt-level=1 -Zmir-enable-passes=+GVN, it reports UB in the final line:

error: Undefined Behavior: reborrow through <452> at alloc311[0x0] is forbidden
  --> gvn.rs:2:16
   |
 2 |     let _str = &**s;
   |                ^^^^ Undefined Behavior occurred here
   |
   = help: this indicates a potential bug in the program: it performed an invalid operation, but the Tree Borrows rules it violated are still experimental
   = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/tree-borrows.md for further information
   = help: the accessed tag <452> has state Disabled which forbids this reborrow (acting as a child read access)
help: the accessed tag <452> was created here, in the initial state Reserved
  --> gvn.rs:9:22
   |
 9 |     let a = unsafe { &mut (*ptr) };
   |                      ^^^^^^^^^^^
help: the accessed tag <452> later transitioned to Disabled due to a foreign write access at offsets [0x0..0x8]
  --> gvn.rs:10:5
   |
10 |     a.push_str(" world");
   |     ^^^^^^^^^^^^^^^^^^^^
   = help: this transition corresponds to a loss of read and write permissions
   = note: stack backtrace:
           0: fmt_mutref_string
               at gvn.rs:2:16: 2:20
           1: main
               at gvn.rs:12:5: 12:26

Cc @rust-lang/wg-mir-opt

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-mir-optArea: MIR optimizationsA-mir-opt-GVNArea: MIR opt Global Value Numbering (GVN)C-bugCategory: This is a bug.I-miscompileIssue: Correct Rust code lowers to incorrect machine codeI-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessP-highHigh priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-opsemRelevant to the opsem team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions