Skip to main content

libc_rs/
io.rs

1//! File descriptor I/O, duplication, pipes, `fcntl`, and `ioctl` operations.
2
3use crate::errno::SysResult;
4use crate::fd::RawFd;
5use crate::raw::{nr, syscall1, syscall2, syscall3, syscall4};
6
7pub const STDIN_FILENO: RawFd = 0;
8pub const STDOUT_FILENO: RawFd = 1;
9pub const STDERR_FILENO: RawFd = 2;
10
11pub const F_DUPFD: i32 = 0;
12pub const F_GETFD: i32 = 1;
13pub const F_SETFD: i32 = 2;
14pub const F_GETFL: i32 = 3;
15pub const F_SETFL: i32 = 4;
16pub const F_SETLK: i32 = 6;
17pub const F_SETLKW: i32 = 7;
18pub const F_DUPFD_CLOEXEC: i32 = 1030;
19
20pub const FD_CLOEXEC: i32 = 1;
21
22pub const F_RDLCK: i16 = 0;
23pub const F_WRLCK: i16 = 1;
24pub const F_UNLCK: i16 = 2;
25
26pub const TCGETS: u64 = 0x5401;
27pub const FIONBIO: u64 = 0x5421;
28
29/// Advisory file-lock record for `fcntl` (`F_SETLK` / `F_SETLKW`).
30#[repr(C)]
31#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
32pub struct Flock {
33    pub l_type: i16,
34    pub l_whence: i16,
35    pub l_start: i64,
36    pub l_len: i64,
37    pub l_pid: i32,
38}
39
40/// Scatter/gather I/O vector (`struct iovec`).
41#[repr(C)]
42#[derive(Clone, Copy, Debug, Eq, PartialEq)]
43pub struct IoVec {
44    pub iov_base: *mut u8,
45    pub iov_len: usize,
46}
47
48impl Default for IoVec {
49    fn default() -> Self {
50        Self {
51            iov_base: core::ptr::null_mut(),
52            iov_len: 0,
53        }
54    }
55}
56
57/// Closes an open file descriptor.
58pub fn close(fd: RawFd) -> SysResult<()> {
59    // SAFETY: `CLOSE` takes a single integer file descriptor.
60    unsafe {
61        syscall1(nr::CLOSE, fd as usize)?;
62    }
63    Ok(())
64}
65
66/// Reads up to `len` bytes from `fd` into raw pointer `buf`.
67///
68/// # Safety
69///
70/// `buf` must be valid for writes of `len` bytes (when `len > 0`).
71pub unsafe fn read_raw(fd: RawFd, buf: *mut u8, len: usize) -> SysResult<usize> {
72    // SAFETY: Caller guarantees `buf` is valid for `len` writable bytes.
73    unsafe { syscall3(nr::READ, fd as usize, buf as usize, len) }
74}
75
76/// Reads bytes from `fd` into `buf`, returning the number of bytes read.
77pub fn read(fd: RawFd, buf: &mut [u8]) -> SysResult<usize> {
78    // SAFETY: `buf` is a valid mutable slice.
79    unsafe { read_raw(fd, buf.as_mut_ptr(), buf.len()) }
80}
81
82/// Writes up to `len` bytes from raw pointer `buf` to `fd`.
83///
84/// # Safety
85///
86/// `buf` must be valid for reads of `len` bytes (when `len > 0`).
87pub unsafe fn write_raw(fd: RawFd, buf: *const u8, len: usize) -> SysResult<usize> {
88    // SAFETY: Caller guarantees `buf` is valid for `len` readable bytes.
89    unsafe { syscall3(nr::WRITE, fd as usize, buf as usize, len) }
90}
91
92/// Writes bytes from `buf` to `fd`, returning the number of bytes written.
93pub fn write(fd: RawFd, buf: &[u8]) -> SysResult<usize> {
94    // SAFETY: `buf` is a valid shared slice.
95    unsafe { write_raw(fd, buf.as_ptr(), buf.len()) }
96}
97
98/// Reads from `fd` at `offset` into `buf` without changing the file offset.
99pub fn pread(fd: RawFd, buf: &mut [u8], offset: i64) -> SysResult<usize> {
100    // SAFETY: `buf` is a valid mutable slice.
101    unsafe {
102        syscall4(
103            nr::PREAD64,
104            fd as usize,
105            buf.as_mut_ptr() as usize,
106            buf.len(),
107            offset as usize,
108        )
109    }
110}
111
112/// Writes `buf` to `fd` at `offset` without changing the file offset.
113pub fn pwrite(fd: RawFd, buf: &[u8], offset: i64) -> SysResult<usize> {
114    // SAFETY: `buf` is a valid shared slice.
115    unsafe {
116        syscall4(
117            nr::PWRITE64,
118            fd as usize,
119            buf.as_ptr() as usize,
120            buf.len(),
121            offset as usize,
122        )
123    }
124}
125
126/// Writes gather buffers `iov` to `fd`.
127///
128/// # Safety
129///
130/// Every [`IoVec`] entry in `iov` must point to valid readable memory for its `iov_len`.
131pub unsafe fn writev(fd: RawFd, iov: &[IoVec]) -> SysResult<usize> {
132    // SAFETY: Caller guarantees each `IoVec` buffer is readable for `iov_len` bytes.
133    unsafe { syscall3(nr::WRITEV, fd as usize, iov.as_ptr() as usize, iov.len()) }
134}
135
136/// Creates a unidirectional pipe pair `[read_fd, write_fd]` with `flags`.
137pub fn pipe2(flags: i32) -> SysResult<[RawFd; 2]> {
138    let mut fds = [0i32; 2];
139    // SAFETY: `fds` is a valid 2-element `i32` array on the stack.
140    unsafe {
141        syscall2(nr::PIPE2, fds.as_mut_ptr() as usize, flags as u32 as usize)?;
142    }
143    Ok(fds)
144}
145
146/// Duplicates file descriptor `fd` to the lowest-numbered unused descriptor.
147pub fn dup(fd: RawFd) -> SysResult<RawFd> {
148    // SAFETY: `DUP` takes a single file descriptor.
149    let raw = unsafe { syscall1(nr::DUP, fd as usize)? };
150    Ok(raw as RawFd)
151}
152
153/// Duplicates `oldfd` onto `newfd` (implementing POSIX `dup2` semantics on AArch64).
154///
155/// When `oldfd == newfd`, validates that `oldfd` is open via `F_GETFD` and returns `newfd`
156/// without clearing `FD_CLOEXEC`. Otherwise delegates to `dup3(oldfd, newfd, 0)`.
157pub fn dup2(oldfd: RawFd, newfd: RawFd) -> SysResult<RawFd> {
158    if oldfd == newfd {
159        fcntl(oldfd, F_GETFD, 0)?;
160        Ok(newfd)
161    } else {
162        dup3(oldfd, newfd, 0)
163    }
164}
165
166/// Duplicates `oldfd` onto `newfd` with `flags` (such as `O_CLOEXEC`).
167pub fn dup3(oldfd: RawFd, newfd: RawFd, flags: i32) -> SysResult<RawFd> {
168    // SAFETY: `DUP3` takes two file descriptors and integer flags.
169    let raw = unsafe {
170        syscall3(
171            nr::DUP3,
172            oldfd as usize,
173            newfd as usize,
174            flags as u32 as usize,
175        )?
176    };
177    Ok(raw as RawFd)
178}
179
180/// Performs a raw `fcntl` command on `fd`.
181pub fn fcntl(fd: RawFd, cmd: i32, arg: usize) -> SysResult<i32> {
182    // SAFETY: `FCNTL` takes a file descriptor, command code, and argument word.
183    let raw = unsafe { syscall3(nr::FCNTL, fd as usize, cmd as u32 as usize, arg)? };
184    Ok(raw as i32)
185}
186
187/// Invokes a raw device control operation (`ioctl`) on `fd`, returning the raw `usize` result.
188///
189/// # Safety
190///
191/// `arg` must satisfy the pointer/type contract of `request`.
192pub unsafe fn ioctl_raw(fd: RawFd, request: u64, arg: usize) -> SysResult<usize> {
193    // SAFETY: Caller guarantees `arg` is valid for `request`.
194    unsafe { syscall3(nr::IOCTL, fd as usize, request as usize, arg) }
195}
196
197/// Invokes a device control operation (`ioctl`) on `fd`.
198///
199/// # Safety
200///
201/// `arg` must satisfy the pointer/type contract of `request`.
202pub unsafe fn ioctl(fd: RawFd, request: u64, arg: usize) -> SysResult<i32> {
203    // SAFETY: Caller guarantees `arg` is valid for `request`.
204    let raw = unsafe { ioctl_raw(fd, request, arg)? };
205    Ok(raw as i32)
206}
207
208/// Returns `true` if `fd` refers to a terminal device (`TCGETS`).
209#[must_use]
210pub fn isatty(fd: RawFd) -> bool {
211    let mut termios = [0u8; 64];
212    // SAFETY: `termios` is a 64-byte stack buffer sufficient for `struct termios` under `TCGETS`.
213    unsafe { ioctl(fd, TCGETS, termios.as_mut_ptr() as usize).is_ok() }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219    use crate::errno::{EBADF, Errno};
220    use crate::raw::with_mock_syscall;
221
222    #[test]
223    fn dup2_same_fd_validates_with_fcntl_getfd() {
224        with_mock_syscall(
225            |nr, args| {
226                assert_eq!(nr, nr::FCNTL);
227                assert_eq!(args[0], 5);
228                assert_eq!(args[1], F_GETFD as usize);
229                Ok(FD_CLOEXEC as usize)
230            },
231            || {
232                assert_eq!(dup2(5, 5), Ok(5));
233            },
234        );
235
236        with_mock_syscall(
237            |nr, _args| {
238                assert_eq!(nr, nr::FCNTL);
239                Err(Errno(EBADF))
240            },
241            || {
242                assert_eq!(dup2(9, 9), Err(Errno(EBADF)));
243            },
244        );
245    }
246
247    #[test]
248    fn dup2_different_fd_routes_to_dup3() {
249        with_mock_syscall(
250            |nr, args| {
251                assert_eq!(nr, nr::DUP3);
252                assert_eq!(args[0], 3);
253                assert_eq!(args[1], 7);
254                assert_eq!(args[2], 0);
255                Ok(7)
256            },
257            || {
258                assert_eq!(dup2(3, 7), Ok(7));
259            },
260        );
261    }
262}