Skip to content

Commit 6ad5e69

Browse files
authored
Rollup merge of #69799 - TimDiekmann:zst, r=Amanieu
Allow ZSTs in `AllocRef` Allows ZSTs in all `AllocRef` methods. The implementation of `AllocRef` for `Global` and `System` were adjusted to reflect those changes. This is the second item on the roadmap to support ZSTs in `AllocRef`: rust-lang/wg-allocators#38 (comment) After this has landed, I will adapt `RawVec`, but since this will be a pretty big overhaul, it makes sense to do a different PR for it. ~~Requires #69794 to land first~~ r? @Amanieu
2 parents 977d69f + f77afc8 commit 6ad5e69

File tree

5 files changed

+96
-81
lines changed

5 files changed

+96
-81
lines changed

Diff for: src/liballoc/alloc.rs

+28-6
Original file line numberDiff line numberDiff line change
@@ -165,13 +165,19 @@ pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
165165
#[unstable(feature = "allocator_api", issue = "32838")]
166166
unsafe impl AllocRef for Global {
167167
#[inline]
168-
unsafe fn alloc(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
169-
NonNull::new(alloc(layout)).ok_or(AllocErr).map(|p| (p, layout.size()))
168+
fn alloc(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
169+
if layout.size() == 0 {
170+
Ok((layout.dangling(), 0))
171+
} else {
172+
unsafe { NonNull::new(alloc(layout)).ok_or(AllocErr).map(|p| (p, layout.size())) }
173+
}
170174
}
171175

172176
#[inline]
173177
unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
174-
dealloc(ptr.as_ptr(), layout)
178+
if layout.size() != 0 {
179+
dealloc(ptr.as_ptr(), layout)
180+
}
175181
}
176182

177183
#[inline]
@@ -181,12 +187,28 @@ unsafe impl AllocRef for Global {
181187
layout: Layout,
182188
new_size: usize,
183189
) -> Result<(NonNull<u8>, usize), AllocErr> {
184-
NonNull::new(realloc(ptr.as_ptr(), layout, new_size)).ok_or(AllocErr).map(|p| (p, new_size))
190+
match (layout.size(), new_size) {
191+
(0, 0) => Ok((layout.dangling(), 0)),
192+
(0, _) => self.alloc(Layout::from_size_align_unchecked(new_size, layout.align())),
193+
(_, 0) => {
194+
self.dealloc(ptr, layout);
195+
Ok((layout.dangling(), 0))
196+
}
197+
(_, _) => NonNull::new(realloc(ptr.as_ptr(), layout, new_size))
198+
.ok_or(AllocErr)
199+
.map(|p| (p, new_size)),
200+
}
185201
}
186202

187203
#[inline]
188-
unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
189-
NonNull::new(alloc_zeroed(layout)).ok_or(AllocErr).map(|p| (p, layout.size()))
204+
fn alloc_zeroed(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
205+
if layout.size() == 0 {
206+
Ok((layout.dangling(), 0))
207+
} else {
208+
unsafe {
209+
NonNull::new(alloc_zeroed(layout)).ok_or(AllocErr).map(|p| (p, layout.size()))
210+
}
211+
}
190212
}
191213
}
192214

Diff for: src/liballoc/raw_vec.rs

+18-20
Original file line numberDiff line numberDiff line change
@@ -73,30 +73,28 @@ impl<T, A: AllocRef> RawVec<T, A> {
7373
}
7474

7575
fn allocate_in(mut capacity: usize, zeroed: bool, mut a: A) -> Self {
76-
unsafe {
77-
let elem_size = mem::size_of::<T>();
76+
let elem_size = mem::size_of::<T>();
7877

79-
let alloc_size = capacity.checked_mul(elem_size).unwrap_or_else(|| capacity_overflow());
80-
alloc_guard(alloc_size).unwrap_or_else(|_| capacity_overflow());
78+
let alloc_size = capacity.checked_mul(elem_size).unwrap_or_else(|| capacity_overflow());
79+
alloc_guard(alloc_size).unwrap_or_else(|_| capacity_overflow());
8180

82-
// Handles ZSTs and `capacity == 0` alike.
83-
let ptr = if alloc_size == 0 {
84-
NonNull::<T>::dangling()
85-
} else {
86-
let align = mem::align_of::<T>();
87-
let layout = Layout::from_size_align(alloc_size, align).unwrap();
88-
let result = if zeroed { a.alloc_zeroed(layout) } else { a.alloc(layout) };
89-
match result {
90-
Ok((ptr, size)) => {
91-
capacity = size / elem_size;
92-
ptr.cast()
93-
}
94-
Err(_) => handle_alloc_error(layout),
81+
// Handles ZSTs and `capacity == 0` alike.
82+
let ptr = if alloc_size == 0 {
83+
NonNull::<T>::dangling()
84+
} else {
85+
let align = mem::align_of::<T>();
86+
let layout = Layout::from_size_align(alloc_size, align).unwrap();
87+
let result = if zeroed { a.alloc_zeroed(layout) } else { a.alloc(layout) };
88+
match result {
89+
Ok((ptr, size)) => {
90+
capacity = size / elem_size;
91+
ptr.cast()
9592
}
96-
};
93+
Err(_) => handle_alloc_error(layout),
94+
}
95+
};
9796

98-
RawVec { ptr: ptr.into(), cap: capacity, a }
99-
}
97+
RawVec { ptr: ptr.into(), cap: capacity, a }
10098
}
10199
}
102100

Diff for: src/liballoc/raw_vec/tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ fn allocator_param() {
2020
fuel: usize,
2121
}
2222
unsafe impl AllocRef for BoundedAlloc {
23-
unsafe fn alloc(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
23+
fn alloc(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
2424
let size = layout.size();
2525
if size > self.fuel {
2626
return Err(AllocErr);

Diff for: src/libcore/alloc.rs

+13-43
Original file line numberDiff line numberDiff line change
@@ -606,20 +606,11 @@ pub unsafe trait GlobalAlloc {
606606
/// method (`dealloc`) or by being passed to a reallocation method
607607
/// (see above) that returns `Ok`.
608608
///
609-
/// A note regarding zero-sized types and zero-sized layouts: many
610-
/// methods in the `AllocRef` trait state that allocation requests
611-
/// must be non-zero size, or else undefined behavior can result.
612-
///
613-
/// * If an `AllocRef` implementation chooses to return `Ok` in this
614-
/// case (i.e., the pointer denotes a zero-sized inaccessible block)
615-
/// then that returned pointer must be considered "currently
616-
/// allocated". On such an allocator, *all* methods that take
617-
/// currently-allocated pointers as inputs must accept these
618-
/// zero-sized pointers, *without* causing undefined behavior.
619-
///
620-
/// * In other words, if a zero-sized pointer can flow out of an
621-
/// allocator, then that allocator must likewise accept that pointer
622-
/// flowing back into its deallocation and reallocation methods.
609+
/// Unlike [`GlobalAlloc`], zero-sized allocations are allowed in
610+
/// `AllocRef`. If an underlying allocator does not support this (like
611+
/// jemalloc) or return a null pointer (such as `libc::malloc`), this case
612+
/// must be caught. In this case [`Layout::dangling()`] can be used to
613+
/// create a dangling, but aligned `NonNull<u8>`.
623614
///
624615
/// Some of the methods require that a layout *fit* a memory block.
625616
/// What it means for a layout to "fit" a memory block means (or
@@ -649,6 +640,9 @@ pub unsafe trait GlobalAlloc {
649640
/// * if an allocator does not support overallocating, it is fine to
650641
/// simply return `layout.size()` as the allocated size.
651642
///
643+
/// [`GlobalAlloc`]: self::GlobalAlloc
644+
/// [`Layout::dangling()`]: self::Layout::dangling
645+
///
652646
/// # Safety
653647
///
654648
/// The `AllocRef` trait is an `unsafe` trait for a number of reasons, and
@@ -669,14 +663,6 @@ pub unsafe trait GlobalAlloc {
669663
/// the future.
670664
#[unstable(feature = "allocator_api", issue = "32838")]
671665
pub unsafe trait AllocRef {
672-
// (Note: some existing allocators have unspecified but well-defined
673-
// behavior in response to a zero size allocation request ;
674-
// e.g., in C, `malloc` of 0 will either return a null pointer or a
675-
// unique pointer, but will not have arbitrary undefined
676-
// behavior.
677-
// However in jemalloc for example,
678-
// `mallocx(0)` is documented as undefined behavior.)
679-
680666
/// On success, returns a pointer meeting the size and alignment
681667
/// guarantees of `layout` and the actual size of the allocated block,
682668
/// which must be greater than or equal to `layout.size()`.
@@ -690,15 +676,6 @@ pub unsafe trait AllocRef {
690676
/// behavior, e.g., to ensure initialization to particular sets of
691677
/// bit patterns.)
692678
///
693-
/// # Safety
694-
///
695-
/// This function is unsafe because undefined behavior can result
696-
/// if the caller does not ensure that `layout` has non-zero size.
697-
///
698-
/// (Extension subtraits might provide more specific bounds on
699-
/// behavior, e.g., guarantee a sentinel address or a null pointer
700-
/// in response to a zero-size allocation request.)
701-
///
702679
/// # Errors
703680
///
704681
/// Returning `Err` indicates that either memory is exhausted or
@@ -716,7 +693,7 @@ pub unsafe trait AllocRef {
716693
/// rather than directly invoking `panic!` or similar.
717694
///
718695
/// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
719-
unsafe fn alloc(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr>;
696+
fn alloc(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr>;
720697

721698
/// Deallocate the memory referenced by `ptr`.
722699
///
@@ -738,10 +715,6 @@ pub unsafe trait AllocRef {
738715
/// Behaves like `alloc`, but also ensures that the contents
739716
/// are set to zero before being returned.
740717
///
741-
/// # Safety
742-
///
743-
/// This function is unsafe for the same reasons that `alloc` is.
744-
///
745718
/// # Errors
746719
///
747720
/// Returning `Err` indicates that either memory is exhausted or
@@ -753,17 +726,17 @@ pub unsafe trait AllocRef {
753726
/// rather than directly invoking `panic!` or similar.
754727
///
755728
/// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html
756-
unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
729+
fn alloc_zeroed(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
757730
let size = layout.size();
758731
let result = self.alloc(layout);
759732
if let Ok((p, _)) = result {
760-
ptr::write_bytes(p.as_ptr(), 0, size);
733+
unsafe { ptr::write_bytes(p.as_ptr(), 0, size) }
761734
}
762735
result
763736
}
764737

765738
// == METHODS FOR MEMORY REUSE ==
766-
// realloc. alloc_excess, realloc_excess
739+
// realloc, realloc_zeroed, grow_in_place, grow_in_place_zeroed, shrink_in_place
767740

768741
/// Returns a pointer suitable for holding data described by
769742
/// a new layout with `layout`’s alignment and a size given
@@ -793,8 +766,6 @@ pub unsafe trait AllocRef {
793766
/// * `layout` must *fit* the `ptr` (see above). (The `new_size`
794767
/// argument need not fit it.)
795768
///
796-
/// * `new_size` must be greater than zero.
797-
///
798769
/// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
799770
/// must not overflow (i.e., the rounded value must be less than `usize::MAX`).
800771
///
@@ -1009,8 +980,7 @@ pub unsafe trait AllocRef {
1009980
/// * `layout` must *fit* the `ptr` (see above); note the
1010981
/// `new_size` argument need not fit it,
1011982
///
1012-
/// * `new_size` must not be greater than `layout.size()`
1013-
/// (and must be greater than zero),
983+
/// * `new_size` must not be greater than `layout.size()`,
1014984
///
1015985
/// # Errors
1016986
///

Diff for: src/libstd/alloc.rs

+36-11
Original file line numberDiff line numberDiff line change
@@ -133,24 +133,41 @@ pub use alloc_crate::alloc::*;
133133
#[derive(Debug, Default, Copy, Clone)]
134134
pub struct System;
135135

136-
// The AllocRef impl just forwards to the GlobalAlloc impl, which is in `std::sys::*::alloc`.
136+
// The AllocRef impl checks the layout size to be non-zero and forwards to the GlobalAlloc impl,
137+
// which is in `std::sys::*::alloc`.
137138
#[unstable(feature = "allocator_api", issue = "32838")]
138139
unsafe impl AllocRef for System {
139140
#[inline]
140-
unsafe fn alloc(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
141-
NonNull::new(GlobalAlloc::alloc(self, layout)).ok_or(AllocErr).map(|p| (p, layout.size()))
141+
fn alloc(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
142+
if layout.size() == 0 {
143+
Ok((layout.dangling(), 0))
144+
} else {
145+
unsafe {
146+
NonNull::new(GlobalAlloc::alloc(self, layout))
147+
.ok_or(AllocErr)
148+
.map(|p| (p, layout.size()))
149+
}
150+
}
142151
}
143152

144153
#[inline]
145-
unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
146-
NonNull::new(GlobalAlloc::alloc_zeroed(self, layout))
147-
.ok_or(AllocErr)
148-
.map(|p| (p, layout.size()))
154+
fn alloc_zeroed(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
155+
if layout.size() == 0 {
156+
Ok((layout.dangling(), 0))
157+
} else {
158+
unsafe {
159+
NonNull::new(GlobalAlloc::alloc_zeroed(self, layout))
160+
.ok_or(AllocErr)
161+
.map(|p| (p, layout.size()))
162+
}
163+
}
149164
}
150165

151166
#[inline]
152167
unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
153-
GlobalAlloc::dealloc(self, ptr.as_ptr(), layout)
168+
if layout.size() != 0 {
169+
GlobalAlloc::dealloc(self, ptr.as_ptr(), layout)
170+
}
154171
}
155172

156173
#[inline]
@@ -160,9 +177,17 @@ unsafe impl AllocRef for System {
160177
layout: Layout,
161178
new_size: usize,
162179
) -> Result<(NonNull<u8>, usize), AllocErr> {
163-
NonNull::new(GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size))
164-
.ok_or(AllocErr)
165-
.map(|p| (p, new_size))
180+
match (layout.size(), new_size) {
181+
(0, 0) => Ok((layout.dangling(), 0)),
182+
(0, _) => self.alloc(Layout::from_size_align_unchecked(new_size, layout.align())),
183+
(_, 0) => {
184+
self.dealloc(ptr, layout);
185+
Ok((layout.dangling(), 0))
186+
}
187+
(_, _) => NonNull::new(GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size))
188+
.ok_or(AllocErr)
189+
.map(|p| (p, new_size)),
190+
}
166191
}
167192
}
168193

0 commit comments

Comments
 (0)