| 1 |
use super::*; |
| 2 |
|
| 3 |
/// Allocate memory of size `bytes` using `HeapAlloc`. |
| 4 |
/// |
| 5 |
/// The memory allocated by this function is uninitialized. |
| 6 |
/// |
| 7 |
/// This function will fail in OOM situations, if the heap is otherwise corrupt, |
| 8 |
/// or if getting a handle to the process heap fails. |
| 9 |
pub fn heap_alloc(bytes: usize) -> crate::Result<*mut std::ffi::c_void> { |
| 10 |
let ptr = unsafe { HeapAlloc(GetProcessHeap(), 0, bytes) }; |
| 11 |
|
| 12 |
if ptr.is_null() { |
| 13 |
Err(E_OUTOFMEMORY.into()) |
| 14 |
} else { |
| 15 |
// HeapAlloc is not guaranteed to return zero memory but usually does. This just ensures that |
| 16 |
// it predictably returns non-zero memory for testing purposes. This is similar to what MSVC's |
| 17 |
// debug allocator does for the same reason. |
| 18 |
#[cfg(debug_assertions)] |
| 19 |
unsafe { |
| 20 |
std::ptr::write_bytes(ptr, 0xCC, bytes); |
| 21 |
} |
| 22 |
Ok(ptr) |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
/// Free memory allocated by `HeapAlloc` or `HeapReAlloc`. |
| 27 |
/// |
| 28 |
/// The pointer is allowed to be null. |
| 29 |
/// |
| 30 |
/// # Safety |
| 31 |
/// |
| 32 |
/// `ptr` must be a valid pointer to memory allocated by `HeapAlloc` or `HeapReAlloc` |
| 33 |
pub unsafe fn heap_free(ptr: *mut std::ffi::c_void) { |
| 34 |
HeapFree(GetProcessHeap(), 0, ptr); |
| 35 |
} |