use super::abi::{
self, classify_read, classify_write, ReadStep, WriteStep, HOST_ABI, HOST_POSIX, TIOCGWINSZ,
};
use super::layout::Winsize;
use super::{Fd, ReadOutcome, INTR, TERM, WINCH};
use core::ffi::c_void;
use core::sync::atomic::Ordering;
#[cfg(target_os = "linux")]
#[path = "unix_linux.rs"]
mod os;
#[cfg(target_os = "macos")]
#[path = "unix_darwin.rs"]
mod os;
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
compile_error!(
"sys/unix.rs supports the Linux and Darwin termios/ioctl ABIs only. This \
target needs its constants added to sys/abi.rs, its struct termios added \
to sys/layout.rs (both host-tested), and a two-item module alongside \
sys/unix_linux.rs giving the layout alias and the errno accessor."
);
use os::RawTermios;
#[allow(non_camel_case_types)]
type c_int = i32;
#[allow(non_camel_case_types)]
type c_ulong = u64;
#[allow(non_camel_case_types)]
type c_char = i8;
#[allow(non_camel_case_types)]
type size_t = usize;
#[allow(non_camel_case_types)]
type ssize_t = isize;
#[derive(Clone, Copy)]
pub struct SavedTermios(RawTermios);
const _: () = assert!(core::mem::size_of::<RawTermios>() >= 60);
const _: () = assert!(HOST_ABI.vmin_idx < HOST_ABI.nccs);
const _: () = assert!(HOST_ABI.vtime_idx < HOST_ABI.nccs);
const _: () = assert!(core::mem::size_of::<Winsize>() == abi::WINSIZE_LEN);
extern "C" {
fn tcgetattr(fd: c_int, termios_p: *mut RawTermios) -> c_int;
fn tcsetattr(fd: c_int, optional_actions: c_int, termios_p: *const RawTermios) -> c_int;
fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int;
fn read(fd: c_int, buf: *mut c_void, count: size_t) -> ssize_t;
fn write(fd: c_int, buf: *const c_void, count: size_t) -> ssize_t;
fn isatty(fd: c_int) -> c_int;
fn open(path: *const c_char, flags: c_int, ...) -> c_int;
fn close(fd: c_int) -> c_int;
fn signal(signum: c_int, handler: usize) -> usize;
}
extern "C" fn on_winch(_sig: c_int) {
WINCH.store(true, Ordering::SeqCst);
}
extern "C" fn on_intr(_sig: c_int) {
INTR.store(true, Ordering::SeqCst);
}
extern "C" fn on_term(_sig: c_int) {
TERM.store(true, Ordering::SeqCst);
}
pub fn install_signal_handlers() {
let p = &HOST_POSIX;
unsafe {
signal(p.sigwinch, on_winch as extern "C" fn(c_int) as usize);
signal(p.sigint, on_intr as extern "C" fn(c_int) as usize);
for sig in [p.sigterm, p.sighup, p.sigquit] {
signal(sig, on_term as extern "C" fn(c_int) as usize);
}
}
}
pub fn is_tty(fd: Fd) -> bool {
unsafe { isatty(fd) == 1 }
}
pub fn open_tty() -> Option<Fd> {
const PATH: &[u8] = b"/dev/tty\0";
let fd = unsafe {
open(
PATH.as_ptr() as *const c_char,
HOST_POSIX.o_rdwr | HOST_POSIX.o_noctty,
)
};
if fd < 0 {
None
} else {
Some(fd)
}
}
pub fn tty_fd() -> Option<(Fd, bool)> {
if is_tty(super::STDIN) {
Some((super::STDIN, false))
} else {
open_tty().map(|fd| (fd, true))
}
}
pub fn close_fd(fd: Fd) {
if fd > 2 {
unsafe {
close(fd);
}
}
}
pub fn winsize() -> Option<(u16, u16)> {
winsize_of(super::STDOUT)
.or_else(|| winsize_of(super::STDIN))
.or_else(|| {
let fd = open_tty()?;
let r = winsize_of(fd);
close_fd(fd);
r
})
}
pub fn winsize_of(fd: Fd) -> Option<(u16, u16)> {
let mut ws = Winsize::zeroed();
let rc = unsafe { ioctl(fd, TIOCGWINSZ as c_ulong, &mut ws as *mut Winsize) };
let (cols, rows) = ws.cols_rows();
abi::winsize_result(rc, cols, rows)
}
pub fn set_raw(fd: Fd) -> Option<SavedTermios> {
let mut t = RawTermios::zeroed();
if unsafe { tcgetattr(fd, &mut t as *mut RawTermios) } != 0 {
return None;
}
let saved = SavedTermios(t);
let mut raw = t;
raw.set_flags(abi::apply_raw_mode(t.flags(&HOST_ABI), &HOST_ABI), &HOST_ABI);
if unsafe { tcsetattr(fd, HOST_ABI.tcsaflush, &raw as *const RawTermios) } != 0 {
return None;
}
Some(saved)
}
pub fn restore(fd: Fd, saved: &SavedTermios) -> bool {
unsafe { tcsetattr(fd, HOST_ABI.tcsaflush, &saved.0 as *const RawTermios) == 0 }
}
pub fn read_input(fd: Fd, buf: &mut [u8]) -> ReadOutcome {
if buf.is_empty() {
return ReadOutcome::Timeout;
}
loop {
let n = unsafe { read(fd, buf.as_mut_ptr().cast(), buf.len()) };
let e = if n < 0 { os::errno() } else { 0 };
match classify_read(n, e, &HOST_ABI) {
ReadStep::Bytes(k) => return ReadOutcome::Bytes(k),
ReadStep::Timeout => return ReadOutcome::Timeout,
ReadStep::Retry => continue,
ReadStep::Error(code) => return ReadOutcome::Error(code),
}
}
}
pub fn write_all(fd: Fd, buf: &[u8]) -> Result<(), i32> {
let mut off = 0usize;
while off < buf.len() {
let n = unsafe { write(fd, buf[off..].as_ptr().cast(), buf.len() - off) };
let e = if n < 0 { os::errno() } else { 0 };
match classify_write(n, e, &HOST_ABI) {
WriteStep::Advance(k) => off += k,
WriteStep::Retry => continue,
WriteStep::Fail(code) => return Err(code),
}
}
Ok(())
}
#[cfg(test)]
#[path = "unix_tests.rs"]
mod tests;