Skip to content

Commit 27a6e6e

Browse files
committed
Wrap HeapAlloc and never inline
1 parent d9d89fd commit 27a6e6e

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

library/std/src/sys/pal/windows/alloc.rs

+13-11
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ static HEAP: AtomicPtr<c_void> = AtomicPtr::new(ptr::null_mut());
9595
#[inline]
9696
fn init_or_get_process_heap() -> c::HANDLE {
9797
let heap = HEAP.load(Ordering::Relaxed);
98-
if heap.is_null() {
98+
if core::intrinsics::unlikely(heap.is_null()) {
9999
// `HEAP` has not yet been successfully initialized
100100
let heap = unsafe { GetProcessHeap() };
101101
if !heap.is_null() {
@@ -115,6 +115,16 @@ fn init_or_get_process_heap() -> c::HANDLE {
115115
}
116116
}
117117

118+
#[inline(never)]
119+
fn process_heap_alloc(flags: c::DWORD, dwBytes: c::SIZE_T) -> c::LPVOID {
120+
let heap = init_or_get_process_heap();
121+
if core::intrinsics::unlikely(heap.is_null()) {
122+
return ptr::null_mut();
123+
}
124+
// SAFETY: `heap` is a non-null handle returned by `GetProcessHeap`.
125+
unsafe { HeapAlloc(heap, flags, dwBytes) }
126+
}
127+
118128
// Get a non-null handle to the default heap of the current process.
119129
// SAFETY: `HEAP` must have been successfully initialized.
120130
#[inline]
@@ -133,25 +143,17 @@ struct Header(*mut u8);
133143
// initialized.
134144
#[inline]
135145
unsafe fn allocate(layout: Layout, zeroed: bool) -> *mut u8 {
136-
let heap = init_or_get_process_heap();
137-
if heap.is_null() {
138-
// Allocation has failed, could not get the current process heap.
139-
return ptr::null_mut();
140-
}
141-
142146
// Allocated memory will be either zeroed or uninitialized.
143147
let flags = if zeroed { HEAP_ZERO_MEMORY } else { 0 };
144148

145149
if layout.align() <= MIN_ALIGN {
146-
// SAFETY: `heap` is a non-null handle returned by `GetProcessHeap`.
147150
// The returned pointer points to the start of an allocated block.
148-
unsafe { HeapAlloc(heap, flags, layout.size()) as *mut u8 }
151+
process_heap_alloc(flags, layout.size()) as *mut u8
149152
} else {
150153
// Allocate extra padding in order to be able to satisfy the alignment.
151154
let total = layout.align() + layout.size();
152155

153-
// SAFETY: `heap` is a non-null handle returned by `GetProcessHeap`.
154-
let ptr = unsafe { HeapAlloc(heap, flags, total) as *mut u8 };
156+
let ptr = process_heap_alloc(flags, total) as *mut u8;
155157
if ptr.is_null() {
156158
// Allocation has failed.
157159
return ptr::null_mut();

0 commit comments

Comments
 (0)