rust-lang / miri

An interpreter for Rust's mid-level intermediate representation
Apache License 2.0
4.37k stars 337 forks source link

Miri does not complain about use-after-move #3710

Closed kyleguarco closed 3 months ago

kyleguarco commented 3 months ago
$ rustc +nightly --version
rustc 1.81.0-nightly (bcf94dec5 2024-06-23)
$ cargo +nightly miri --version
miri 0.1.0 (bcf94de 2024-06-23)

This unique case of UB was discussed in the Rust Community Discord. Here's a link to the message that started the discussion.


This strip of code causes UB when used on a non-Copy type:

struct Test<T>(*const T);

impl<T> Test<T> {
  fn new(iref: &T) -> Self { Self(iref as *const T) }
}

fn main() {
  let foo = vec![7u8];
  println!("Address of foo: Vec<u8> -> {:p}", &foo);
  let test = Test::new(&foo);
  println!("testref located at {:p}, foo at {:p}", test.0, &foo);
  let bar = foo;
  println!("Moved foo into bar");
  println!("testref located at {:p}, bar at {:p}", test.0, &bar);
  println!("Contents of foo using testref -> {:?}", unsafe { &*test.0 });
}
$ cargo +nightly miri run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s
     Running `/home/kyleg/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/bin/cargo-miri runner target/miri/x86_64-unknown-linux-gnu/debug/tmiri`
Address of foo: Vec<u8> -> 0x25b68
testref located at 0x25b68, foo at 0x25b68
Moved foo into bar
testref located at 0x25b68, bar at 0x41b68
Contents of foo using testref -> [7]

miri does not complain about dereferencing a moved pointer (moving foo to bar) despite test still holding reference &foo.

Might be related to (or a duplicate of) rust-lang/unsafe-code-guidelines#188?

RalfJung commented 3 months ago

This is behaving as intended. There are two ways this could be UB, https://github.com/rust-lang/unsafe-code-guidelines/issues/188 and by foo reaching the end of its lifetime. However, current MIR generation makes foo live until the end of its scope. This is not a guarantee, this program might become UB in future rustc versions, and then Miri will detect it as such.

But for now, there's no bug here.