use super::linux;
use std::{
fs,
io::{self, Read, Seek, Write},
os::{fd::AsFd, unix::fs::MetadataExt},
sync::atomic::{AtomicBool, AtomicU8, Ordering},
};
static CLOSED: AtomicU8 = AtomicU8::new(0);
static STDERR_FAILED: AtomicBool = AtomicBool::new(false);
#[used]
#[unsafe(link_section = ".preinit_array")]
static CAPTURE: unsafe extern "C" fn() = capture;
unsafe extern "C" fn capture() {
let mut closed = 0;
for fd in 0..3 {
if unsafe { linux::syscall(72, fd, 1, 0, 0) } == -9 {
closed |= 1 << fd;
let opened = unsafe {
linux::syscall(
257,
(-100isize) as usize,
c"/dev/null".as_ptr() as usize,
usize::from(fd == 0),
0,
)
};
if opened != fd as isize {
unsafe { linux::syscall(231, 1, 0, 0, 0) };
}
}
}
CLOSED.store(closed, Ordering::Relaxed);
}
pub(super) fn originally_closed(fd: usize) -> bool {
CLOSED.load(Ordering::Relaxed) & (1 << fd) != 0
}
pub(super) fn check_input_access() -> io::Result<()> {
let flags = result(unsafe { linux::syscall(72, 0, 3, 0, 0) })?;
if flags & 3 == 1 {
Err(io::Error::from_raw_os_error(9))
} else {
Ok(())
}
}
pub(super) fn finish_stderr() -> bool {
let failed = STDERR_FAILED.load(Ordering::Relaxed);
let closed = unsafe { linux::syscall(3, 2, 0, 0, 0) };
!failed && (closed >= 0 || closed == -9)
}
fn result(value: isize) -> io::Result<usize> {
if value < 0 {
Err(io::Error::from_raw_os_error(-value as i32))
} else {
Ok(value as usize)
}
}
pub(super) struct Stdin;
impl Read for Stdin {
fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
loop {
let value =
unsafe { linux::syscall(0, 0, bytes.as_mut_ptr() as usize, bytes.len(), 0) };
if value != -4 {
return result(value);
}
}
}
}
impl Seek for Stdin {
fn seek(&mut self, position: io::SeekFrom) -> io::Result<u64> {
let (offset, whence) = match position {
io::SeekFrom::Start(offset) => (offset as usize, 0),
io::SeekFrom::Current(offset) => (offset as usize, 1),
io::SeekFrom::End(offset) => (offset as usize, 2),
};
result(unsafe { linux::syscall(8, 0, offset, whence, 0) }).map(|at| at as u64)
}
}
pub(super) fn regular_input_length() -> Option<u64> {
let file = fs::File::from(io::stdin().as_fd().try_clone_to_owned().ok()?);
let metadata = file.metadata().ok()?;
(metadata.is_file() && metadata.len() != 0 && metadata.blocks() != 0).then_some(metadata.len())
}
pub(super) fn write(fd: usize, bytes: &[u8]) -> io::Result<usize> {
loop {
let value = unsafe { linux::syscall(1, fd, bytes.as_ptr() as usize, bytes.len(), 0) };
if value != -4 {
return result(value);
}
}
}
pub(super) struct Stderr;
impl Write for Stderr {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
let result = write(2, bytes);
if result.is_err() {
STDERR_FAILED.store(true, Ordering::Relaxed);
}
result
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}