From 0eafb87ba0b027613d19bc07fb6b65d04d5f38fa Mon Sep 17 00:00:00 2001 From: mattsu Date: Mon, 9 Mar 2026 19:38:26 +0900 Subject: [PATCH] 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. --- src/uu/wc/src/wc.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/uu/wc/src/wc.rs b/src/uu/wc/src/wc.rs index 61085f93316..0c09c2c3a43 100644 --- a/src/uu/wc/src/wc.rs +++ b/src/uu/wc/src/wc.rs @@ -297,12 +297,13 @@ impl<'a> Input<'a> { #[cfg(unix)] fn is_stdin_small_file() -> bool { - use std::os::unix::io::{AsRawFd, FromRawFd}; - // Safety: we'll rely on Rust to give us a valid RawFd for stdin with which we can attempt to - // open a File, but only for the sake of fetching .metadata(). ManuallyDrop will ensure we - // don't do anything else to the FD if anything unexpected happens. - let f = std::mem::ManuallyDrop::new(unsafe { File::from_raw_fd(io::stdin().as_raw_fd()) }); - matches!(f.metadata(), Ok(meta) if meta.is_file() && meta.len() <= (10 << 20)) + use nix::sys::stat; + use std::os::fd::AsFd; + + matches!( + stat::fstat(io::stdin().as_fd()), + Ok(meta) if meta.st_mode & libc::S_IFMT == libc::S_IFREG && meta.st_size <= (10 << 20) + ) } #[cfg(not(unix))]