Skip to content

Commit d8a6409

Browse files
committed
Auto merge of #135344 - scottmcm:safe-dangling, r=joboet
Less unsafe in `dangling`/`without_provenance` This PR was inspired by the new `NonNull::without_provenance` (cc #135243 (comment)) since it made me realize that we could write `NonNull::dangling` in completely-safe code using other existing things. Then doing that led me to a few more places that could be simplified, like now that GVN will optimize Transmute-then-PtrToPtr, we can just implement `ptr::without_provenance` by calling `ptr::without_provenance_mut` since the shipped rlib of `core` ends up with the same single statement as the implementation (thanks to GVN merging the steps) and thus there's no need to duplicate the `transmute` -- and more importantly, no need to repeat a long safety comment. There did end up being a couple of other changes needed to avoid exploding certain bits of MIR, though -- like `<Box<[i32]>>::default()`'s MIR originally got way worse as certain things didn't inline, or had a bunch of extraneous UbChecks -- so there's a couple of other changes to solve that.
2 parents d61f55d + c18718c commit d8a6409

18 files changed

+272
-457
lines changed

library/core/src/ptr/alignment.rs

+9-3
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,10 @@ impl Alignment {
4242
/// but in an `Alignment` instead of a `usize`.
4343
#[unstable(feature = "ptr_alignment_type", issue = "102070")]
4444
#[inline]
45+
#[must_use]
4546
pub const fn of<T>() -> Self {
46-
// SAFETY: rustc ensures that type alignment is always a power of two.
47-
unsafe { Alignment::new_unchecked(mem::align_of::<T>()) }
47+
// This can't actually panic since type alignment is always a power of two.
48+
const { Alignment::new(mem::align_of::<T>()).unwrap() }
4849
}
4950

5051
/// Creates an `Alignment` from a `usize`, or returns `None` if it's
@@ -95,8 +96,13 @@ impl Alignment {
9596
#[unstable(feature = "ptr_alignment_type", issue = "102070")]
9697
#[inline]
9798
pub const fn as_nonzero(self) -> NonZero<usize> {
99+
// This transmutes directly to avoid the UbCheck in `NonZero::new_unchecked`
100+
// since there's no way for the user to trip that check anyway -- the
101+
// validity invariant of the type would have to have been broken earlier --
102+
// and emitting it in an otherwise simple method is bad for compile time.
103+
98104
// SAFETY: All the discriminants are non-zero.
99-
unsafe { NonZero::new_unchecked(self.as_usize()) }
105+
unsafe { mem::transmute::<Alignment, NonZero<usize>>(self) }
100106
}
101107

102108
/// Returns the base-2 logarithm of the alignment.

library/core/src/ptr/mod.rs

+3-8
Original file line numberDiff line numberDiff line change
@@ -596,12 +596,7 @@ pub const fn null_mut<T: ?Sized + Thin>() -> *mut T {
596596
#[stable(feature = "strict_provenance", since = "1.84.0")]
597597
#[rustc_const_stable(feature = "strict_provenance", since = "1.84.0")]
598598
pub const fn without_provenance<T>(addr: usize) -> *const T {
599-
// An int-to-pointer transmute currently has exactly the intended semantics: it creates a
600-
// pointer without provenance. Note that this is *not* a stable guarantee about transmute
601-
// semantics, it relies on sysroot crates having special status.
602-
// SAFETY: every valid integer is also a valid pointer (as long as you don't dereference that
603-
// pointer).
604-
unsafe { mem::transmute(addr) }
599+
without_provenance_mut(addr)
605600
}
606601

607602
/// Creates a new pointer that is dangling, but non-null and well-aligned.
@@ -618,7 +613,7 @@ pub const fn without_provenance<T>(addr: usize) -> *const T {
618613
#[stable(feature = "strict_provenance", since = "1.84.0")]
619614
#[rustc_const_stable(feature = "strict_provenance", since = "1.84.0")]
620615
pub const fn dangling<T>() -> *const T {
621-
without_provenance(mem::align_of::<T>())
616+
dangling_mut()
622617
}
623618

624619
/// Creates a pointer with the given address and no [provenance][crate::ptr#provenance].
@@ -661,7 +656,7 @@ pub const fn without_provenance_mut<T>(addr: usize) -> *mut T {
661656
#[stable(feature = "strict_provenance", since = "1.84.0")]
662657
#[rustc_const_stable(feature = "strict_provenance", since = "1.84.0")]
663658
pub const fn dangling_mut<T>() -> *mut T {
664-
without_provenance_mut(mem::align_of::<T>())
659+
NonNull::dangling().as_ptr()
665660
}
666661

667662
/// Converts an address back to a pointer, picking up some previously 'exposed'

library/core/src/ptr/non_null.rs

+7-9
Original file line numberDiff line numberDiff line change
@@ -91,12 +91,12 @@ impl<T: Sized> NonNull<T> {
9191
///
9292
/// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
9393
#[unstable(feature = "nonnull_provenance", issue = "135243")]
94+
#[must_use]
95+
#[inline]
9496
pub const fn without_provenance(addr: NonZero<usize>) -> Self {
97+
let pointer = crate::ptr::without_provenance(addr.get());
9598
// SAFETY: we know `addr` is non-zero.
96-
unsafe {
97-
let ptr = crate::ptr::without_provenance_mut(addr.get());
98-
NonNull::new_unchecked(ptr)
99-
}
99+
unsafe { NonNull { pointer } }
100100
}
101101

102102
/// Creates a new `NonNull` that is dangling, but well-aligned.
@@ -123,11 +123,8 @@ impl<T: Sized> NonNull<T> {
123123
#[must_use]
124124
#[inline]
125125
pub const fn dangling() -> Self {
126-
// SAFETY: ptr::dangling_mut() returns a non-null well-aligned pointer.
127-
unsafe {
128-
let ptr = crate::ptr::dangling_mut::<T>();
129-
NonNull::new_unchecked(ptr)
130-
}
126+
let align = crate::ptr::Alignment::of::<T>();
127+
NonNull::without_provenance(align.as_nonzero())
131128
}
132129

133130
/// Converts an address back to a mutable pointer, picking up some previously 'exposed'
@@ -137,6 +134,7 @@ impl<T: Sized> NonNull<T> {
137134
///
138135
/// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
139136
#[unstable(feature = "nonnull_provenance", issue = "135243")]
137+
#[inline]
140138
pub fn with_exposed_provenance(addr: NonZero<usize>) -> Self {
141139
// SAFETY: we know `addr` is non-zero.
142140
unsafe {

tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.32bit.panic-abort.diff

+19-44
Original file line numberDiff line numberDiff line change
@@ -16,25 +16,23 @@
1616
scope 4 (inlined Unique::<[bool; 0]>::dangling) {
1717
let mut _5: std::ptr::NonNull<[bool; 0]>;
1818
scope 5 (inlined NonNull::<[bool; 0]>::dangling) {
19-
let _6: *mut [bool; 0];
19+
let mut _6: std::num::NonZero<usize>;
2020
scope 6 {
21-
scope 10 (inlined NonNull::<[bool; 0]>::new_unchecked) {
22-
let mut _8: bool;
23-
let _9: ();
24-
let mut _10: *mut ();
25-
let mut _11: *const [bool; 0];
26-
scope 11 (inlined core::ub_checks::check_language_ub) {
27-
scope 12 (inlined core::ub_checks::check_language_ub::runtime) {
21+
scope 8 (inlined std::ptr::Alignment::as_nonzero) {
22+
}
23+
scope 9 (inlined NonNull::<[bool; 0]>::without_provenance) {
24+
let _7: *const [bool; 0];
25+
scope 10 {
26+
}
27+
scope 11 (inlined NonZero::<usize>::get) {
28+
}
29+
scope 12 (inlined without_provenance::<[bool; 0]>) {
30+
scope 13 (inlined without_provenance_mut::<[bool; 0]>) {
2831
}
2932
}
3033
}
3134
}
32-
scope 7 (inlined dangling_mut::<[bool; 0]>) {
33-
let mut _7: usize;
34-
scope 8 (inlined align_of::<[bool; 0]>) {
35-
}
36-
scope 9 (inlined without_provenance_mut::<[bool; 0]>) {
37-
}
35+
scope 7 (inlined std::ptr::Alignment::of::<[bool; 0]>) {
3836
}
3937
}
4038
}
@@ -44,54 +42,31 @@
4442
StorageLive(_1);
4543
StorageLive(_2);
4644
StorageLive(_3);
47-
StorageLive(_9);
4845
StorageLive(_4);
4946
StorageLive(_5);
5047
StorageLive(_6);
48+
_6 = const NonZero::<usize>(core::num::niche_types::NonZeroUsizeInner(1_usize));
5149
StorageLive(_7);
52-
_7 = const 1_usize;
53-
_6 = const {0x1 as *mut [bool; 0]};
54-
StorageLive(_11);
55-
StorageLive(_8);
56-
_8 = UbChecks();
57-
switchInt(move _8) -> [0: bb4, otherwise: bb2];
58-
}
59-
60-
bb1: {
61-
StorageDead(_1);
62-
return;
63-
}
64-
65-
bb2: {
66-
StorageLive(_10);
67-
_10 = const {0x1 as *mut ()};
68-
_9 = NonNull::<T>::new_unchecked::precondition_check(const {0x1 as *mut ()}) -> [return: bb3, unwind unreachable];
69-
}
70-
71-
bb3: {
72-
StorageDead(_10);
73-
goto -> bb4;
74-
}
75-
76-
bb4: {
77-
StorageDead(_8);
78-
_11 = const {0x1 as *const [bool; 0]};
50+
_7 = const {0x1 as *const [bool; 0]};
7951
_5 = const NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }};
80-
StorageDead(_11);
8152
StorageDead(_7);
8253
StorageDead(_6);
8354
_4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }};
8455
StorageDead(_5);
8556
_3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }};
8657
StorageDead(_4);
8758
_2 = const Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global);
88-
StorageDead(_9);
8959
StorageDead(_3);
9060
_1 = const A {{ foo: Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }};
9161
StorageDead(_2);
9262
_0 = const ();
9363
drop(_1) -> [return: bb1, unwind unreachable];
9464
}
65+
66+
bb1: {
67+
StorageDead(_1);
68+
return;
69+
}
9570
}
9671

9772
ALLOC2 (size: 8, align: 4) { .. }

tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.DataflowConstProp.32bit.panic-unwind.diff

+23-48
Original file line numberDiff line numberDiff line change
@@ -16,25 +16,23 @@
1616
scope 4 (inlined Unique::<[bool; 0]>::dangling) {
1717
let mut _5: std::ptr::NonNull<[bool; 0]>;
1818
scope 5 (inlined NonNull::<[bool; 0]>::dangling) {
19-
let _6: *mut [bool; 0];
19+
let mut _6: std::num::NonZero<usize>;
2020
scope 6 {
21-
scope 10 (inlined NonNull::<[bool; 0]>::new_unchecked) {
22-
let mut _8: bool;
23-
let _9: ();
24-
let mut _10: *mut ();
25-
let mut _11: *const [bool; 0];
26-
scope 11 (inlined core::ub_checks::check_language_ub) {
27-
scope 12 (inlined core::ub_checks::check_language_ub::runtime) {
21+
scope 8 (inlined std::ptr::Alignment::as_nonzero) {
22+
}
23+
scope 9 (inlined NonNull::<[bool; 0]>::without_provenance) {
24+
let _7: *const [bool; 0];
25+
scope 10 {
26+
}
27+
scope 11 (inlined NonZero::<usize>::get) {
28+
}
29+
scope 12 (inlined without_provenance::<[bool; 0]>) {
30+
scope 13 (inlined without_provenance_mut::<[bool; 0]>) {
2831
}
2932
}
3033
}
3134
}
32-
scope 7 (inlined dangling_mut::<[bool; 0]>) {
33-
let mut _7: usize;
34-
scope 8 (inlined align_of::<[bool; 0]>) {
35-
}
36-
scope 9 (inlined without_provenance_mut::<[bool; 0]>) {
37-
}
35+
scope 7 (inlined std::ptr::Alignment::of::<[bool; 0]>) {
3836
}
3937
}
4038
}
@@ -44,58 +42,35 @@
4442
StorageLive(_1);
4543
StorageLive(_2);
4644
StorageLive(_3);
47-
StorageLive(_9);
4845
StorageLive(_4);
4946
StorageLive(_5);
5047
StorageLive(_6);
48+
_6 = const NonZero::<usize>(core::num::niche_types::NonZeroUsizeInner(1_usize));
5149
StorageLive(_7);
52-
_7 = const 1_usize;
53-
_6 = const {0x1 as *mut [bool; 0]};
54-
StorageLive(_11);
55-
StorageLive(_8);
56-
_8 = UbChecks();
57-
switchInt(move _8) -> [0: bb5, otherwise: bb3];
58-
}
59-
60-
bb1: {
61-
StorageDead(_1);
62-
return;
63-
}
64-
65-
bb2 (cleanup): {
66-
resume;
67-
}
68-
69-
bb3: {
70-
StorageLive(_10);
71-
_10 = const {0x1 as *mut ()};
72-
_9 = NonNull::<T>::new_unchecked::precondition_check(const {0x1 as *mut ()}) -> [return: bb4, unwind unreachable];
73-
}
74-
75-
bb4: {
76-
StorageDead(_10);
77-
goto -> bb5;
78-
}
79-
80-
bb5: {
81-
StorageDead(_8);
82-
_11 = const {0x1 as *const [bool; 0]};
50+
_7 = const {0x1 as *const [bool; 0]};
8351
_5 = const NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }};
84-
StorageDead(_11);
8552
StorageDead(_7);
8653
StorageDead(_6);
8754
_4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }};
8855
StorageDead(_5);
8956
_3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }};
9057
StorageDead(_4);
9158
_2 = const Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC1, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global);
92-
StorageDead(_9);
9359
StorageDead(_3);
9460
_1 = const A {{ foo: Box::<[bool]>(Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC2, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }}, std::alloc::Global) }};
9561
StorageDead(_2);
9662
_0 = const ();
9763
drop(_1) -> [return: bb1, unwind: bb2];
9864
}
65+
66+
bb1: {
67+
StorageDead(_1);
68+
return;
69+
}
70+
71+
bb2 (cleanup): {
72+
resume;
73+
}
9974
}
10075

10176
ALLOC2 (size: 8, align: 4) { .. }

0 commit comments

Comments
 (0)