Skip to content

Commit 66ebed2

Browse files
committed
Auto merge of #97710 - RalfJung:ptr-addr, r=thomcc
implement ptr.addr() via transmute As per the discussion in rust-lang/unsafe-code-guidelines#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 rust-lang/rust#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](rust-lang/miri#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.
2 parents 9b5ebba + f607195 commit 66ebed2

File tree

2 files changed

+6
-2
lines changed

2 files changed

+6
-2
lines changed

core/src/ptr/const_ptr.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,9 @@ impl<T: ?Sized> *const T {
180180
T: Sized,
181181
{
182182
// FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
183-
self as usize
183+
// SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
184+
// provenance).
185+
unsafe { mem::transmute(self) }
184186
}
185187

186188
/// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future

core/src/ptr/mut_ptr.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,9 @@ impl<T: ?Sized> *mut T {
184184
T: Sized,
185185
{
186186
// FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
187-
self as usize
187+
// SAFETY: Pointer-to-integer transmutes are valid (if you are okay with losing the
188+
// provenance).
189+
unsafe { mem::transmute(self) }
188190
}
189191

190192
/// Gets the "address" portion of the pointer, and 'exposes' the "provenance" part for future

0 commit comments

Comments
 (0)