Skip to content

Miri complains about undefined behavior when using index_mut instead of square brackets to access disjoined array elements #2906

@jplatte

Description

@jplatte

This code:

use std::ops::IndexMut as _;

fn main() {
    let mut array = [0, 1];
    {
        let a = unsafe { &mut *((&mut array[0]) as *mut i32) };
        let b = unsafe { &mut *((&mut array[1]) as *mut i32) };
        std::mem::swap(a, b);
    }

    {
        let a = unsafe { &mut *(array.index_mut(0) as *mut i32) };
        let b = unsafe { &mut *(array.index_mut(1) as *mut i32) };
        std::mem::swap(a, b);
    }
}

has Miri report an invalid retag at the second std::mem::swap even though the first and second code block look like they should be equivalent at least semantically. Error message:

error: Undefined Behavior: trying to retag from <2686> for SharedReadWrite permission at alloc1403[0x0], but that tag does not exist in the borrow stack for this location
  --> src/main.rs:14:24
   |
14 |         std::mem::swap(a, b);
   |                        ^
   |                        |
   |                        trying to retag from <2686> for SharedReadWrite permission at alloc1403[0x0], but that tag does not exist in the borrow stack for this location
   |                        this error occurs as part of two-phase retag at alloc1403[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: <2686> was created by a Unique retag at offsets [0x0..0x4]
  --> src/main.rs:12:26
   |
12 |         let a = unsafe { &mut *(array.index_mut(0) as *mut i32) };
   |                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: <2686> was later invalidated at offsets [0x0..0x8] by a Unique function-entry retag inside this call
  --> src/main.rs:13:33
   |
13 |         let b = unsafe { &mut *(array.index_mut(1) as *mut i32) };
   |                                 ^^^^^^^^^^^^^^^^^^
   = note: BACKTRACE (of the first span):
   = note: inside `main` at src/main.rs:14:24: 14:25

Is this a Miri bug, or somehow intentional?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions