Skip to main content

ialloc/allocator/win32/
heap_no_serialize.rs

1use crate::*;
2use crate::meta::*;
3use super::Error;
4
5use winapi::um::heapapi::{HeapAlloc, HeapReAlloc, HeapFree, HeapSize, HeapDestroy, HeapCreate};
6use winapi::um::winnt::{HANDLE, HEAP_ZERO_MEMORY, HEAP_NO_SERIALIZE, HEAP_GENERATE_EXCEPTIONS};
7
8use core::mem::MaybeUninit;
9use core::num::NonZeroUsize;
10use core::ptr::NonNull;
11
12
13
14/// [`HeapAlloc`] / [`HeapReAlloc`] / [`HeapFree`] / [`HeapSize`] w/ [`HEAP_NO_SERIALIZE`]
15///
16/// | Rust                                      | C                     |
17/// | ------------------------------------------| ----------------------|
18/// | [`thin::Alloc::alloc_uninit`]             | <code>[HeapAlloc](heap, [HEAP_NO_SERIALIZE], size)</code>
19/// | [`thin::Alloc::alloc_zeroed`]             | <code>[HeapAlloc](heap, [HEAP_NO_SERIALIZE]\|[HEAP_ZERO_MEMORY], size)</code>
20/// | [`thin::Realloc::realloc_uninit`]         | <code>[HeapReAlloc](heap, [HEAP_NO_SERIALIZE], ptr, size)</code>
21/// | [`thin::Realloc::realloc_zeroed`]         | <code>[HeapReAlloc](heap, [HEAP_NO_SERIALIZE]\|[HEAP_ZERO_MEMORY], ptr, size)</code>
22/// | [`thin::Free::free`]                      | <code>[HeapFree]\(heap, [HEAP_NO_SERIALIZE], ptr\)</code>
23/// | [`thin::SizeOf::size_of`]                 | <code>[HeapSize]\(heap, [HEAP_NO_SERIALIZE], ptr\)</code>
24///
25/// ## Recommended Reading
26/// *   [Heap Functions](https://learn.microsoft.com/en-us/windows/win32/memory/heap-functions)
27/// *   [Low-fragmentation Heap](https://learn.microsoft.com/en-us/windows/win32/memory/low-fragmentation-heap)
28///
29#[doc = include_str!("_refs.md")]
30#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] // SAFETY: this cannot be Clone or Copy as this owns the `HANDLE`
31#[repr(transparent)] // SAFETY: HeapNoSerialize::borrow makes use of this
32pub struct HeapNoSerialize(HANDLE); // SAFETY: This should always be a valid `Heap*` compatible handle, to a heap used exclusively by this thread
33
34impl Drop for HeapNoSerialize {
35    fn drop(&mut self) {
36        // SAFETY: ✔️ We supposedly exclusively own `self.0`
37        let succeeds = unsafe { HeapDestroy(self.0) };
38        if succeeds == 0 {
39            let err = super::get_last_error();
40            panic!("HeapDestroy({:?}) failed with GetLastError() == 0x{:08x}", self.0, err);
41        }
42    }
43}
44
45/// ```no_compile,E0277
46/// # use ialloc::allocator::win32::HeapNoSerialize;
47/// let heap = HeapNoSerialize::create(0, None, None);
48/// assert_send(heap);
49/// fn assert_send(_: impl Send) {}
50/// ```
51///
52/// ```no_compile,E0277
53/// # use ialloc::allocator::win32::HeapNoSerialize;
54/// let heap = HeapNoSerialize::create(0, None, None);
55/// assert_sync(heap);
56/// fn assert_sync(_: impl Sync) {}
57/// ```
58#[allow(dead_code)] struct AssertNotSendSync;
59
60impl HeapNoSerialize {
61    /// Borrow a [`HeapAlloc`]-compatible `HANDLE`.
62    ///
63    /// ### Safety
64    /// *   `*handle` must be a valid [`HeapAlloc`]-compatible `HANDLE`.
65    /// *   `*handle` must be a growable heap
66    /// *   `*handle` must only be accessed by the current thread
67    /// *   `*handle` must remain valid while borrowed
68    ///
69    #[doc = include_str!("_refs.md")]
70    pub unsafe fn borrow(handle: &HANDLE) -> &Self {
71        // SAFETY: ✔️ `Self` is a `#[repr(transparent)]` wrapper around `HANDLE`, so this should be safe
72        unsafe { core::mem::transmute(handle) }
73    }
74
75    /// [`HeapCreate`]
76    ///
77    /// [`HEAP_NO_SERIALIZE`] is recommended but not required.
78    ///
79    /// ### Safety
80    /// *   <code>options &amp; [HEAP_GENERATE_EXCEPTIONS]</code> is forbidden: Rust assumes C-ABI / no SEH exceptions
81    /// *   New `options` may be added which are similarly undefined behavior.
82    /// *   The function may make a best-effort attempt to [`panic!`] instead of invoking UB.
83    /// *   No idea what happens if `initial_size` > `maximum_size`.
84    ///
85    #[doc = include_str!("_refs.md")]
86    pub unsafe fn try_create(options: u32, initial_size: Option<NonZeroUsize>, maximum_size: Option<NonZeroUsize>) -> Result<Self, Error> {
87        assert!(options & HEAP_GENERATE_EXCEPTIONS == 0, "bug: undefined behavior: HeapNoSerialize::try_create cannot be used with HEAP_GENERATE_EXCEPTIONS");
88        let initial_size = initial_size.map_or(0, |nz| nz.get());
89        let maximum_size = maximum_size.map_or(0, |nz| nz.get());
90
91        // SAFETY: ✔️ preconditions documented in Safety docs
92        let handle = unsafe { HeapCreate(options, initial_size, maximum_size) };
93        if handle.is_null() { return Err(Error::get_last()) }
94        Ok(Self(handle))
95    }
96
97    /// [`HeapCreate`]
98    ///
99    /// [`HEAP_NO_SERIALIZE`] is recommended but not required.
100    ///
101    /// ### Safety
102    /// *   <code>options &amp; [HEAP_GENERATE_EXCEPTIONS]</code> is forbidden: Rust assumes C-ABI / no SEH exceptions
103    /// *   New `options` may be added which are similarly undefined behavior.
104    /// *   The function may make a best-effort attempt to [`panic!`] instead of invoking UB.
105    /// *   No idea what happens if `initial_size` > `maximum_size`.
106    ///
107    #[doc = include_str!("_refs.md")]
108    pub unsafe fn create(options: u32, initial_size: Option<NonZeroUsize>, maximum_size: Option<NonZeroUsize>) -> Self {
109        // SAFETY: ✔️ create and try_create have identical preconditions
110        unsafe { Self::try_create(options, initial_size, maximum_size) }.unwrap_or_else(|err| panic!("HeapCreate failed with GetLastError() == {err:?}"))
111    }
112}
113
114
115
116
117// meta::*
118
119impl Meta for HeapNoSerialize {
120    type Error = Error;
121
122    const MIN_ALIGN : Alignment = super::MEMORY_ALLOCATION_ALIGNMENT; // Verified through testing
123
124    /// The alignment of memory returned by `HeapAlloc` is `MEMORY_ALLOCATION_ALIGNMENT` in WinNT.h:
125    /// ```cpp
126    /// #if defined(_WIN64) || defined(_M_ALPHA)
127    /// #define MEMORY_ALLOCATION_ALIGNMENT 16
128    /// #else
129    /// #define MEMORY_ALLOCATION_ALIGNMENT 8
130    /// #endif
131    /// ```
132    ///
133    /// <https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapalloc#remarks>
134    const MAX_ALIGN : Alignment = super::MEMORY_ALLOCATION_ALIGNMENT; // Verified through testing
135    const MAX_SIZE  : usize     = usize::MAX;
136    const ZST_SUPPORTED : bool  = true;
137}
138
139impl ZstSupported for HeapNoSerialize {}
140
141
142
143// thin::*
144
145/// | Safety Item   | Description   |
146/// | --------------| --------------|
147/// | `align`       | ✔️ Validated via [`thin::test::alignment`]
148/// | `size`        | ✔️ Validated via [`thin::test::edge_case_sizes`]
149/// | `pin`         | ✔️ [`HeapNoSerialize`] is `'static` - allocations by [`HeapAlloc`] live until [`HeapReAlloc`]ed, [`HeapFree`]d, or the [`HeapNoSerialize`] is [`Drop`]ed outright (not merely moved.)
150/// | `compatible`  | ✔️ [`HeapNoSerialize`] uses exclusively intercompatible `Heap*` fns
151/// | `exclusive`   | ✔️ Allocations by [`HeapAlloc`] are exclusive/unique
152/// | `exceptions`  | ✔️ [`HeapAlloc`] returns null on error per docs / lack of [`HEAP_GENERATE_EXCEPTIONS`].  Non-unwinding fatalish heap corruption exceptions will only occur after previous undefined behavior.
153/// | `threads`     | ✔️ [`HEAP_NO_SERIALIZE`] is used, making this not thread safe.  However, we enforce `HeapNoSerialize : !Send + !Sync` as validated by `AssertNotSendSync`.
154/// | `zeroed`      | ✔️ Validated via [`thin::test::zeroed_alloc`], correct use of [`HEAP_ZERO_MEMORY`]
155///
156#[doc = include_str!("_refs.md")]
157// SAFETY: per above
158unsafe impl thin::Alloc for HeapNoSerialize {
159    fn alloc_uninit(&self, size: usize) -> Result<AllocNN, Self::Error> {
160        // SAFETY: ✔️ `self.0` is a valid heap, accessed exclusively by this thread, per `Self`'s construction
161        let alloc = unsafe { HeapAlloc(self.0, HEAP_NO_SERIALIZE, size) };
162        NonNull::new(alloc.cast()).ok_or_else(Error::get_last)
163    }
164
165    fn alloc_zeroed(&self, size: usize) -> Result<AllocNN0, Self::Error> {
166        // SAFETY: ✔️ `self.0` is a valid heap, accessed exclusively by this thread, per `Self`'s construction
167        let alloc = unsafe { HeapAlloc(self.0, HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY, size) };
168        NonNull::new(alloc.cast()).ok_or_else(Error::get_last)
169    }
170}
171
172/// | Safety Item   | Description   |
173/// | --------------| --------------|
174/// | `align`       | ⚠️ untested, but *should* be safe if [`thin::Alloc`] was
175/// | `size`        | ⚠️ untested, but *should* be safe if [`thin::Alloc`] was
176/// | `pin`         | ✔️ [`HeapNoSerialize`] is `'static` - reallocations by [`HeapReAlloc`] live until [`HeapReAlloc`]ed again or [`HeapFree`]d
177/// | `compatible`  | ✔️ [`HeapNoSerialize`] uses exclusively intercompatible `Heap*` fns
178/// | `exclusive`   | ✔️ Allocations by [`HeapReAlloc`] are exclusive/unique
179/// | `exceptions`  | ✔️ [`HeapReAlloc`] returns null on error per docs / lack of [`HEAP_GENERATE_EXCEPTIONS`].  Non-unwinding fatalish heap corruption exceptions will only occur after previous undefined behavior.
180/// | `threads`     | ✔️ [`HEAP_NO_SERIALIZE`] is used, making this not thread safe.  However, we enforce `HeapNoSerialize : !Send + !Sync` as validated by `AssertNotSendSync`.
181/// | `zeroed`      | ⚠️ untested, but we use [`HEAP_ZERO_MEMORY`] appropriately...
182/// | `preserved`   | ⚠️ untested, but *should* be the case...
183///
184#[doc = include_str!("_refs.md")]
185#[allow(clippy::missing_safety_doc)]
186// SAFETY: per above
187unsafe impl thin::Realloc for HeapNoSerialize {
188    const CAN_REALLOC_ZEROED : bool = true;
189
190    unsafe fn realloc_uninit(&self, ptr: AllocNN, new_size: usize) -> Result<AllocNN, Self::Error> {
191        // SAFETY: ✔️ `self.0` is a valid heap, accessed exclusively by this thread, per `Self`'s construction
192        // SAFETY: ✔️ `ptr` belongs to `self` per thin::Realloc's documented safety preconditions, and thus was allocated with `Heap{,Re}Alloc` on `self.0`
193        let alloc = unsafe { HeapReAlloc(self.0, HEAP_NO_SERIALIZE, ptr.as_ptr().cast(), new_size) };
194        NonNull::new(alloc.cast()).ok_or_else(Error::get_last)
195    }
196
197    unsafe fn realloc_zeroed(&self, ptr: AllocNN, new_size: usize) -> Result<AllocNN, Self::Error> {
198        // SAFETY: ✔️ `self.0` is a valid heap, accessed exclusively by this thread, per `Self`'s construction
199        // SAFETY: ✔️ `ptr` belongs to `self` per thin::Realloc's documented safety preconditions, and thus was allocated with `Heap{,Re}Alloc` on `self.0`
200        let alloc = unsafe { HeapReAlloc(self.0, HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY, ptr.as_ptr().cast(), new_size) };
201        NonNull::new(alloc.cast()).ok_or_else(Error::get_last)
202    }
203}
204
205/// | Safety Item   | Description   |
206/// | --------------| --------------|
207/// | `compatible`  | ✔️ [`HeapNoSerialize`] uses exclusively intercompatible `Heap*` fns
208/// | `exceptions`  | ✔️ [`HeapFree`] returns `FALSE`/`0` on error per docs / lack of [`HEAP_GENERATE_EXCEPTIONS`].  Non-unwinding fatalish heap corruption exceptions will only occur after previous undefined behavior.
209/// | `threads`     | ✔️ [`HEAP_NO_SERIALIZE`] is used, making this not thread safe.  However, we enforce `HeapNoSerialize : !Send + !Sync` as validated by `AssertNotSendSync`.
210///
211#[doc = include_str!("_refs.md")]
212#[allow(clippy::missing_safety_doc)]
213// SAFETY: per above
214unsafe impl thin::Free for HeapNoSerialize {
215    unsafe fn free_nullable(&self, ptr: *mut MaybeUninit<u8>) {
216        // SAFETY: ✔️ `ptr` can be nullptr (validated via [`thin::test::nullable`] and documented: "[This pointer can be NULL](https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapfree#parameters).")
217        // SAFETY: ✔️ `ptr` otherwise belongs to `self` per [`thin::Free::free_nullable`]'s documented safety preconditions - and thus was allocated with `Heap{,Re}Alloc` on `self.0`
218        if unsafe { HeapFree(self.0, HEAP_NO_SERIALIZE, ptr.cast()) } == 0 && cfg!(debug_assertions) { bug::ub::free_failed(ptr) }
219    }
220}
221
222// SAFETY: ✔️ SizeOfDebug has same preconditions
223unsafe impl thin::SizeOf for HeapNoSerialize {}
224
225/// | Safety Item   | Description   |
226/// | --------------| --------------|
227/// | `size`        | ✔️ Validated via [`thin::test::size_exact_alloc`]
228/// | `compatible`  | ✔️ [`HeapNoSerialize`] uses exclusively intercompatible `Heap*` fns
229/// | `exceptions`  | ✔️ [`HeapSize`] returns `-1` on error per docs / lack of [`HEAP_GENERATE_EXCEPTIONS`].  Non-unwinding fatalish heap corruption exceptions will only occur after previous undefined behavior.
230/// | `threads`     | ✔️ [`HEAP_NO_SERIALIZE`] is used, making this not thread safe.  However, we enforce `HeapNoSerialize : !Send + !Sync` as validated by `AssertNotSendSync`.
231///
232#[doc = include_str!("_refs.md")]
233#[allow(clippy::missing_safety_doc)]
234// SAFETY: per above
235unsafe impl thin::SizeOfDebug for HeapNoSerialize {
236    unsafe fn size_of_debug(&self, ptr: AllocNN) -> Option<usize> {
237        // SAFETY: ✔️ `ptr` belongs to `self` per [`thin::SizeOfDebug::size_of_debug`]'s documented safety preconditions - and thus was allocated with `Heap{,Re}Alloc` on `self.0`
238        let size = unsafe { HeapSize(self.0, HEAP_NO_SERIALIZE, ptr.as_ptr().cast()) };
239        if size == !0 { return None }
240        Some(size)
241    }
242}
243
244
245
246#[no_implicit_prelude] mod cleanroom {
247    use super::{impls, HeapNoSerialize};
248
249    impls! {
250        unsafe impl ialloc::fat::Alloc      for HeapNoSerialize => ialloc::thin::Alloc;
251        unsafe impl ialloc::fat::Realloc    for HeapNoSerialize => ialloc::thin::Realloc;
252        unsafe impl ialloc::fat::Free       for HeapNoSerialize => ialloc::thin::Free;
253    }
254}
255
256
257
258#[cfg(test)] fn create_test_heap(initial_size: Option<NonZeroUsize>, maximum_size: Option<NonZeroUsize>) -> HeapNoSerialize {
259    // SAFETY: ✔️ no forbidden flags used
260    unsafe { HeapNoSerialize::create(HEAP_NO_SERIALIZE, initial_size, maximum_size) }
261}
262
263#[test] fn thin_alignment() {
264    thin::test::alignment(create_test_heap(None, None));
265    thin::test::alignment(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
266}
267
268#[test] fn thin_edge_case_sizes() {
269    thin::test::edge_case_sizes(create_test_heap(None, None));
270    thin::test::edge_case_sizes(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
271}
272
273#[test] fn thin_nullable() {
274    thin::test::nullable(create_test_heap(None, None));
275    thin::test::nullable(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
276}
277
278#[test] fn thin_size() {
279    thin::test::size_exact_alloc(create_test_heap(None, None));
280    thin::test::size_exact_alloc(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
281}
282
283#[test] fn thin_uninit() {
284    unsafe {
285        thin::test::uninit_alloc_unsound(create_test_heap(None, None));
286        thin::test::uninit_alloc_unsound(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
287    }
288}
289
290#[test] fn thin_uninit_realloc() {
291    thin::test::uninit_realloc(create_test_heap(None, None));
292    thin::test::uninit_realloc(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
293}
294
295#[test] fn thin_zeroed() {
296    thin::test::zeroed_alloc(create_test_heap(None, None));
297    thin::test::zeroed_alloc(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
298}
299
300#[test] fn thin_zeroed_realloc() {
301    thin::test::zeroed_realloc(create_test_heap(None, None));
302    thin::test::zeroed_realloc(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
303}
304
305#[test] fn thin_zst_support() {
306    thin::test::zst_supported_accurate(create_test_heap(None, None));
307    thin::test::zst_supported_accurate(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
308}
309
310
311
312#[test] fn fat_alignment() {
313    fat::test::alignment(create_test_heap(None, None));
314    fat::test::alignment(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
315}
316
317#[test] fn fat_edge_case_sizes() {
318    fat::test::edge_case_sizes(create_test_heap(None, None));
319    fat::test::edge_case_sizes(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
320}
321
322#[test] fn fat_uninit() {
323    unsafe { fat::test::uninit_alloc_unsound(create_test_heap(None, None)) };
324    unsafe { fat::test::uninit_alloc_unsound(create_test_heap(None, NonZeroUsize::new(1024 * 1024))) };
325}
326
327#[test] fn fat_uninit_realloc() {
328    fat::test::uninit_realloc(create_test_heap(None, None));
329    fat::test::uninit_realloc(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
330}
331
332#[test] fn fat_zeroed() {
333    fat::test::zeroed_alloc(create_test_heap(None, None));
334    fat::test::zeroed_alloc(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
335}
336
337#[test] fn fat_zeroed_realloc() {
338    fat::test::zeroed_realloc(create_test_heap(None, None));
339    fat::test::zeroed_realloc(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
340}
341
342#[test] fn fat_zst_support() {
343    fat::test::zst_supported_accurate(create_test_heap(None, None));
344    fat::test::zst_supported_accurate(create_test_heap(None, NonZeroUsize::new(1024 * 1024)));
345}