Auto merge of #97710 - RalfJung:ptr-addr, r=thomcc
implement ptr.addr() via transmute As per the discussion in https://github.com/rust-lang/unsafe-code-guidelines/issues/286, the semantics for ptr-to-int transmutes that we are going with for now is to make them strip provenance without exposing it. That's exactly what `ptr.addr()` does! So we can implement `ptr.addr()` via `transmute`. This also means that once https://github.com/rust-lang/rust/pull/97684 lands, Miri can distinguish `ptr.addr()` from `ptr.expose_addr()`, and the following code will correctly be called out as having UB (if permissive provenance mode is enabled, which will become the default once the [implementation is complete](https://github.com/rust-lang/miri/issues/2133)): ```rust fn main() { let x: i32 = 3; let x_ptr = &x as *const i32; let x_usize: usize = x_ptr.addr(); // Cast back an address that did *not* get exposed. let ptr = std::ptr::from_exposed_addr::<i32>(x_usize); assert_eq!(unsafe { *ptr }, 3); //~ ERROR Undefined Behavior: dereferencing pointer failed } ``` This completes the Miri implementation of the new distinctions introduced by strict provenance. :) Cc `@Gankra` -- for now I left in your `FIXME(strict_provenance_magic)` saying these should be intrinsics, but I do not necessarily agree that they should be. Or if we have an intrinsic, I think it should behave exactly like the `transmute` does, which makes one wonder why the intrinsic should be needed.
This commit is contained in:
commit
760237ff78
2 changed files with 6 additions and 2 deletions
|
@ -180,7 +180,9 @@ impl<T: ?Sized> *const T {
|
|||
T: Sized,
|
||||
{
|
||||
// FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
|
||||
self as usize
|
||||
// SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
|
||||
// provenance).
|
||||
unsafe { mem::transmute(self) }
|
||||
}
|
||||
|
||||
/// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future
|
||||
|
|
|
@ -184,7 +184,9 @@ impl<T: ?Sized> *mut T {
|
|||
T: Sized,
|
||||
{
|
||||
// FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
|
||||
self as usize
|
||||
// SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
|
||||
// provenance).
|
||||
unsafe { mem::transmute(self) }
|
||||
}
|
||||
|
||||
/// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future
|
||||
|
|
Loading…
Add table
Reference in a new issue