Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UB in safe code with raw pointer receivers #2786

Closed
RalfJung opened this issue Feb 13, 2023 · 1 comment · Fixed by rust-lang/rust#109568
Closed

UB in safe code with raw pointer receivers #2786

RalfJung opened this issue Feb 13, 2023 · 1 comment · Fixed by rust-lang/rust#109568

Comments

@RalfJung
Copy link
Member

This code reports UB:

#![feature(arbitrary_self_types)]
use std::ptr;

trait Foo {
    fn foo(self: *const Self) -> &'static str;
}

impl Foo for i32 {
    fn foo(self: *const Self) -> &'static str {
        "I'm an i32!"
    }
}

impl Foo for u32 {
    fn foo(self: *const Self) -> &'static str {
        "I'm a u32!"
    }
}

fn main() {
    let null_i32 = ptr::null::<i32>() as *const dyn Foo;
    let null_u32 = ptr::null::<u32>() as *const dyn Foo;

    assert_eq!("I'm an i32!", null_i32.foo());
    assert_eq!("I'm a u32!", null_u32.foo());
}
error: Undefined Behavior: dereferencing pointer failed: null pointer is a dangling pointer (it has no provenance)
  --> src/main.rs:24:31
   |
24 |     assert_eq!("I'm an i32!", null_i32.foo());
   |                               ^^^^^^^^^^^^^^ dereferencing pointer failed: null pointer is a dangling pointer (it has no provenance)
   |
   = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
   = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
   = note: BACKTRACE:
   = note: inside `main` at src/main.rs:24:31: 24:45

Given that this is all safe code, definitely something is wrong here. I am not sure why there is a pointer deref, this might have to do with internals of dyn receiver handling.

@RalfJung
Copy link
Member Author

It's this deref_operand here which creates a place that currently implicitly comes with the requirement of being dereferenceable:

https://github.com/rust-lang/rust/blob/adb4bfd25d3c1190b0e7433ef945221d8aeea427/compiler/rustc_const_eval/src/interpret/terminator.rs#L543

oli-obk pushed a commit to oli-obk/miri that referenced this issue Apr 4, 2023
miri: fix raw pointer dyn receivers

r? `@oli-obk`
Fixes rust-lang#2786
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant