Skip to content

Commit 53200b3

Browse files
mattsu2020cakebaker
authored andcommitted
refactor: replace File::from_raw_fd with nix::sys::stat for safer stdin size check
Replace the unsafe File::from_raw_fd approach with nix::sys::stat::fstat for checking if stdin is a small file. This change improves safety by avoiding manual file descriptor management and using the nix crate's safer interface for file statistics.
1 parent bf955a9 commit 53200b3

1 file changed

Lines changed: 7 additions & 6 deletions

File tree

src/uu/wc/src/wc.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -297,12 +297,13 @@ impl<'a> Input<'a> {
297297

298298
#[cfg(unix)]
299299
fn is_stdin_small_file() -> bool {
300-
use std::os::unix::io::{AsRawFd, FromRawFd};
301-
// Safety: we'll rely on Rust to give us a valid RawFd for stdin with which we can attempt to
302-
// open a File, but only for the sake of fetching .metadata(). ManuallyDrop will ensure we
303-
// don't do anything else to the FD if anything unexpected happens.
304-
let f = std::mem::ManuallyDrop::new(unsafe { File::from_raw_fd(io::stdin().as_raw_fd()) });
305-
matches!(f.metadata(), Ok(meta) if meta.is_file() && meta.len() <= (10 << 20))
300+
use nix::sys::stat;
301+
use std::os::fd::AsFd;
302+
303+
matches!(
304+
stat::fstat(io::stdin().as_fd()),
305+
Ok(meta) if meta.st_mode & libc::S_IFMT == libc::S_IFREG && meta.st_size <= (10 << 20)
306+
)
306307
}
307308

308309
#[cfg(not(unix))]

0 commit comments

Comments
 (0)