#![allow(unsafe_code)]
use std::io;
use std::os::fd::RawFd;
use std::ptr;
#[cfg(target_os = "linux")]
pub const MAP_FIXED_NOREPLACE: libc::c_int = 0x100_000;
#[must_use]
pub fn fixed_map_flag() -> libc::c_int {
#[cfg(target_os = "linux")]
{
MAP_FIXED_NOREPLACE
}
#[cfg(not(target_os = "linux"))]
{
libc::MAP_FIXED
}
}
#[must_use]
pub fn page_size() -> Option<usize> {
let raw = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
if raw <= 0 {
return None;
}
usize::try_from(raw).ok()
}
#[must_use]
pub fn phys_pages() -> Option<u64> {
let raw = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) };
if raw <= 0 {
return None;
}
u64::try_from(raw).ok()
}
#[must_use]
pub fn phys_mem_bytes() -> u64 {
match (phys_pages(), page_size()) {
(Some(pages), Some(page)) => {
let s = u64::try_from(page).unwrap_or(0);
pages.saturating_mul(s).max(64 * 1024 * 1024)
}
_ => 8 * 1024 * 1024 * 1024, }
}
pub fn close_fd(fd: RawFd) {
unsafe {
let _ = libc::close(fd);
}
}
#[must_use]
pub fn dup_fd(fd: RawFd) -> Option<RawFd> {
let rc = unsafe { libc::dup(fd) };
if rc < 0 { None } else { Some(rc) }
}
pub fn lseek_fd(fd: RawFd, offset: i64, whence: libc::c_int) -> Option<i64> {
let rc = unsafe { libc::lseek(fd, offset, whence) };
if rc < 0 { None } else { Some(rc) }
}
pub fn fcntl_get(fd: RawFd, cmd: libc::c_int) -> Option<i32> {
let rc = unsafe { libc::fcntl(fd, cmd) };
if rc < 0 { None } else { Some(rc) }
}
pub fn fcntl_set(fd: RawFd, cmd: libc::c_int, arg: libc::c_int) -> Option<i32> {
let rc = unsafe { libc::fcntl(fd, cmd, arg) };
if rc < 0 { None } else { Some(rc) }
}
pub fn open_path(path: &std::ffi::CStr, flags: libc::c_int, mode: libc::c_uint) -> Option<RawFd> {
let rc = unsafe { libc::open(path.as_ptr(), flags, mode) };
if rc < 0 { None } else { Some(rc) }
}
pub fn openat(
dirfd: RawFd,
path: &std::ffi::CStr,
flags: libc::c_int,
mode: libc::c_uint,
) -> Option<RawFd> {
let rc = unsafe { libc::openat(dirfd, path.as_ptr(), flags, mode) };
if rc < 0 { None } else { Some(rc) }
}
pub fn write_fd(fd: RawFd, data: &[u8]) -> io::Result<usize> {
if data.is_empty() {
return Ok(0);
}
let n = unsafe { libc::write(fd, data.as_ptr().cast(), data.len()) };
if n < 0 {
return Err(io::Error::last_os_error());
}
usize::try_from(n).map_err(|_| io::Error::other("write returned out-of-range count"))
}
pub fn read_fd(fd: RawFd, buf: &mut [u8]) -> io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
if n < 0 {
return Err(io::Error::last_os_error());
}
usize::try_from(n).map_err(|_| io::Error::other("read returned out-of-range count"))
}
pub fn fstat_fd(fd: RawFd) -> Option<libc::stat> {
let mut st: libc::stat = unsafe { std::mem::zeroed() };
let rc = unsafe { libc::fstat(fd, std::ptr::addr_of_mut!(st)) };
if rc == 0 { Some(st) } else { None }
}
pub fn ftruncate_fd(fd: RawFd, length: i64) -> Option<()> {
let rc = unsafe { libc::ftruncate(fd, length) };
if rc == 0 { Some(()) } else { None }
}
pub fn fsync_fd(fd: RawFd) -> Option<()> {
let rc = unsafe { libc::fsync(fd) };
if rc == 0 { Some(()) } else { None }
}
pub fn gettimeofday() -> Option<libc::timeval> {
let mut tv: libc::timeval = unsafe { std::mem::zeroed() };
let rc = unsafe { libc::gettimeofday(std::ptr::addr_of_mut!(tv), ptr::null_mut()) };
if rc == 0 { Some(tv) } else { None }
}
pub fn clock_gettime(clock_id: libc::clockid_t) -> Option<libc::timespec> {
let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
let rc = unsafe { libc::clock_gettime(clock_id, std::ptr::addr_of_mut!(ts)) };
if rc == 0 { Some(ts) } else { None }
}
#[must_use]
pub fn mmap(
fixed_addr: Option<u64>,
len: usize,
prot: libc::c_int,
flags: libc::c_int,
fd: RawFd,
offset: i64,
) -> Option<*mut u8> {
if len == 0 {
return None;
}
let addr = fixed_addr.map_or(ptr::null_mut(), u64_as_void_ptr);
let raw = unsafe { libc::mmap(addr, len, prot, flags, fd, offset) };
if raw == libc::MAP_FAILED {
None
} else {
Some(raw.cast())
}
}
pub fn munmap(ptr: *mut u8, len: usize) -> bool {
if ptr.is_null() || len == 0 {
return true;
}
let rc = unsafe { libc::munmap(ptr.cast(), len) };
rc == 0
}
pub fn mprotect(ptr: *mut u8, len: usize, prot: libc::c_int) -> bool {
if ptr.is_null() || len == 0 {
return true;
}
let rc = unsafe { libc::mprotect(ptr.cast(), len, prot) };
rc == 0
}
pub fn msync(ptr: *mut u8, len: usize, flags: libc::c_int) -> bool {
if ptr.is_null() || len == 0 {
return true;
}
let rc = unsafe { libc::msync(ptr.cast(), len, flags) };
rc == 0
}
#[must_use]
pub fn ptr_addr_u64(p: *mut u8) -> u64 {
u64::try_from(p.addr()).unwrap_or(0)
}
#[must_use]
pub fn u64_as_void_ptr(addr: u64) -> *mut libc::c_void {
let u = usize::try_from(addr).unwrap_or(0);
ptr::with_exposed_provenance_mut::<u8>(u).cast()
}
#[derive(Debug)]
pub struct HostDir {
ptr: *mut libc::DIR,
}
unsafe impl Send for HostDir {}
unsafe impl Sync for HostDir {}
impl HostDir {
pub fn open_dup(host_fd: RawFd) -> Result<Self, i32> {
let dup = unsafe { libc::dup(host_fd) };
if dup < 0 {
return Err(last_errno_i32());
}
let dir = unsafe { libc::fdopendir(dup) };
if dir.is_null() {
let err = last_errno_i32();
unsafe {
libc::close(dup);
}
return Err(err);
}
Ok(Self { ptr: dir })
}
pub fn read_next(&mut self) -> Option<(Vec<u8>, u8)> {
use std::ffi::CStr;
loop {
let ent = unsafe { libc::readdir(self.ptr) };
if ent.is_null() {
return None;
}
let d_type = unsafe { (*ent).d_type };
let name_ptr = unsafe { (*ent).d_name.as_ptr() };
let name = unsafe { CStr::from_ptr(name_ptr) };
let bytes = name.to_bytes().to_vec();
if bytes.is_empty() {
continue;
}
return Some((bytes, d_type));
}
}
}
impl Drop for HostDir {
fn drop(&mut self) {
if !self.ptr.is_null() {
unsafe {
let _ = libc::closedir(self.ptr);
}
self.ptr = ptr::null_mut();
}
}
}
fn last_errno_i32() -> i32 {
let raw = io::Error::last_os_error()
.raw_os_error()
.unwrap_or(1)
.unsigned_abs();
i32::try_from(raw).unwrap_or(1)
}