use lazy_static::lazy_static;
#[cfg(windows)]
use windows_sys::Win32;
mod alloc;
mod mem;
pub use alloc::*;
pub use mem::*;
lazy_static! {
pub static ref PAGE_SIZE: usize = {
#[cfg(unix)]
unsafe {
libc::sysconf(libc::_SC_PAGESIZE) as usize
}
#[cfg(windows)]
unsafe {
let mut sysconf = core::mem::MaybeUninit::uninit();
Win32::System::SystemInformation::GetSystemInfo(sysconf.as_mut_ptr());
(*sysconf.as_ptr()).dwPageSize as usize
}
};
}
#[cfg(unix)]
#[allow(non_snake_case, non_upper_case_globals)]
pub mod Prot {
pub type PF = libc::c_int;
pub const NoAccess: PF = libc::PROT_NONE;
pub const ReadOnly: PF = libc::PROT_READ;
pub const ReadWrite: PF = libc::PROT_READ | libc::PROT_WRITE;
}
#[cfg(windows)]
#[allow(non_snake_case, non_upper_case_globals)]
pub mod Prot {
use windows_sys::Win32;
pub type PF = Win32::System::Memory::PAGE_PROTECTION_FLAGS;
pub const NoAccess: PF = Win32::System::Memory::PAGE_NOACCESS;
pub const ReadOnly: PF = Win32::System::Memory::PAGE_READONLY;
pub const ReadWrite: PF = Win32::System::Memory::PAGE_READWRITE;
}
#[cfg(unix)]
#[inline]
unsafe fn __mprotect(start: *mut u8, n: usize, prot: Prot::PF) -> bool {
libc::mprotect(start.cast(), n, prot) == 0
}
#[cfg(windows)]
#[inline]
unsafe fn __mprotect(start: *mut u8, n: usize, prot: Prot::PF) -> bool {
let mut dump = std::mem::MaybeUninit::uninit();
let ret = Win32::System::Memory::VirtualProtect(start.cast(), n, prot, dump.as_mut_ptr());
dump.assume_init_drop();
ret != 0
}
pub unsafe fn mprotect(start: *mut u8, n: usize, prot: Prot::PF) -> bool {
__mprotect(start, n, prot)
}
pub unsafe fn mlock(start: *mut u8, n: usize) -> bool {
#[cfg(unix)]
{
#[cfg(target_os = "linux")]
libc::madvise(start.cast(), n, libc::MADV_DONTDUMP);
#[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
libc::madvise(start.cast(), n, libc::MADV_NOCORE);
libc::mlock(start.cast(), n) == 0
}
#[cfg(windows)]
{
Win32::System::Memory::VirtualLock(start.cast(), n) != 0
}
}
pub unsafe fn munlock(start: *mut u8, n: usize) -> bool {
#[cfg(unix)]
{
#[cfg(target_os = "linux")]
libc::madvise(start.cast(), n, libc::MADV_DODUMP);
#[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
libc::madvise(start.cast(), n, libc::MADV_DOCORE);
libc::munlock(start.cast(), n) == 0
}
#[cfg(windows)]
{
Win32::System::Memory::VirtualUnlock(start.cast(), n) != 0
}
}