use core::ffi::CStr;
use core::ffi::c_void;
use core::mem::MaybeUninit;
use core::ptr::{null, null_mut};
use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
use crate::mem::windows::{Region, RegionState};
use crate::mem::{Advice, MapOptions, Place, Protection, Sharing};
use crate::sys::{RawHandle, cvt, dll, last_error};
use crate::{BorrowedHandle, ErrorKind, OwnedHandle, Result};
#[repr(C)]
struct SystemInfo {
_oem_id: u32,
page_size: u32,
_minimum_application_address: *mut c_void,
_maximum_application_address: *mut c_void,
_active_processor_mask: usize,
_number_of_processors: u32,
_processor_type: u32,
allocation_granularity: u32,
_processor_level: u16,
_processor_revision: u16,
}
#[repr(C)]
struct MemoryBasicInformation {
base_address: *mut c_void,
allocation_base: *mut c_void,
_allocation_protect: usize,
region_size: usize,
state: u32,
protect: u32,
kind: u32,
}
#[repr(C)]
struct UnicodeString {
length: u16,
_maximum_length: u16,
buffer: *const u16,
}
dll!("ntdll.dll" {
fn NtQueryObject(
handle: RawHandle,
class: u32,
info: *mut c_void,
len: u32,
returned: *mut u32,
) -> i32;
});
const OBJECT_TYPE_INFORMATION: u32 = 2;
#[repr(C)]
struct MemoryRangeEntry {
virtual_address: *mut c_void,
number_of_bytes: usize,
}
dll!("kernel32.dll" {
fn GetSystemInfo(info: *mut SystemInfo);
fn GetLargePageMinimum() -> usize;
fn GetCurrentProcess() -> RawHandle;
fn VirtualAlloc(addr: *mut c_void, size: usize, kind: u32, protect: u32) -> *mut c_void;
fn VirtualFree(addr: *mut c_void, size: usize, kind: u32) -> i32;
fn VirtualProtect(addr: *mut c_void, size: usize, protect: u32, old: *mut u32) -> i32;
fn VirtualQuery(addr: *const c_void, info: *mut MemoryBasicInformation, len: usize) -> usize;
fn VirtualLock(addr: *mut c_void, size: usize) -> i32;
fn VirtualUnlock(addr: *mut c_void, size: usize) -> i32;
fn PrefetchVirtualMemory(
process: RawHandle,
entries: usize,
ranges: *mut MemoryRangeEntry,
flags: u32,
) -> i32;
fn CreateFileMappingW(
file: RawHandle,
attributes: *mut c_void,
protect: u32,
maximum_size_high: u32,
maximum_size_low: u32,
name: *const u16,
) -> RawHandle;
fn MapViewOfFileEx(
mapping: RawHandle,
access: u32,
offset_high: u32,
offset_low: u32,
size: usize,
base: *mut c_void,
) -> *mut c_void;
fn GetModuleHandleW(name: *const u16) -> *mut c_void;
fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void;
fn UnmapViewOfFile(addr: *const c_void) -> i32;
fn UnmapViewOfFileEx(addr: *mut c_void, flags: u32) -> i32;
fn FlushViewOfFile(addr: *const c_void, size: usize) -> i32;
fn FlushFileBuffers(file: RawHandle) -> i32;
fn FlushInstructionCache(process: RawHandle, addr: *const c_void, size: usize) -> i32;
fn CloseHandle(handle: RawHandle) -> i32;
});
const INVALID_HANDLE_VALUE: RawHandle = -1isize as RawHandle;
const ERROR_INVALID_PARAMETER: i32 = 87;
const ERROR_INVALID_ADDRESS: i32 = 487;
const MEM_COMMIT: u32 = 0x1000;
const MEM_RESERVE: u32 = 0x2000;
const MEM_DECOMMIT: u32 = 0x4000;
const MEM_RELEASE: u32 = 0x8000;
const MEM_FREE: u32 = 0x1_0000;
const MEM_MAPPED: u32 = 0x4_0000;
const MEM_RESET: u32 = 0x8_0000;
const MEM_IMAGE: u32 = 0x100_0000;
const MEM_LARGE_PAGES: u32 = 0x2000_0000;
pub(crate) const EXTRA_LARGE_PAGES: u32 = 1;
pub(crate) fn large_page_size() -> usize {
unsafe { GetLargePageMinimum() }
}
const MEM_COALESCE_PLACEHOLDERS: u32 = 0x1;
const MEM_PRESERVE_PLACEHOLDER: u32 = 0x2;
const MEM_REPLACE_PLACEHOLDER: u32 = 0x4000;
const MEM_RESERVE_PLACEHOLDER: u32 = 0x4_0000;
const PAGE_NOACCESS: u32 = 0x01;
const PAGE_READONLY: u32 = 0x02;
const PAGE_READWRITE: u32 = 0x04;
const PAGE_WRITECOPY: u32 = 0x08;
const PAGE_EXECUTE: u32 = 0x10;
const PAGE_EXECUTE_READ: u32 = 0x20;
const PAGE_EXECUTE_READWRITE: u32 = 0x40;
const PAGE_EXECUTE_WRITECOPY: u32 = 0x80;
const FILE_MAP_COPY: u32 = 0x01;
const FILE_MAP_WRITE: u32 = 0x02;
const FILE_MAP_READ: u32 = 0x04;
const FILE_MAP_EXECUTE: u32 = 0x20;
static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
static GRANULARITY: AtomicUsize = AtomicUsize::new(0);
#[cold]
fn system_info() -> (usize, usize) {
let mut info = MaybeUninit::<SystemInfo>::zeroed();
let info = unsafe {
GetSystemInfo(info.as_mut_ptr());
info.assume_init()
};
let sizes = (
info.page_size as usize,
info.allocation_granularity as usize,
);
PAGE_SIZE.store(sizes.0, Ordering::Relaxed);
GRANULARITY.store(sizes.1, Ordering::Relaxed);
sizes
}
pub(crate) fn page_size() -> usize {
match PAGE_SIZE.load(Ordering::Relaxed) {
0 => system_info().0,
size => size,
}
}
pub(crate) fn allocation_granularity() -> usize {
match GRANULARITY.load(Ordering::Relaxed) {
0 => system_info().1,
size => size,
}
}
fn page(protection: Protection) -> u32 {
let read = protection.contains(Protection::READ);
let write = protection.contains(Protection::WRITE);
let execute = protection.contains(Protection::EXECUTE);
match (execute, write, read) {
(false, false, false) => PAGE_NOACCESS,
(false, false, true) => PAGE_READONLY,
(false, true, _) => PAGE_READWRITE,
(true, false, false) => PAGE_EXECUTE,
(true, false, true) => PAGE_EXECUTE_READ,
(true, true, _) => PAGE_EXECUTE_READWRITE,
}
}
fn cvt_ptr(ptr: *mut c_void) -> Result<*mut u8> {
if ptr.is_null() {
Err(last_error())
} else {
Ok(ptr.cast())
}
}
type VirtualAlloc2Fn = unsafe extern "system" fn(
process: RawHandle,
base: *mut c_void,
size: usize,
kind: u32,
protect: u32,
parameters: *mut c_void,
count: u32,
) -> *mut c_void;
type MapViewOfFile3Fn = unsafe extern "system" fn(
mapping: RawHandle,
process: RawHandle,
base: *mut c_void,
offset: u64,
size: usize,
kind: u32,
protect: u32,
parameters: *mut c_void,
count: u32,
) -> *mut c_void;
static KERNELBASE: [u16; 15] = {
let ascii = b"kernelbase.dll\0";
let mut wide = [0; 15];
let mut i = 0;
while i < wide.len() {
wide[i] = ascii[i] as u16;
i += 1;
}
wide
};
static VIRTUAL_ALLOC2: AtomicPtr<c_void> = AtomicPtr::new(null_mut());
static MAP_VIEW_OF_FILE3: AtomicPtr<c_void> = AtomicPtr::new(null_mut());
fn optional(cache: &AtomicPtr<c_void>, name: &CStr) -> Result<*mut c_void> {
let known = cache.load(Ordering::Relaxed);
if !known.is_null() {
return Ok(known);
}
let function = unsafe {
let kernelbase = GetModuleHandleW(KERNELBASE.as_ptr());
if kernelbase.is_null() {
return Err(ErrorKind::Unsupported.into());
}
GetProcAddress(kernelbase, name.as_ptr().cast())
};
if function.is_null() {
return Err(ErrorKind::Unsupported.into());
}
cache.store(function, Ordering::Relaxed);
Ok(function)
}
fn virtual_alloc2() -> Result<VirtualAlloc2Fn> {
let function = optional(&VIRTUAL_ALLOC2, c"VirtualAlloc2")?;
Ok(unsafe { core::mem::transmute::<*mut c_void, VirtualAlloc2Fn>(function) })
}
fn map_view_of_file3() -> Result<MapViewOfFile3Fn> {
let function = optional(&MAP_VIEW_OF_FILE3, c"MapViewOfFile3")?;
Ok(unsafe { core::mem::transmute::<*mut c_void, MapViewOfFile3Fn>(function) })
}
fn query(addr: *const u8) -> Result<MemoryBasicInformation> {
let mut info = MaybeUninit::<MemoryBasicInformation>::zeroed();
unsafe {
if VirtualQuery(addr.cast(), info.as_mut_ptr(), size_of_val(&info)) == 0 {
return Err(last_error());
}
Ok(info.assume_init())
}
}
fn placed(result: Result<*mut u8>) -> Result<*mut u8> {
match result {
Err(error) if error.raw_os_error() == ERROR_INVALID_ADDRESS => {
Err(ErrorKind::AlreadyExists.into())
}
result => result,
}
}
fn base(place: Place) -> *mut c_void {
match place {
Place::Anywhere => null_mut(),
Place::At(addr) | Place::In(addr) => addr as *mut c_void,
}
}
unsafe fn in_placeholder(
addr: usize,
len: usize,
replace: impl FnOnce(*mut c_void, usize) -> Result<*mut u8>,
) -> Result<*mut u8> {
let len = len.next_multiple_of(page_size());
let end = addr + len;
let info = query(addr as *const u8)?;
let whole = info.allocation_base as usize;
let whole_end = (info.base_address as usize).saturating_add(info.region_size);
if info.state != MEM_RESERVE || end > whole_end {
return Err(ErrorKind::InvalidInput.into());
}
let split = whole != addr || whole_end != end;
if split {
cvt(unsafe {
VirtualFree(
addr as *mut c_void,
len,
MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
)
})?;
}
let view = replace(addr as *mut c_void, len);
if view.is_err() && split {
unsafe {
VirtualFree(
whole as *mut c_void,
whole_end - whole,
MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS,
)
};
}
view
}
pub(crate) fn map_anonymous(len: usize, options: &MapOptions) -> Result<*mut u8> {
let protect = page(options.protection);
let large = options.extra & EXTRA_LARGE_PAGES != 0;
match options.place {
Place::Anywhere | Place::At(_) => {
let kind = MEM_RESERVE | MEM_COMMIT | if large { MEM_LARGE_PAGES } else { 0 };
placed(cvt_ptr(unsafe {
VirtualAlloc(base(options.place), len, kind, protect)
}))
}
Place::In(_) if large => Err(ErrorKind::InvalidInput.into()),
Place::In(addr) => {
let alloc = virtual_alloc2()?;
unsafe {
in_placeholder(addr, len, |base, size| {
cvt_ptr(alloc(
null_mut(),
base,
size,
MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER,
protect,
null_mut(),
0,
))
})
}
}
}
}
pub(crate) fn map_file(
file: BorrowedHandle<'_>,
offset: u64,
len: usize,
sharing: Sharing,
options: &MapOptions,
) -> Result<*mut u8> {
let protection = options.protection;
if options.extra & EXTRA_LARGE_PAGES != 0 {
return Err(ErrorKind::InvalidInput.into());
}
let file = file.as_raw();
if file == INVALID_HANDLE_VALUE {
return Err(ErrorKind::BadHandle.into());
}
let write = protection.contains(Protection::WRITE);
let execute = protection.contains(Protection::EXECUTE);
let (section, mut access, granted) = match (sharing, write, execute) {
(Sharing::Shared, false, false) => (PAGE_READONLY, FILE_MAP_READ, PAGE_READONLY),
(Sharing::Shared, false, true) => (PAGE_EXECUTE_READ, FILE_MAP_READ, PAGE_EXECUTE_READ),
(Sharing::Shared, true, false) => (
PAGE_READWRITE,
FILE_MAP_READ | FILE_MAP_WRITE,
PAGE_READWRITE,
),
(Sharing::Shared, true, true) => (
PAGE_EXECUTE_READWRITE,
FILE_MAP_READ | FILE_MAP_WRITE,
PAGE_EXECUTE_READWRITE,
),
(Sharing::Private, _, false) => (PAGE_WRITECOPY, FILE_MAP_COPY, PAGE_READWRITE),
(Sharing::Private, _, true) => (
PAGE_EXECUTE_WRITECOPY,
FILE_MAP_COPY,
PAGE_EXECUTE_READWRITE,
),
};
if execute {
access |= FILE_MAP_EXECUTE;
}
let wanted = page(protection);
let protect = |view: *mut u8, keep: u32| {
if wanted != granted {
let mut old = 0;
if let Err(error) = cvt(unsafe { VirtualProtect(view.cast(), len, wanted, &mut old) }) {
unsafe { UnmapViewOfFileEx(view.cast(), keep) };
return Err(error);
}
}
Ok(view)
};
let map3 = match options.place {
Place::In(_) => Some(map_view_of_file3()?),
_ => None,
};
let created = unsafe { CreateFileMappingW(file, null_mut(), section, 0, 0, null()) };
let mapping = if created.is_null() {
let error = last_error();
if !is_section(file) {
return Err(error);
}
file
} else {
created
};
let view = match (options.place, map3) {
(Place::In(addr), Some(map3)) => {
unsafe {
in_placeholder(addr, len, |base, _| {
let view = cvt_ptr(map3(
mapping,
GetCurrentProcess(),
base,
offset,
len,
MEM_REPLACE_PLACEHOLDER,
section,
null_mut(),
0,
))?;
protect(view, MEM_PRESERVE_PLACEHOLDER)
})
}
}
_ => placed(cvt_ptr(unsafe {
MapViewOfFileEx(
mapping,
access,
(offset >> 32) as u32,
offset as u32,
len,
base(options.place),
)
}))
.and_then(|view| protect(view, 0)),
};
if !created.is_null() {
unsafe { CloseHandle(created) };
}
view
}
fn is_section(handle: RawHandle) -> bool {
let mut info = [0u64; 64];
let mut returned = 0;
let status = unsafe {
NtQueryObject(
handle,
OBJECT_TYPE_INFORMATION,
info.as_mut_ptr().cast(),
size_of_val(&info) as u32,
&mut returned,
)
};
if status < 0 {
return false;
}
let name = unsafe {
let name = &*info.as_ptr().cast::<UnicodeString>();
if name.buffer.is_null() {
return false;
}
core::slice::from_raw_parts(name.buffer, name.length as usize / 2)
};
name.iter().copied().eq("Section".encode_utf16())
}
pub(crate) fn create_shared(len: usize) -> Result<OwnedHandle> {
let len = len as u64;
let section = unsafe {
CreateFileMappingW(
INVALID_HANDLE_VALUE,
null_mut(),
PAGE_READWRITE,
(len >> 32) as u32,
len as u32,
null(),
)
};
if section.is_null() {
return Err(last_error());
}
Ok(unsafe { OwnedHandle::from_raw(section) })
}
pub(crate) fn query_region(ptr: *const u8) -> Result<Region> {
let info = query(ptr)?;
let state = match info.state {
MEM_FREE => RegionState::Free,
MEM_RESERVE => RegionState::Reserved,
MEM_COMMIT => RegionState::Committed,
_ => return Err(ErrorKind::Other.into()),
};
let protection = match info.protect & 0xff {
PAGE_READONLY => Protection::READ,
PAGE_READWRITE | PAGE_WRITECOPY => Protection::READ_WRITE,
PAGE_EXECUTE => Protection::EXECUTE,
PAGE_EXECUTE_READ => Protection::READ_EXECUTE,
PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY => {
Protection::READ_WRITE | Protection::EXECUTE
}
_ => Protection::NONE,
};
Ok(Region {
base: info.base_address.cast(),
len: info.region_size,
state,
protection,
allocation_base: info.allocation_base.cast(),
})
}
pub(crate) fn reserve(len: usize, options: &MapOptions, placeholder: bool) -> Result<*mut u8> {
if options.extra & EXTRA_LARGE_PAGES != 0 {
return Err(ErrorKind::InvalidInput.into());
}
let base = base(options.place);
if placeholder {
let alloc = virtual_alloc2()?;
placed(cvt_ptr(unsafe {
alloc(
null_mut(),
base,
len,
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
PAGE_NOACCESS,
null_mut(),
0,
)
}))
} else {
placed(cvt_ptr(unsafe {
VirtualAlloc(base, len, MEM_RESERVE, PAGE_NOACCESS)
}))
}
}
pub(crate) unsafe fn unmap(ptr: *mut u8, _len: usize) -> Result<()> {
let info = query(ptr)?;
if info.state == MEM_FREE || info.allocation_base != ptr.cast() {
return Err(ErrorKind::InvalidInput.into());
}
if info.kind == MEM_MAPPED || info.kind == MEM_IMAGE {
cvt(unsafe { UnmapViewOfFile(ptr.cast()) })
} else {
cvt(unsafe { VirtualFree(ptr.cast(), 0, MEM_RELEASE) })
}
}
pub(crate) unsafe fn protect(ptr: *mut u8, len: usize, protection: Protection) -> Result<()> {
let mut old = 0;
let wanted = page(protection);
let result = cvt(unsafe { VirtualProtect(ptr.cast(), len, wanted, &mut old) });
let copy = match wanted {
PAGE_READWRITE => PAGE_WRITECOPY,
PAGE_EXECUTE_READWRITE => PAGE_EXECUTE_WRITECOPY,
_ => return result,
};
match result {
Err(error) if error.raw_os_error() == ERROR_INVALID_PARAMETER => {
cvt(unsafe { VirtualProtect(ptr.cast(), len, copy, &mut old) })
}
result => result,
}
}
pub(crate) unsafe fn commit(ptr: *mut u8, len: usize, protection: Protection) -> Result<()> {
cvt_ptr(unsafe { VirtualAlloc(ptr.cast(), len, MEM_COMMIT, page(protection)) }).map(drop)
}
pub(crate) unsafe fn decommit(ptr: *mut u8, len: usize) -> Result<()> {
cvt(unsafe { VirtualFree(ptr.cast(), len, MEM_DECOMMIT) })
}
pub(crate) unsafe fn advise(ptr: *mut u8, len: usize, advice: Advice) -> Result<()> {
match advice {
Advice::WillNeed => {
let mut range = MemoryRangeEntry {
virtual_address: ptr.cast(),
number_of_bytes: len,
};
cvt(unsafe { PrefetchVirtualMemory(GetCurrentProcess(), 1, &mut range, 0) })
}
Advice::Discard => {
let Some(len) = len.checked_next_multiple_of(page_size()) else {
return Err(ErrorKind::InvalidInput.into());
};
cvt_ptr(unsafe { VirtualAlloc(ptr.cast(), len, MEM_RESET, PAGE_NOACCESS) }).map(drop)
}
}
}
pub(crate) fn flush(ptr: *const u8, len: usize, file: BorrowedHandle<'_>) -> Result<()> {
cvt(unsafe { FlushViewOfFile(ptr.cast(), len) })?;
cvt(unsafe { FlushFileBuffers(file.as_raw()) })
}
pub(crate) fn lock(ptr: *const u8, len: usize) -> Result<()> {
cvt(unsafe { VirtualLock(ptr.cast_mut().cast(), len) })
}
pub(crate) fn unlock(ptr: *const u8, len: usize) -> Result<()> {
cvt(unsafe { VirtualUnlock(ptr.cast_mut().cast(), len) })
}
pub(crate) unsafe fn flush_instruction_cache(ptr: *const u8, len: usize) -> Result<()> {
cvt(unsafe { FlushInstructionCache(GetCurrentProcess(), ptr.cast(), len) })
}