Skip to content

Commit

Permalink
Rollup merge of #97219 - RalfJung:ptr-invalid, r=thomcc
Browse files Browse the repository at this point in the history
make ptr::invalid not the same as a regular int2ptr cast

In Miri, we would like to distinguish `ptr::invalid` from `ptr::from_exposed_provenance`, so that we can provide better diagnostics issues like rust-lang/miri#2134, and so that we can detect the UB in programs like
```rust
fn main() {
    let x = 0u8;
    let original_ptr = &x as *const u8;
    let addr = original_ptr.expose_addr();
    let new_ptr: *const u8 = core::ptr::invalid(addr);
    unsafe {
        dbg!(*new_ptr);
    }
}
```

To achieve that, the two functions need to have different implementations. Currently, both are just `as` casts. We *could* add an intrinsic for this, but it turns out `transmute` already has the right behavior, at least as far as Miri is concerned. So I propose we just use that.

Cc `@Gankra`
  • Loading branch information
GuillaumeGomez committed May 21, 2022
2 parents e5c7b21 + 31c3c04 commit 6fef5f1
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions library/core/src/ptr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,11 @@ pub const fn null_mut<T>() -> *mut T {
#[unstable(feature = "strict_provenance", issue = "95228")]
pub const fn invalid<T>(addr: usize) -> *const T {
// FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
addr as *const T
// We use transmute rather than a cast so tools like Miri can tell that this
// is *not* the same as from_exposed_addr.
// SAFETY: every valid integer is also a valid pointer (as long as you don't dereference that
// pointer).
unsafe { mem::transmute(addr) }
}

/// Creates an invalid mutable pointer with the given address.
Expand All @@ -582,7 +586,11 @@ pub const fn invalid<T>(addr: usize) -> *const T {
#[unstable(feature = "strict_provenance", issue = "95228")]
pub const fn invalid_mut<T>(addr: usize) -> *mut T {
// FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
addr as *mut T
// We use transmute rather than a cast so tools like Miri can tell that this
// is *not* the same as from_exposed_addr.
// SAFETY: every valid integer is also a valid pointer (as long as you don't dereference that
// pointer).
unsafe { mem::transmute(addr) }
}

/// Convert an address back to a pointer, picking up a previously 'exposed' provenance.
Expand Down

0 comments on commit 6fef5f1

Please sign in to comment.