use std::{
ops::{Bound, Range, RangeBounds},
os::windows::raw::HANDLE,
ptr,
};
use windows_sys::Win32::System::Memory::{
MEM_ADDRESS_REQUIREMENTS, MEM_EXTENDED_PARAMETER, MemExtendedParameterAddressRequirements,
PAGE_PROTECTION_FLAGS, VIRTUAL_ALLOCATION_TYPE, VirtualAlloc, VirtualAlloc2,
};
use crate::{address::AsAddress, system};
pub trait AllocBounds<A: AsAddress>: RangeBounds<A> {
fn as_alloc_bounds(&self) -> (usize, usize);
fn is_unbounded(&self) -> bool;
}
impl<R: RangeBounds<A>, A: AsAddress> AllocBounds<A> for R {
fn as_alloc_bounds(&self) -> (usize, usize) {
let low_addr = match self.start_bound() {
Bound::Unbounded => 0,
Bound::Excluded(bound) => bound.as_addr().saturating_add(1),
Bound::Included(bound) => bound.as_addr(),
};
let high_addr = match self.end_bound() {
Bound::Unbounded => usize::MAX,
Bound::Excluded(bound) => bound.as_addr(),
Bound::Included(bound) => bound.as_addr().saturating_add(1),
};
(low_addr, high_addr)
}
fn is_unbounded(&self) -> bool {
matches!(
(self.start_bound(), self.end_bound()),
(Bound::Unbounded, Bound::Unbounded)
)
}
}
pub fn try_alloc_in_bounds<B: AllocBounds<A>, A: AsAddress>(
bounds: B,
size: usize,
alloc_type: VIRTUAL_ALLOCATION_TYPE,
protection_flags: PAGE_PROTECTION_FLAGS,
) -> Option<Range<*mut u8>> {
let system_info = system::get_info();
unsafe {
try_alloc_in_bounds_unchecked(
bounds,
size,
alloc_type,
protection_flags,
system_info.dwAllocationGranularity as usize,
system_info.dwPageSize as usize,
)
}
}
pub unsafe fn try_alloc_in_bounds_unchecked<B: AllocBounds<A>, A: AsAddress>(
bounds: B,
size: usize,
alloc_type: VIRTUAL_ALLOCATION_TYPE,
protection_flags: PAGE_PROTECTION_FLAGS,
alloc_granularity: usize,
page_size: usize,
) -> Option<Range<*mut u8>> {
let alloc_size = size.next_multiple_of(page_size);
let alloc = if bounds.is_unbounded() {
unsafe { VirtualAlloc(ptr::null(), alloc_size, alloc_type, protection_flags) }
} else {
let (low_addr, high_addr) = bounds.as_alloc_bounds();
let low_alloc_addr = low_addr
.saturating_sub(alloc_granularity - 1)
.next_multiple_of(alloc_granularity);
let high_alloc_addr = match high_addr % alloc_granularity {
0 => high_addr.saturating_sub(1),
r => (high_addr - r)
.checked_add(alloc_granularity)
.unwrap_or(high_addr - r)
.saturating_sub(1),
};
let mut address_requirements = MEM_ADDRESS_REQUIREMENTS {
LowestStartingAddress: low_alloc_addr as _,
HighestEndingAddress: high_alloc_addr as _,
Alignment: alloc_granularity,
};
let mut extended_parameters = MEM_EXTENDED_PARAMETER::default();
extended_parameters.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as _;
extended_parameters.Anonymous2.Pointer = &raw mut address_requirements as _;
unsafe {
VirtualAlloc2(
HANDLE::default(),
ptr::null_mut(),
alloc_size,
alloc_type,
protection_flags,
&mut extended_parameters,
1,
)
}
} as *mut u8;
(!alloc.is_null()).then(|| unsafe { alloc..alloc.add(alloc_size) })
}