use core::ffi::{c_char, c_int, c_void};
use core::mem::MaybeUninit;
use crate::mem::macos::Region;
use crate::mem::unix::AccessPattern;
use crate::mem::{Advice, MapOptions, Place, Protection, Sharing};
use crate::sys::{cvt, last_error};
use crate::{AsHandle, BorrowedHandle, ErrorKind, OwnedHandle, Result};
unsafe extern "C" {
fn getpagesize() -> c_int;
fn mmap(
addr: *mut c_void,
len: usize,
prot: c_int,
flags: c_int,
fd: c_int,
offset: i64,
) -> *mut c_void;
fn munmap(addr: *mut c_void, len: usize) -> c_int;
fn mprotect(addr: *mut c_void, len: usize, prot: c_int) -> c_int;
fn msync(addr: *mut c_void, len: usize, flags: c_int) -> c_int;
fn madvise(addr: *mut c_void, len: usize, advice: c_int) -> c_int;
fn mlock(addr: *const c_void, len: usize) -> c_int;
fn munlock(addr: *const c_void, len: usize) -> c_int;
fn sys_icache_invalidate(start: *mut c_void, len: usize);
fn pthread_jit_write_protect_supported_np() -> c_int;
fn pthread_jit_write_protect_np(enabled: c_int);
fn shm_open(name: *const c_char, flags: c_int, ...) -> c_int;
fn shm_unlink(name: *const c_char) -> c_int;
fn mach_vm_region(
task: u32,
address: *mut u64,
size: *mut u64,
flavor: c_int,
info: *mut c_int,
count: *mut u32,
object_name: *mut u32,
) -> c_int;
static mach_task_self_: u32;
}
const O_RDWR: c_int = 0x0002;
const O_CREAT: c_int = 0x0200;
const O_EXCL: c_int = 0x0800;
const F_SETFD: c_int = 2;
const FD_CLOEXEC: c_int = 1;
const VM_REGION_BASIC_INFO_64: c_int = 9;
const VM_REGION_BASIC_INFO_COUNT_64: usize = 9;
const KERN_SUCCESS: c_int = 0;
const KERN_INVALID_ADDRESS: c_int = 1;
const MADV_NORMAL: c_int = 0;
const MADV_RANDOM: c_int = 1;
const MADV_SEQUENTIAL: c_int = 2;
const PROT_NONE: c_int = 0;
const PROT_READ: c_int = 1;
const PROT_WRITE: c_int = 2;
const PROT_EXEC: c_int = 4;
const MAP_SHARED: c_int = 0x0001;
const MAP_PRIVATE: c_int = 0x0002;
const MAP_FIXED: c_int = 0x0010;
const MAP_NORESERVE: c_int = 0x0040;
const MAP_JIT: c_int = 0x0800;
const MAP_ANON: c_int = 0x1000;
const MAP_FAILED: *mut c_void = !0 as *mut c_void;
const MS_SYNC: c_int = 0x0010;
pub(crate) const EXTRA_JIT: u32 = 1;
fn extra(options: &MapOptions) -> c_int {
if options.extra & EXTRA_JIT != 0 {
MAP_JIT
} else {
0
}
}
const MADV_WILLNEED: c_int = 3;
const MADV_FREE: c_int = 5;
pub(crate) fn page_size() -> usize {
unsafe { getpagesize() as usize }
}
pub(crate) fn allocation_granularity() -> usize {
page_size()
}
unsafe fn map(
addr: *mut u8,
len: usize,
prot: c_int,
flags: c_int,
fd: c_int,
offset: u64,
) -> Result<*mut u8> {
let Ok(offset) = i64::try_from(offset) else {
return Err(ErrorKind::InvalidInput.into());
};
let ptr = unsafe { mmap(addr.cast(), len, prot, flags, fd, offset) };
if ptr == MAP_FAILED {
Err(last_error())
} else {
Ok(ptr.cast())
}
}
fn prot(protection: Protection) -> c_int {
let mut prot = PROT_NONE;
if protection.contains(Protection::READ) {
prot |= PROT_READ;
}
if protection.contains(Protection::WRITE) {
prot |= PROT_WRITE;
}
if protection.contains(Protection::EXECUTE) {
prot |= PROT_EXEC;
}
prot
}
fn map_placed(
place: Place,
len: usize,
prot: c_int,
flags: c_int,
fd: c_int,
offset: u64,
) -> Result<*mut u8> {
match place {
Place::Anywhere => unsafe { map(core::ptr::null_mut(), len, prot, flags, fd, offset) },
Place::At(addr) => {
let ptr = unsafe { map(addr as *mut u8, len, prot, flags, fd, offset) }?;
if ptr.addr() != addr {
unsafe { munmap(ptr.cast(), len) };
return Err(ErrorKind::AlreadyExists.into());
}
Ok(ptr)
}
Place::In(addr) => {
let result = unsafe { map(addr as *mut u8, len, prot, flags | MAP_FIXED, fd, offset) };
if result.is_err() {
let _ = unsafe {
map(
addr as *mut u8,
len,
PROT_NONE,
MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED,
-1,
0,
)
};
}
result
}
}
}
pub(crate) fn map_anonymous(len: usize, options: &MapOptions) -> Result<*mut u8> {
map_placed(
options.place,
len,
prot(options.protection),
MAP_PRIVATE | MAP_ANON | extra(options),
-1,
0,
)
}
pub(crate) fn map_file(
file: BorrowedHandle<'_>,
offset: u64,
len: usize,
sharing: Sharing,
options: &MapOptions,
) -> Result<*mut u8> {
let flags = match sharing {
Sharing::Shared => MAP_SHARED,
Sharing::Private => MAP_PRIVATE,
};
map_placed(
options.place,
len,
prot(options.protection),
flags | extra(options),
file.as_raw(),
offset,
)
}
pub(crate) fn reserve(len: usize, options: &MapOptions, _placeholder: bool) -> Result<*mut u8> {
map_placed(
options.place,
len,
PROT_NONE,
MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | extra(options),
-1,
0,
)
}
pub(crate) unsafe fn unmap(ptr: *mut u8, len: usize) -> Result<()> {
cvt(unsafe { munmap(ptr.cast(), len) }).map(drop)
}
pub(crate) unsafe fn protect(ptr: *mut u8, len: usize, protection: Protection) -> Result<()> {
cvt(unsafe { mprotect(ptr.cast(), len, prot(protection)) }).map(drop)
}
pub(crate) unsafe fn commit(ptr: *mut u8, len: usize, protection: Protection) -> Result<()> {
unsafe { protect(ptr, len, protection) }
}
pub(crate) unsafe fn decommit(ptr: *mut u8, len: usize) -> Result<()> {
unsafe {
map(
ptr,
len,
PROT_NONE,
MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED,
-1,
0,
)
}
.map(drop)
}
pub(crate) unsafe fn advise(ptr: *mut u8, len: usize, advice: Advice) -> Result<()> {
let advice = match advice {
Advice::WillNeed => MADV_WILLNEED,
Advice::Discard => MADV_FREE,
};
cvt(unsafe { madvise(ptr.cast(), len, advice) }).map(drop)
}
pub(crate) fn flush(ptr: *const u8, len: usize, _file: BorrowedHandle<'_>) -> Result<()> {
cvt(unsafe { msync(ptr.cast_mut().cast(), len, MS_SYNC) }).map(drop)
}
pub(crate) fn lock(ptr: *const u8, len: usize) -> Result<()> {
cvt(unsafe { mlock(ptr.cast(), len) }).map(drop)
}
pub(crate) fn unlock(ptr: *const u8, len: usize) -> Result<()> {
cvt(unsafe { munlock(ptr.cast(), len) }).map(drop)
}
pub(crate) unsafe fn flush_instruction_cache(ptr: *const u8, len: usize) -> Result<()> {
unsafe { sys_icache_invalidate(ptr.cast_mut().cast(), len) };
Ok(())
}
pub(crate) fn jit_write_protect_supported() -> bool {
unsafe { pthread_jit_write_protect_supported_np() != 0 }
}
pub(crate) unsafe fn jit_write_protect(protect: bool) {
unsafe { pthread_jit_write_protect_np(protect as c_int) };
}
pub(crate) fn create_shared(len: usize) -> Result<OwnedHandle> {
let mut random = [MaybeUninit::<u8>::uninit(); 8];
crate::sys::rand::fill(&mut random)?;
let mut name = *b"/oscall-0000000000000000\0";
for (index, byte) in random.iter().enumerate() {
let byte = unsafe { byte.assume_init() };
name[8 + 2 * index] = b"0123456789abcdef"[(byte >> 4) as usize];
name[9 + 2 * index] = b"0123456789abcdef"[(byte & 15) as usize];
}
let name = name.as_ptr().cast::<c_char>();
let fd = cvt(unsafe { shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0o600 as c_int) })?;
let handle = unsafe { OwnedHandle::from_raw(fd) };
unsafe { shm_unlink(name) };
cvt(unsafe { crate::sys::io::fcntl(fd, F_SETFD, FD_CLOEXEC) })?;
crate::sys::fs::set_len(handle.as_handle(), len as u64)?;
Ok(handle)
}
pub(crate) fn advise_access(ptr: *const u8, len: usize, pattern: AccessPattern) -> Result<()> {
let advice = match pattern {
AccessPattern::Normal => MADV_NORMAL,
AccessPattern::Sequential => MADV_SEQUENTIAL,
AccessPattern::Random => MADV_RANDOM,
};
cvt(unsafe { madvise(ptr.cast_mut().cast(), len, advice) }).map(drop)
}
fn protection(prot: c_int) -> Protection {
let mut protection = Protection::NONE;
if prot & PROT_READ != 0 {
protection |= Protection::READ;
}
if prot & PROT_WRITE != 0 {
protection |= Protection::WRITE;
}
if prot & PROT_EXEC != 0 {
protection |= Protection::EXECUTE;
}
protection
}
pub(crate) fn query(ptr: *const u8) -> Result<Option<Region>> {
let mut address = ptr.addr() as u64;
let mut size = 0u64;
let mut info = [0 as c_int; VM_REGION_BASIC_INFO_COUNT_64];
let mut count = VM_REGION_BASIC_INFO_COUNT_64 as u32;
let mut object_name = 0u32;
let result = unsafe {
mach_vm_region(
mach_task_self_,
&mut address,
&mut size,
VM_REGION_BASIC_INFO_64,
info.as_mut_ptr(),
&mut count,
&mut object_name,
)
};
match result {
KERN_SUCCESS => {}
KERN_INVALID_ADDRESS => return Ok(None),
_ => return Err(ErrorKind::Other.into()),
}
if address > ptr.addr() as u64 {
return Ok(None);
}
Ok(Some(Region {
base: ptr.with_addr(address as usize).cast_mut(),
len: size as usize,
protection: protection(info[0]),
max_protection: protection(info[1]),
}))
}