#![allow(unsafe_code, clippy::undocumented_unsafe_blocks)]
use crate::backend::c;
use crate::backend::conv::{by_ref, c_uint, ret};
use crate::fd::BorrowedFd;
use crate::io;
use crate::pid::Pid;
#[cfg(all(feature = "alloc", feature = "procfs"))]
use crate::procfs;
use crate::termios::{
speed, Action, ControlModes, InputModes, LocalModes, OptionalActions, OutputModes,
QueueSelector, SpecialCodeIndex, Termios, Winsize,
};
#[cfg(all(feature = "alloc", feature = "procfs"))]
use crate::{ffi::CStr, fs::FileType, path::DecInt};
use core::mem::MaybeUninit;
#[inline]
pub(crate) fn tcgetwinsize(fd: BorrowedFd<'_>) -> io::Result<Winsize> {
unsafe {
let mut result = MaybeUninit::<Winsize>::uninit();
ret(syscall!(__NR_ioctl, fd, c_uint(c::TIOCGWINSZ), &mut result))?;
Ok(result.assume_init())
}
}
#[inline]
pub(crate) fn tcgetattr(fd: BorrowedFd<'_>) -> io::Result<Termios> {
let mut result = MaybeUninit::<Termios>::uninit();
unsafe {
match ret(syscall!(__NR_ioctl, fd, c_uint(c::TCGETS2), &mut result)) {
Ok(()) => Ok(result.assume_init()),
#[cfg(not(any(target_arch = "powerpc", target_arch = "powerpc64")))]
Err(io::Errno::NOTTY) | Err(io::Errno::ACCESS) => tcgetattr_fallback(fd),
Err(err) => Err(err),
}
}
}
#[cfg(not(any(target_arch = "powerpc", target_arch = "powerpc64")))]
#[cold]
fn tcgetattr_fallback(fd: BorrowedFd<'_>) -> io::Result<Termios> {
use core::ptr::{addr_of, addr_of_mut};
let mut result = MaybeUninit::<Termios>::uninit();
unsafe {
ret(syscall!(__NR_ioctl, fd, c_uint(c::TCGETS), &mut result))?;
let ptr = result.as_mut_ptr();
let control_modes = addr_of!((*ptr).control_modes).read();
let encoded_out = control_modes.bits() & c::CBAUD;
let output_speed = match speed::decode(encoded_out) {
Some(output_speed) => output_speed,
None => return Err(io::Errno::RANGE),
};
addr_of_mut!((*ptr).output_speed).write(output_speed);
let encoded_in = (control_modes.bits() & c::CIBAUD) >> c::IBSHIFT;
let input_speed = if encoded_in == c::B0 {
output_speed
} else {
match speed::decode(encoded_in) {
Some(input_speed) => input_speed,
None => return Err(io::Errno::RANGE),
}
};
addr_of_mut!((*ptr).input_speed).write(input_speed);
Ok(result.assume_init())
}
}
#[inline]
pub(crate) fn tcgetpgrp(fd: BorrowedFd<'_>) -> io::Result<Pid> {
unsafe {
let mut result = MaybeUninit::<c::pid_t>::uninit();
ret(syscall!(__NR_ioctl, fd, c_uint(c::TIOCGPGRP), &mut result))?;
let pid = result.assume_init();
if pid == 0 {
return Err(io::Errno::OPNOTSUPP);
}
Ok(Pid::from_raw_unchecked(pid))
}
}
#[inline]
pub(crate) fn tcsetattr(
fd: BorrowedFd<'_>,
optional_actions: OptionalActions,
termios: &Termios,
) -> io::Result<()> {
let request = c::TCSETS2
+ if cfg!(any(
target_arch = "mips",
target_arch = "mips32r6",
target_arch = "mips64",
target_arch = "mips64r6"
)) {
optional_actions as u32 - c::TCSETS
} else {
optional_actions as u32
};
unsafe {
match ret(syscall_readonly!(
__NR_ioctl,
fd,
c_uint(request),
by_ref(termios)
)) {
Ok(()) => Ok(()),
#[cfg(not(any(target_arch = "powerpc", target_arch = "powerpc64")))]
Err(io::Errno::NOTTY) | Err(io::Errno::ACCESS) => {
tcsetattr_fallback(fd, optional_actions, termios)
}
Err(err) => Err(err),
}
}
}
#[cfg(not(any(target_arch = "powerpc", target_arch = "powerpc64")))]
#[cold]
fn tcsetattr_fallback(
fd: BorrowedFd<'_>,
optional_actions: OptionalActions,
termios: &Termios,
) -> io::Result<()> {
let control_modes_bits = termios.control_modes.bits();
let encoded_out = control_modes_bits & c::CBAUD;
let encoded_in = (control_modes_bits & c::CIBAUD) >> c::IBSHIFT;
if encoded_out == c::BOTHER || encoded_in == c::BOTHER {
return Err(io::Errno::RANGE);
}
let request = if cfg!(any(
target_arch = "mips",
target_arch = "mips32r6",
target_arch = "mips64",
target_arch = "mips64r6"
)) {
optional_actions as u32
} else {
optional_actions as u32 + c::TCSETS
};
unsafe {
ret(syscall_readonly!(
__NR_ioctl,
fd,
c_uint(request),
by_ref(termios)
))
}
}
#[inline]
pub(crate) fn tcsendbreak(fd: BorrowedFd<'_>) -> io::Result<()> {
unsafe {
ret(syscall_readonly!(
__NR_ioctl,
fd,
c_uint(c::TCSBRK),
c_uint(0)
))
}
}
#[inline]
pub(crate) fn tcdrain(fd: BorrowedFd<'_>) -> io::Result<()> {
unsafe {
ret(syscall_readonly!(
__NR_ioctl,
fd,
c_uint(c::TCSBRK),
c_uint(1)
))
}
}
#[inline]
pub(crate) fn tcflush(fd: BorrowedFd<'_>, queue_selector: QueueSelector) -> io::Result<()> {
unsafe {
ret(syscall_readonly!(
__NR_ioctl,
fd,
c_uint(c::TCFLSH),
c_uint(queue_selector as u32)
))
}
}
#[inline]
pub(crate) fn tcflow(fd: BorrowedFd<'_>, action: Action) -> io::Result<()> {
unsafe {
ret(syscall_readonly!(
__NR_ioctl,
fd,
c_uint(c::TCXONC),
c_uint(action as u32)
))
}
}
#[inline]
pub(crate) fn tcgetsid(fd: BorrowedFd<'_>) -> io::Result<Pid> {
unsafe {
let mut result = MaybeUninit::<c::pid_t>::uninit();
ret(syscall!(__NR_ioctl, fd, c_uint(c::TIOCGSID), &mut result))?;
let pid = result.assume_init();
Ok(Pid::from_raw_unchecked(pid))
}
}
#[inline]
pub(crate) fn tcsetwinsize(fd: BorrowedFd<'_>, winsize: Winsize) -> io::Result<()> {
unsafe {
ret(syscall_readonly!(
__NR_ioctl,
fd,
c_uint(c::TIOCSWINSZ),
by_ref(&winsize)
))
}
}
#[inline]
pub(crate) fn tcsetpgrp(fd: BorrowedFd<'_>, pid: Pid) -> io::Result<()> {
let raw_pid: c::c_int = pid.as_raw_nonzero().get();
unsafe {
ret(syscall_readonly!(
__NR_ioctl,
fd,
c_uint(c::TIOCSPGRP),
by_ref(&raw_pid)
))
}
}
#[inline]
pub(crate) fn set_speed(termios: &mut Termios, arbitrary_speed: u32) -> io::Result<()> {
let encoded_speed = speed::encode(arbitrary_speed).unwrap_or(c::BOTHER);
debug_assert_eq!(encoded_speed & !c::CBAUD, 0);
termios.control_modes -= ControlModes::from_bits_retain(c::CBAUD | c::CIBAUD);
termios.control_modes |=
ControlModes::from_bits_retain(encoded_speed | (encoded_speed << c::IBSHIFT));
termios.input_speed = arbitrary_speed;
termios.output_speed = arbitrary_speed;
Ok(())
}
#[inline]
pub(crate) fn set_output_speed(termios: &mut Termios, arbitrary_speed: u32) -> io::Result<()> {
let encoded_speed = speed::encode(arbitrary_speed).unwrap_or(c::BOTHER);
debug_assert_eq!(encoded_speed & !c::CBAUD, 0);
termios.control_modes -= ControlModes::from_bits_retain(c::CBAUD);
termios.control_modes |= ControlModes::from_bits_retain(encoded_speed);
termios.output_speed = arbitrary_speed;
Ok(())
}
#[inline]
pub(crate) fn set_input_speed(termios: &mut Termios, arbitrary_speed: u32) -> io::Result<()> {
let encoded_speed = speed::encode(arbitrary_speed).unwrap_or(c::BOTHER);
debug_assert_eq!(encoded_speed & !c::CBAUD, 0);
termios.control_modes -= ControlModes::from_bits_retain(c::CIBAUD);
termios.control_modes |= ControlModes::from_bits_retain(encoded_speed << c::IBSHIFT);
termios.input_speed = arbitrary_speed;
Ok(())
}
#[inline]
pub(crate) fn cfmakeraw(termios: &mut Termios) {
termios.input_modes -= InputModes::IGNBRK
| InputModes::BRKINT
| InputModes::PARMRK
| InputModes::ISTRIP
| InputModes::INLCR
| InputModes::IGNCR
| InputModes::ICRNL
| InputModes::IXON;
termios.output_modes -= OutputModes::OPOST;
termios.local_modes -= LocalModes::ECHO
| LocalModes::ECHONL
| LocalModes::ICANON
| LocalModes::ISIG
| LocalModes::IEXTEN;
termios.control_modes -= ControlModes::CSIZE | ControlModes::PARENB;
termios.control_modes |= ControlModes::CS8;
termios.special_codes[SpecialCodeIndex::VMIN] = 1;
termios.special_codes[SpecialCodeIndex::VTIME] = 0;
}
#[inline]
pub(crate) fn isatty(fd: BorrowedFd<'_>) -> bool {
tcgetwinsize(fd).is_ok()
}
#[cfg(all(feature = "alloc", feature = "procfs"))]
pub(crate) fn ttyname(fd: BorrowedFd<'_>, buf: &mut [MaybeUninit<u8>]) -> io::Result<usize> {
let fd_stat = crate::backend::fs::syscalls::fstat(fd)?;
if FileType::from_raw_mode(fd_stat.st_mode) != FileType::CharacterDevice {
return Err(io::Errno::NOTTY);
}
tcgetwinsize(fd)?;
let proc_self_fd = procfs::proc_self_fd()?;
let r = crate::backend::fs::syscalls::readlinkat(
proc_self_fd,
DecInt::from_fd(fd).as_c_str(),
buf,
)?;
if r == buf.len() {
return Err(io::Errno::RANGE);
}
buf[r].write(b'\0');
{
let path = unsafe { CStr::from_ptr(buf.as_ptr().cast()) };
let path_stat = crate::backend::fs::syscalls::stat(path)?;
if path_stat.st_dev != fd_stat.st_dev || path_stat.st_ino != fd_stat.st_ino {
return Err(io::Errno::NODEV);
}
}
Ok(r)
}