use crate::dlpi;
use crate::error::{Error, Result};
use crate::{ImportKind, Symbol};
use core::ffi::{c_char, c_void};
use std::sync::OnceLock;
fn last_errno() -> u32 {
std::io::Error::last_os_error()
.raw_os_error()
.map_or(0, |e| u32::try_from(e).unwrap_or(0))
}
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 {
0x1000
} else {
usize::try_from(size).unwrap_or(0x1000)
}
})
}
pub(crate) fn query_protection(address: usize) -> u32 {
let Ok(maps) = std::fs::read_to_string("/proc/self/maps") else {
return 0;
};
for line in maps.lines() {
let Some((range, rest)) = line.split_once(' ') else {
continue;
};
let Some((start, end)) = range.split_once('-') else {
continue;
};
let (Ok(start), Ok(end)) = (
usize::from_str_radix(start, 16),
usize::from_str_radix(end, 16),
) else {
continue;
};
if address >= start && address < end {
let perms = rest.as_bytes();
let mut prot = 0u32;
if perms.first() == Some(&b'r') {
prot |= libc::PROT_READ as u32;
}
if perms.get(1) == Some(&b'w') {
prot |= libc::PROT_WRITE as u32;
}
if perms.get(2) == Some(&b'x') {
prot |= libc::PROT_EXEC as u32;
}
return prot;
}
}
0
}
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: last_errno(),
});
}
if prot & (libc::PROT_WRITE as u32) == 0 {
let want = i32::try_from(prot | libc::PROT_WRITE as u32 | libc::PROT_READ as u32)
.unwrap_or(libc::PROT_READ | libc::PROT_WRITE);
let rc = unsafe { libc::mprotect(page as *mut c_void, page_size(), want) };
if rc != 0 {
return Err(Error::Protect {
slot: page,
os_error: last_errno(),
});
}
}
Ok(prot)
}
pub(crate) unsafe fn restore_protection(page: usize, protection: u32) -> Result<()> {
let prot = i32::try_from(protection).unwrap_or(libc::PROT_READ);
let rc = unsafe { libc::mprotect(page as *mut c_void, page_size(), prot) };
if rc != 0 {
return Err(Error::Protect {
slot: page,
os_error: last_errno(),
});
}
Ok(())
}
pub(crate) fn module_still_loaded(base: usize) -> bool {
dlpi::find_base(base).is_some()
}
pub(crate) fn slot_belongs_to_module(address: usize, module_base: usize) -> bool {
dlpi::find_base(module_base).is_some_and(|obj| obj.contains_address(address))
}
pub(crate) fn resolve_original(
_kind: ImportKind,
_library: &str,
symbol: &Symbol,
_slot_value: usize,
) -> Option<usize> {
let Symbol::Name(name) = symbol else {
return None;
};
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() {
None
} else {
Some(ptr as usize)
}
}