#![allow(unsafe_code)]
#[cfg(not(target_os = "macos"))]
use std::ffi::c_short;
use std::ffi::{c_int, c_ulong, c_ushort, c_void};
use std::io;
use std::sync::OnceLock;
use std::time::{Duration, Instant};
const TERMIOS_WORDS: usize = 32;
const TCSANOW: c_int = 0;
#[cfg(target_os = "linux")]
mod os {
use std::ffi::{c_int, c_ulong};
pub(super) const TIOCGWINSZ: c_ulong = 0x5413;
pub(super) const O_NONBLOCK: c_int = 0o4000;
pub(super) type NFds = c_ulong;
pub(super) const TCIFLUSH: c_int = 0;
pub(super) const O_CLOEXEC: c_int = 0o2_000_000;
}
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
mod os {
#[cfg(target_os = "freebsd")]
use std::ffi::c_uint;
use std::ffi::{c_int, c_ulong};
pub(super) const TIOCGWINSZ: c_ulong = 0x4008_7468;
pub(super) const O_NONBLOCK: c_int = 0x0004;
#[cfg(target_os = "freebsd")]
pub(super) type NFds = c_uint;
pub(super) const TCIFLUSH: c_int = 1;
#[cfg(target_os = "freebsd")]
pub(super) const O_CLOEXEC: c_int = 0x0010_0000;
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd")))]
compile_error!("petitcarnets supports Linux, macOS and FreeBSD for now");
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
compile_error!("petitcarnets supports x86-64 and 64-bit Arm for now");
const F_GETFL: c_int = 3;
const F_SETFL: c_int = 4;
#[cfg(target_os = "macos")]
const F_SETFD: c_int = 2;
#[cfg(target_os = "macos")]
const FD_CLOEXEC: c_int = 1;
#[cfg(not(target_os = "macos"))]
const POLLIN: c_short = 0x01;
#[cfg(not(target_os = "macos"))]
const POLLERR: c_short = 0x08;
#[cfg(not(target_os = "macos"))]
const POLLHUP: c_short = 0x10;
#[cfg(not(target_os = "macos"))]
const POLLNVAL: c_short = 0x20;
const EINTR: i32 = 4;
#[derive(Clone, Copy)]
pub(crate) struct Termios([u64; TERMIOS_WORDS]);
#[cfg(not(test))]
impl std::fmt::Debug for Termios {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Termios(..)")
}
}
#[cfg(test)]
impl std::fmt::Debug for Termios {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let set = self
.settled()
.into_iter()
.enumerate()
.filter(|(_, w)| *w != 0);
f.debug_map()
.entries(set.map(|(i, w)| (i, format!("{w:#x}"))))
.finish()
}
}
#[cfg(test)]
impl Termios {
fn settled(&self) -> [u64; TERMIOS_WORDS] {
let words = self.0;
#[cfg(target_os = "macos")]
let words = {
const PENDIN: u64 = 0x2000_0000;
let mut words = words;
words[3] &= !PENDIN;
words
};
words
}
}
#[cfg(test)]
impl PartialEq for Termios {
fn eq(&self, other: &Self) -> bool {
self.settled() == other.settled()
}
}
#[repr(C)]
#[derive(Default)]
struct Winsize {
rows: c_ushort,
cols: c_ushort,
x_pixels: c_ushort,
y_pixels: c_ushort,
}
#[cfg(not(target_os = "macos"))]
#[repr(C)]
struct PollFd {
fd: c_int,
events: c_short,
revents: c_short,
}
unsafe extern "C" {
fn tcgetattr(fd: c_int, termios: *mut u64) -> c_int;
fn tcsetattr(fd: c_int, action: c_int, termios: *const u64) -> c_int;
fn cfmakeraw(termios: *mut u64);
fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int;
fn isatty(fd: c_int) -> c_int;
fn tcflush(fd: c_int, queue: c_int) -> c_int;
#[cfg(target_os = "macos")]
fn pipe(fds: *mut c_int) -> c_int;
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
fn pipe2(fds: *mut c_int, flags: c_int) -> c_int;
fn read(fd: c_int, buf: *mut c_void, count: usize) -> isize;
fn write(fd: c_int, buf: *const c_void, count: usize) -> isize;
fn close(fd: c_int) -> c_int;
fn fcntl(fd: c_int, cmd: c_int, ...) -> c_int;
#[cfg(not(target_os = "macos"))]
fn poll(fds: *mut PollFd, nfds: os::NFds, timeout: c_int) -> c_int;
}
pub(crate) const STDIN: c_int = 0;
pub(crate) const STDOUT: c_int = 1;
fn check(rc: c_int) -> io::Result<c_int> {
if rc == -1 {
Err(io::Error::last_os_error())
} else {
Ok(rc)
}
}
pub(crate) fn get_mode(fd: c_int) -> io::Result<Termios> {
let mut t = Termios([0; TERMIOS_WORDS]);
check(unsafe { tcgetattr(fd, t.0.as_mut_ptr()) }).map(drop)?;
Ok(t)
}
pub(crate) fn set_mode(fd: c_int, termios: &Termios) -> io::Result<()> {
set_mode_when(fd, TCSANOW, termios)?;
check(unsafe { tcflush(fd, os::TCIFLUSH) }).map(drop)
}
pub(crate) fn set_mode_now(fd: c_int, termios: &Termios) -> io::Result<()> {
set_mode_when(fd, TCSANOW, termios)
}
fn set_mode_when(fd: c_int, action: c_int, termios: &Termios) -> io::Result<()> {
check(unsafe { tcsetattr(fd, action, termios.0.as_ptr()) }).map(drop)
}
pub(crate) fn make_raw(mode: &Termios) -> Termios {
let mut raw = *mode;
unsafe { cfmakeraw(raw.0.as_mut_ptr()) };
raw
}
pub(crate) fn window_size(fd: c_int) -> io::Result<(u16, u16)> {
let mut size = Winsize::default();
let rc = unsafe { ioctl(fd, os::TIOCGWINSZ, &raw mut size) };
if rc == 0 && size.cols > 0 && size.rows > 0 {
Ok((size.cols, size.rows))
} else {
Err(io::Error::other("the window size is not available"))
}
}
pub(crate) fn is_tty(fd: c_int) -> bool {
unsafe { isatty(fd) == 1 }
}
pub(crate) fn read_fd(fd: c_int, buf: &mut [u8]) -> io::Result<usize> {
loop {
let n = unsafe { read(fd, buf.as_mut_ptr().cast(), buf.len()) };
match usize::try_from(n) {
Ok(n) => return Ok(n),
Err(_) => interrupted_or(io::Error::last_os_error())?,
}
}
}
pub(crate) fn write_all_fd(fd: c_int, mut bytes: &[u8]) -> io::Result<()> {
while !bytes.is_empty() {
let n = unsafe { write(fd, bytes.as_ptr().cast(), bytes.len()) };
match usize::try_from(n) {
Ok(0) => return Err(io::ErrorKind::WriteZero.into()),
Ok(n) => bytes = &bytes[n..],
Err(_) => interrupted_or(io::Error::last_os_error())?,
}
}
Ok(())
}
fn interrupted_or(err: io::Error) -> io::Result<()> {
if err.raw_os_error() == Some(EINTR) {
Ok(())
} else {
Err(err)
}
}
pub(crate) fn wait_readable<const N: usize>(
fds: [c_int; N],
timeout: Option<Duration>,
) -> io::Result<[bool; N]> {
#[cfg(target_os = "macos")]
return select::wait_readable(fds, timeout.map(|t| Instant::now() + t));
#[cfg(not(target_os = "macos"))]
poll_readable(fds, timeout.map(|t| Instant::now() + t))
}
#[cfg(not(target_os = "macos"))]
fn poll_readable<const N: usize>(
fds: [c_int; N],
deadline: Option<Instant>,
) -> io::Result<[bool; N]> {
let mut polled = fds.map(|fd| PollFd {
fd,
events: POLLIN,
revents: 0,
});
let count = os::NFds::try_from(N).map_err(io::Error::other)?;
loop {
let wait = poll_timeout(deadline);
let rc = unsafe { poll(polled.as_mut_ptr(), count, wait) };
if rc >= 0 {
break;
}
interrupted_or(io::Error::last_os_error())?;
}
if polled.iter().any(|p| p.revents & POLLNVAL != 0) {
return Err(io::Error::other("poll cannot watch this descriptor"));
}
let ready = POLLIN | POLLERR | POLLHUP;
Ok(polled.map(|p| p.revents & ready != 0))
}
#[cfg(not(target_os = "macos"))]
fn poll_timeout(deadline: Option<Instant>) -> c_int {
deadline.map_or(-1, |at| {
let left = at.saturating_duration_since(Instant::now());
let ms = left.as_micros().div_ceil(1000);
c_int::try_from(ms).unwrap_or(c_int::MAX)
})
}
#[derive(Debug)]
pub(crate) struct Pipe {
pub(crate) read: c_int,
pub(crate) write: c_int,
}
impl Pipe {
pub(crate) fn new() -> io::Result<Self> {
let pipe = Self::cloexec()?;
let flags = check(unsafe { fcntl(pipe.write, F_GETFL) })?;
check(unsafe { fcntl(pipe.write, F_SETFL, flags | os::O_NONBLOCK) }).map(drop)?;
Ok(pipe)
}
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
fn cloexec() -> io::Result<Self> {
let mut fds = [-1; 2];
check(unsafe { pipe2(fds.as_mut_ptr(), os::O_CLOEXEC) }).map(drop)?;
Ok(Self {
read: fds[0],
write: fds[1],
})
}
#[cfg(target_os = "macos")]
fn cloexec() -> io::Result<Self> {
let mut fds = [-1; 2];
check(unsafe { pipe(fds.as_mut_ptr()) }).map(drop)?;
let pipe = Self {
read: fds[0],
write: fds[1],
};
for fd in fds {
check(unsafe { fcntl(fd, F_SETFD, FD_CLOEXEC) }).map(drop)?;
}
Ok(pipe)
}
#[cfg(test)]
pub(crate) fn close_write(&mut self) {
close_fd(&mut self.write);
}
}
fn close_fd(fd: &mut c_int) {
if *fd >= 0 {
let _ = unsafe { close(*fd) };
*fd = -1;
}
}
impl Drop for Pipe {
fn drop(&mut self) {
close_fd(&mut self.read);
close_fd(&mut self.write);
}
}
pub(crate) fn wake_pipe() -> io::Result<&'static Pipe> {
static WAKE: OnceLock<Pipe> = OnceLock::new();
if let Some(pipe) = WAKE.get() {
return Ok(pipe);
}
let pipe = Pipe::new()?;
Ok(WAKE.get_or_init(|| pipe))
}
mod signal;
pub(crate) use signal::{default_stop, signo, stop_process_group, unwatch_signals, watch_signals};
#[cfg(target_os = "macos")]
mod select;
#[cfg(test)]
mod pty;
#[cfg(test)]
pub(crate) use pty::open_pty;
#[cfg(test)]
mod tests;