From 31c3c0449807d22a0f10e7a290a8e4ed114b98d4 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 20 May 2022 17:16:41 +0200 Subject: [PATCH] make ptr::invalid not the same as a regular int2ptr cast --- library/core/src/ptr/mod.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index ba8b0670147ae..dc229c9ff9b44 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -555,7 +555,11 @@ pub const fn null_mut() -> *mut T { #[unstable(feature = "strict_provenance", issue = "95228")] pub const fn invalid(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. @@ -582,7 +586,11 @@ pub const fn invalid(addr: usize) -> *const T { #[unstable(feature = "strict_provenance", issue = "95228")] pub const fn invalid_mut(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.