#![allow(dead_code)]
use crate::Error;
use core::{
num::NonZeroU32,
ptr::NonNull,
sync::atomic::{fence, AtomicPtr, Ordering},
};
use libc::c_void;
cfg_if! {
if #[cfg(any(target_os = "netbsd", target_os = "openbsd", target_os = "android"))] {
use libc::__errno as errno_location;
} else if #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "redox"))] {
use libc::__errno_location as errno_location;
} else if #[cfg(any(target_os = "solaris", target_os = "illumos"))] {
use libc::___errno as errno_location;
} else if #[cfg(any(target_os = "macos", target_os = "freebsd"))] {
use libc::__error as errno_location;
} else if #[cfg(target_os = "haiku")] {
use libc::_errnop as errno_location;
} else if #[cfg(all(target_os = "horizon", target_arch = "arm"))] {
extern "C" {
fn __errno() -> *mut libc::c_int;
}
use __errno as errno_location;
}
}
cfg_if! {
if #[cfg(target_os = "vxworks")] {
use libc::errnoGet as get_errno;
} else if #[cfg(target_os = "dragonfly")] {
unsafe fn get_errno() -> libc::c_int { -1 }
} else {
unsafe fn get_errno() -> libc::c_int { *errno_location() }
}
}
pub fn last_os_error() -> Error {
let errno = unsafe { get_errno() };
if errno > 0 {
Error::from(NonZeroU32::new(errno as u32).unwrap())
} else {
Error::ERRNO_NOT_POSITIVE
}
}
pub fn sys_fill_exact(
mut buf: &mut [u8],
sys_fill: impl Fn(&mut [u8]) -> libc::ssize_t,
) -> Result<(), Error> {
while !buf.is_empty() {
let res = sys_fill(buf);
if res < 0 {
let err = last_os_error();
if err.raw_os_error() != Some(libc::EINTR) {
return Err(err);
}
} else {
buf = &mut buf[(res as usize)..];
}
}
Ok(())
}
pub struct Weak {
name: &'static str,
addr: AtomicPtr<c_void>,
}
impl Weak {
const UNINIT: *mut c_void = 1 as *mut c_void;
pub const unsafe fn new(name: &'static str) -> Self {
Self {
name,
addr: AtomicPtr::new(Self::UNINIT),
}
}
pub fn ptr(&self) -> Option<NonNull<c_void>> {
match self.addr.load(Ordering::Relaxed) {
Self::UNINIT => {
let symbol = self.name.as_ptr() as *const _;
let addr = unsafe { libc::dlsym(libc::RTLD_DEFAULT, symbol) };
self.addr.store(addr, Ordering::Release);
NonNull::new(addr)
}
addr => {
let func = NonNull::new(addr)?;
fence(Ordering::Acquire);
Some(func)
}
}
}
}
cfg_if! {
if #[cfg(any(target_os = "linux", target_os = "emscripten"))] {
use libc::open64 as open;
} else {
use libc::open;
}
}
pub unsafe fn open_readonly(path: &str) -> Result<libc::c_int, Error> {
debug_assert_eq!(path.as_bytes().last(), Some(&0));
loop {
let fd = open(path.as_ptr() as *const _, libc::O_RDONLY | libc::O_CLOEXEC);
if fd >= 0 {
return Ok(fd);
}
let err = last_os_error();
if err.raw_os_error() != Some(libc::EINTR) {
return Err(err);
}
}
}