use crate::error::{Error, Result};
use crate::{ImportKind, Symbol};
use core::ffi::{c_char, c_int, c_void};
use std::sync::OnceLock;
use mach2::dyld;
use mach2::kern_return::KERN_SUCCESS;
use mach2::traps::mach_task_self;
use mach2::vm::{mach_vm_protect, mach_vm_region};
use mach2::vm_prot::{VM_PROT_COPY, VM_PROT_EXECUTE, VM_PROT_READ, VM_PROT_WRITE};
use mach2::vm_region::{VM_REGION_BASIC_INFO_64, vm_region_basic_info_data_64_t};
fn kr_code(kr: c_int) -> u32 {
u32::from_ne_bytes(kr.to_ne_bytes())
}
fn rwx_mask() -> u32 {
u32::from_ne_bytes((VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE).to_ne_bytes())
}
fn as_vm_prot(protection: u32) -> c_int {
c_int::try_from(protection & rwx_mask()).unwrap_or(VM_PROT_READ)
}
pub(crate) fn page_size() -> usize {
static PAGE_SIZE: OnceLock<usize> = OnceLock::new();
*PAGE_SIZE.get_or_init(|| {
let size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
if size <= 0 {
0x4000
} else {
usize::try_from(size).unwrap_or(0x4000)
}
})
}
pub(crate) fn query_protection(address: usize) -> u32 {
let task = unsafe { mach_task_self() };
let mut region_addr = address as u64;
let mut region_size: u64 = 0;
let mut info: vm_region_basic_info_data_64_t = unsafe { core::mem::zeroed() };
let mut count = vm_region_basic_info_data_64_t::count();
let mut object_name: mach2::port::mach_port_t = 0;
let kr = unsafe {
mach_vm_region(
task,
&raw mut region_addr,
&raw mut region_size,
VM_REGION_BASIC_INFO_64,
(&raw mut info).cast::<c_int>(),
&raw mut count,
&raw mut object_name,
)
};
if kr != KERN_SUCCESS {
return 0;
}
let addr = address as u64;
if addr < region_addr || addr >= region_addr.saturating_add(region_size) {
return 0; }
u32::from_ne_bytes(info.protection.to_ne_bytes()) & rwx_mask()
}
pub(crate) unsafe fn make_writable(page: usize) -> Result<u32> {
let prot = query_protection(page);
if prot == 0 {
return Err(Error::Protect {
slot: page,
os_error: 0,
});
}
if prot & u32::from_ne_bytes(VM_PROT_WRITE.to_ne_bytes()) == 0 {
let task = unsafe { mach_task_self() };
let base = as_vm_prot(prot) | VM_PROT_READ | VM_PROT_WRITE;
let kr = unsafe {
mach_vm_protect(
task,
page as u64,
page_size() as u64,
0,
base | VM_PROT_COPY,
)
};
if kr != KERN_SUCCESS {
let kr2 = unsafe { mach_vm_protect(task, page as u64, page_size() as u64, 0, base) };
if kr2 != KERN_SUCCESS {
return Err(Error::Protect {
slot: page,
os_error: kr_code(kr2),
});
}
}
}
Ok(prot)
}
pub(crate) unsafe fn restore_protection(page: usize, protection: u32) -> Result<()> {
let task = unsafe { mach_task_self() };
let kr = unsafe {
mach_vm_protect(
task,
page as u64,
page_size() as u64,
0,
as_vm_prot(protection),
)
};
if kr != KERN_SUCCESS {
return Err(Error::Protect {
slot: page,
os_error: kr_code(kr),
});
}
Ok(())
}
pub(crate) fn module_still_loaded(base: usize) -> bool {
let count = unsafe { dyld::_dyld_image_count() };
(0..count).any(|i| unsafe { dyld::_dyld_get_image_header(i) } as usize == base)
}
pub(crate) fn slot_belongs_to_module(address: usize, module_base: usize) -> bool {
let count = unsafe { dyld::_dyld_image_count() };
for i in 0..count {
if unsafe { dyld::_dyld_get_image_header(i) } as usize != module_base {
continue;
}
let slide = unsafe { dyld::_dyld_get_image_vmaddr_slide(i) };
return image_contains(module_base, slide, address);
}
false
}
fn image_contains(header: usize, slide: isize, address: usize) -> bool {
const LC_SEGMENT_64: u32 = 0x19;
const MH_MAGIC_64: u32 = 0xfeed_facf;
const MAX_CMDS: u32 = 1 << 16;
let magic = unsafe { core::ptr::read_unaligned(header as *const u32) };
if magic != MH_MAGIC_64 {
return false;
}
let ncmds = unsafe { core::ptr::read_unaligned((header + 16) as *const u32) };
let sizeofcmds = unsafe { core::ptr::read_unaligned((header + 20) as *const u32) } as usize;
if ncmds > MAX_CMDS {
return false;
}
let cmds_end = header.saturating_add(32).saturating_add(sizeofcmds);
let mut cursor = header + 32;
for _ in 0..ncmds {
if cursor.saturating_add(8) > cmds_end {
break;
}
let cmd = unsafe { core::ptr::read_unaligned(cursor as *const u32) };
let cmdsize = unsafe { core::ptr::read_unaligned((cursor + 4) as *const u32) } as usize;
if cmdsize < 8 || cursor.saturating_add(cmdsize) > cmds_end {
break;
}
if cmd == LC_SEGMENT_64 && cmdsize >= 72 {
let vmaddr_u64 = unsafe { core::ptr::read_unaligned((cursor + 24) as *const u64) };
let vmsize_u64 = unsafe { core::ptr::read_unaligned((cursor + 32) as *const u64) };
let vmaddr = usize::try_from(vmaddr_u64).unwrap_or(usize::MAX);
let vmsize = usize::try_from(vmsize_u64).unwrap_or(0);
let start = vmaddr.wrapping_add_signed(slide);
let end = start.wrapping_add(vmsize);
if address >= start && address < end {
return true;
}
}
cursor = cursor.saturating_add(cmdsize);
}
false
}
pub(crate) fn resolve_original(
_kind: ImportKind,
_library: &str,
symbol: &Symbol,
slot_value: usize,
) -> Option<usize> {
let Symbol::Name(name) = symbol else {
return None;
};
if slot_value != 0 && dladdr_name_matches(slot_value, name) {
return Some(slot_value);
}
let mut c_name: Vec<u8> = name.as_bytes().to_vec();
c_name.push(0);
let ptr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c_name.as_ptr().cast::<c_char>()) };
if !ptr.is_null() {
return Some(ptr as usize);
}
(slot_value != 0).then_some(slot_value)
}
fn dladdr_name_matches(addr: usize, name: &str) -> bool {
let mut info: libc::Dl_info = unsafe { core::mem::zeroed() };
let ok = unsafe { libc::dladdr(addr as *const c_void, &raw mut info) };
if ok == 0 || info.dli_sname.is_null() {
return false;
}
let sname = unsafe { core::ffi::CStr::from_ptr(info.dli_sname) };
sname
.to_str()
.ok()
.and_then(crate::macho::normalize_symbol_name)
.is_some_and(|resolved| resolved == name)
}