From 4c1a42fd88ddef736be3d5cace513218229f5813 Mon Sep 17 00:00:00 2001 From: Aditya <152765789+adityawrk@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:20:56 +0530 Subject: [PATCH 1/2] sort: report a full temporary file by name and exit 2 A write or close error on a temporary file printed only the errno and exited 1. GNU sort names that file and exits 2: sort: close failed: t/: No space left on device Flush and close the temporary file explicitly, and report the failure with its path. On Linux, close can return EINTR after the descriptor is already closed, so do not retry it. Fixes #16851 --- src/uu/sort/locales/en-US.ftl | 1 + src/uu/sort/locales/fr-FR.ftl | 1 + src/uu/sort/src/ext_sort/threaded.rs | 73 ++++++++++++++++++++++++++-- src/uu/sort/src/merge.rs | 73 ++++++++++++++++++++++++---- src/uu/sort/src/sort.rs | 30 ++++++++++++ tests/by-util/test_sort.rs | 12 +++-- 6 files changed, 174 insertions(+), 16 deletions(-) diff --git a/src/uu/sort/locales/en-US.ftl b/src/uu/sort/locales/en-US.ftl index bae3efeecf3..95924bd9f51 100644 --- a/src/uu/sort/locales/en-US.ftl +++ b/src/uu/sort/locales/en-US.ftl @@ -17,6 +17,7 @@ sort-parse-key-error = failed to parse key {$key}: {$msg} sort-cannot-read = cannot read: {$path}: {$error} sort-read-failed = read failed: {$error} sort-open-tmp-file-failed = failed to open temporary file: {$error} +sort-tmp-file-close-failed = close failed: {$path}: {$error} sort-compress-prog-execution-failed = could not run compress program '{$prog}': {$error} sort-compress-prog-terminated-abnormally = {$prog} terminated abnormally sort-cannot-create-tmp-file = cannot create temporary file in {$path}: diff --git a/src/uu/sort/locales/fr-FR.ftl b/src/uu/sort/locales/fr-FR.ftl index 6a00e99b9bd..8e19c62b426 100644 --- a/src/uu/sort/locales/fr-FR.ftl +++ b/src/uu/sort/locales/fr-FR.ftl @@ -17,6 +17,7 @@ sort-parse-key-error = échec d'analyse de la clé {$key} : {$msg} sort-cannot-read = impossible de lire : {$path} : {$error} sort-read-failed = échec de lecture : {$error} sort-open-tmp-file-failed = échec d'ouverture du fichier temporaire : {$error} +sort-tmp-file-close-failed = échec de fermeture : {$path} : {$error} sort-compress-prog-execution-failed = impossible d'exécuter le programme de compression '{$prog}' : {$error} sort-compress-prog-terminated-abnormally = {$prog} s'est terminé anormalement sort-cannot-create-tmp-file = impossible de créer un fichier temporaire dans {$path} : diff --git a/src/uu/sort/src/ext_sort/threaded.rs b/src/uu/sort/src/ext_sort/threaded.rs index 0c5706c10e8..d63698da0ef 100644 --- a/src/uu/sort/src/ext_sort/threaded.rs +++ b/src/uu/sort/src/ext_sort/threaded.rs @@ -14,7 +14,7 @@ use std::sync::mpsc::{Receiver, SyncSender}; use std::thread; use itertools::Itertools; -use uucore::error::{UResult, strip_errno}; +use uucore::error::{UError, UResult, strip_errno}; use crate::Output; use crate::chunks::RecycledChunk; @@ -23,7 +23,7 @@ use crate::merge::WriteablePlainTmpFile; use crate::merge::WriteableTmpFile; use crate::tmp_dir::{TmpDirWrapper, TmpPath}; use crate::{ - GlobalSettings, Line, + GlobalSettings, Line, SortError, chunks::{self, Chunk}, compare_by, merge, print_sorted, sort_by, }; @@ -293,8 +293,13 @@ fn write( compress_prog: Option<&str>, separator: u8, ) -> UResult { + let path = file.1.path().to_owned(); let mut tmp_file = I::create(file, compress_prog)?; - write_lines(chunk.lines(), tmp_file.as_write(), separator)?; + // GNU reports a full temporary file when it closes it (`close failed`), + // including when the write that filled the buffer is what failed. + write_lines(chunk.lines(), tmp_file.as_write(), separator).map_err(|error| { + Box::new(SortError::TmpFileCloseFailed { path, error }) as Box + })?; tmp_file.finished_writing() } @@ -308,9 +313,12 @@ fn write_lines(lines: &[Line], writer: &mut T, separator: u8) -> std:: #[cfg(test)] mod tests { + use std::error::Error; use std::io; + use std::path::Path; use super::*; + use crate::chunks::{ChunkContents, LineData}; struct FailingWriter(io::ErrorKind); @@ -339,4 +347,63 @@ mod tests { assert_eq!(result.unwrap_err().kind(), io::ErrorKind::StorageFull); } + + fn one_line_chunk(payload: &[u8]) -> Chunk { + let mut data = payload.to_vec(); + data.push(b'\n'); + Chunk::try_new(data, |buffer| { + let line = &buffer[..buffer.len() - 1]; + Ok::<_, std::convert::Infallible>(ChunkContents { + lines: vec![Line { line, index: 0 }], + line_data: LineData::default(), + token_buffer: Vec::new(), + line_count_hint: 1, + }) + }) + .unwrap() + } + + fn assert_close_failed(err: &(dyn UError + 'static), expected: &Path) { + assert_eq!(err.code(), 2, "{err}"); + match (err as &(dyn Error + 'static)) + .downcast_ref::() + .unwrap_or_else(|| panic!("expected SortError, got {err}")) + { + SortError::TmpFileCloseFailed { path, .. } => assert_eq!(path, expected), + other => panic!("expected a temporary-file close failure, got {other:?}"), + } + } + + /// A read-only temporary file fails when the buffered chunk is flushed. + #[test] + fn buffered_temp_write_reports_close_failure_with_the_file_name() { + let dir = tempfile::tempdir().unwrap(); + let mut tmp_dir = TmpDirWrapper::new(dir.path().to_owned()); + let (file, tmp_path) = tmp_dir.next_file().unwrap(); + let expected = tmp_path.path().to_owned(); + drop(file); + let ro = File::open(&expected).unwrap(); + let chunk = one_line_chunk(b"line"); + let Err(err) = write::(&chunk, (ro, tmp_path), None, b'\n') else { + panic!("expected the temporary file write to fail"); + }; + assert_close_failed(err.as_ref(), &expected); + } + + /// A payload larger than the buffer fails during the write itself. + #[test] + fn large_temp_write_reports_close_failure_with_the_file_name() { + let dir = tempfile::tempdir().unwrap(); + let mut tmp_dir = TmpDirWrapper::new(dir.path().to_owned()); + let (file, tmp_path) = tmp_dir.next_file().unwrap(); + let expected = tmp_path.path().to_owned(); + drop(file); + let ro = File::open(&expected).unwrap(); + let payload = vec![b'x'; 20 * 1024]; + let chunk = one_line_chunk(&payload); + let Err(err) = write::(&chunk, (ro, tmp_path), None, b'\n') else { + panic!("expected the temporary file write to fail"); + }; + assert_close_failed(err.as_ref(), &expected); + } } diff --git a/src/uu/sort/src/merge.rs b/src/uu/sort/src/merge.rs index 79fab4b86e2..dee0c6147ce 100644 --- a/src/uu/sort/src/merge.rs +++ b/src/uu/sort/src/merge.rs @@ -26,7 +26,7 @@ use std::{ thread::{self, JoinHandle}, }; -use uucore::error::{FromIo, UResult}; +use uucore::error::{FromIo, UError, UResult}; use uucore::fs::FileInformation; use crate::{ @@ -155,10 +155,17 @@ pub fn merge_with_file_limit< while files.len() > 0 { // Create the output before opening this batch's inputs, so that // creating it doesn't compete with them for file descriptors. - let mut tmp_file = - Tmp::create(tmp_dir.next_file()?, settings.compress_prog.as_deref())?; + let (file, tmp_path) = tmp_dir.next_file()?; + let failed_path = tmp_path.path().to_owned(); + let mut tmp_file = Tmp::create((file, tmp_path), settings.compress_prog.as_deref())?; let merger = merge_without_limit(files.by_ref().take(batch_size), settings)?; - merger.write_all_to(settings, tmp_file.as_write(), || "write failed".into())?; + merger.write_all_to(settings, tmp_file.as_write(), |error| { + SortError::TmpFileCloseFailed { + path: failed_path, + error, + } + .into() + })?; temporary_files.push(tmp_file.finished_writing()?); } merge_with_file_limit::<_, _, Tmp>( @@ -353,16 +360,18 @@ impl FileMerger<'_> { fn write_all(self, settings: &GlobalSettings, output: Output) -> UResult<()> { let ctx = output.write_failed_context(); let mut out = output.into_write()?; - self.write_all_to(settings, &mut out, &ctx)?; + self.write_all_to(settings, &mut out, |error| { + error.map_err_context(&ctx) as Box + })?; out.flush().map_err_context(ctx) } - /// Write the merged contents to `out`, reporting write errors with `ctx`. + /// Write the merged contents to `out`, reporting write errors with `map_err`. fn write_all_to( mut self, settings: &GlobalSettings, out: &mut impl Write, - ctx: impl FnOnce() -> String, + map_err: impl FnOnce(io::Error) -> Box, ) -> UResult<()> { let write_result = loop { match self.write_next(out, settings) { @@ -400,7 +409,7 @@ impl FileMerger<'_> { let reader_result = reader_join_handle.join().unwrap(); // A write failure is what the user needs to hear about; the reader hitting an error // on the way down is secondary. - write_result.map_err_context(ctx).and(reader_result) + write_result.map_err(map_err).and(reader_result) } fn write_next( @@ -463,6 +472,34 @@ impl FileMerger<'_> { } } +/// Close `file` and return an error from `close`. +/// +/// `File`'s destructor ignores that error. Non-Unix targets drop the handle; +/// the caller has already flushed. That drop cannot fail, but the signature +/// stays a `Result` so every caller reports a close failure the same way. +#[cfg_attr(not(unix), allow(clippy::unnecessary_wraps))] +fn close_tmp_file(file: File) -> io::Result<()> { + #[cfg(unix)] + { + use std::os::fd::IntoRawFd; + let fd = file.into_raw_fd(); + // SAFETY: `fd` is exclusively owned and is not used after this call. + // Do not retry on EINTR. On Linux the descriptor is already closed, + // and a retry could close a descriptor the process has reused. + let rc = unsafe { libc::close(fd) }; + if rc == 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } + #[cfg(not(unix))] + { + drop(file); + Ok(()) + } +} + /// Wait for the child to exit and check its exit code. fn check_child_success(mut child: Child, program: &str) -> UResult<()> { if matches!(child.wait().map(|e| e.code()), Ok(Some(0) | None) | Err(_)) { @@ -522,6 +559,19 @@ impl WriteableTmpFile for WriteablePlainTmpFile { } fn finished_writing(self) -> UResult { + let path = self.path.path().to_owned(); + // `BufWriter`'s destructor drops a flush error, and `File`'s destructor + // drops a close error. GNU `sort` reports either as + // `close failed: `, which is the ENOSPC seen with `-T` on a + // full temporary filesystem. + let file = self + .file + .into_inner() + .map_err(|err| SortError::TmpFileCloseFailed { + path: path.clone(), + error: err.into_error(), + })?; + close_tmp_file(file).map_err(|error| SortError::TmpFileCloseFailed { path, error })?; Ok(ClosedPlainTmpFile { path: self.path }) } @@ -599,7 +649,12 @@ impl WriteableTmpFile for WriteableCompressedTmpFile { } fn finished_writing(self) -> UResult { - drop(self.child_stdin); + let path = self.path.path().to_owned(); + let mut stdin = self.child_stdin; + stdin + .flush() + .map_err(|error| SortError::TmpFileCloseFailed { path, error })?; + drop(stdin); check_child_success(self.child, &self.compress_prog)?; Ok(ClosedCompressedTmpFile { path: self.path, diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index cec38b32a24..54d958c657a 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -160,6 +160,14 @@ pub enum SortError { #[error("{}", translate!("sort-open-tmp-file-failed", "error" => strip_errno(.error)))] OpenTmpFileFailed { error: std::io::Error }, + /// Writing, flushing, or closing a temporary file failed. + /// GNU `sort` reports all of these as `close failed: ` and exits 2. + #[error("{}", translate_text!("sort-tmp-file-close-failed", "path" => format!("{}", .path.maybe_quote()), "error" => strip_errno(.error)))] + TmpFileCloseFailed { + path: PathBuf, + error: std::io::Error, + }, + #[error("{}", translate!("sort-compress-prog-execution-failed", "prog" => .prog, "error" => strip_errno(.error)))] CompressProgExecutionFailed { prog: String, error: std::io::Error }, @@ -3469,6 +3477,28 @@ mod tests { use super::*; + #[test] + fn tmp_file_enospc_names_the_file_and_exits_2() { + uucore::locale::setup_localization("sort").unwrap(); + // 28 is ENOSPC on Linux and macOS. + let error = std::io::Error::from_raw_os_error(28); + let err = SortError::TmpFileCloseFailed { + path: PathBuf::from("t/chunk"), + error, + }; + assert_eq!(UError::code(&err), 2); + let message = err.to_string(); + assert!( + message.starts_with("close failed: "), + "unexpected message: {message}" + ); + assert!(message.contains("t/chunk"), "unexpected message: {message}"); + assert!( + message.contains("No space left on device"), + "unexpected message: {message}" + ); + } + fn tokenize_helper(line: &[u8], separator: Option) -> Vec { let mut buffer = vec![]; let precomputed = Precomputed::default(); diff --git a/tests/by-util/test_sort.rs b/tests/by-util/test_sort.rs index 7f63dcec076..deae11b2763 100644 --- a/tests/by-util/test_sort.rs +++ b/tests/by-util/test_sort.rs @@ -1550,8 +1550,8 @@ fn test_merge_write_error_does_not_panic() { } } -// Regression test: a full temporary filesystem must make external sort fail -// cleanly instead of panicking while spilling a sorted chunk. +// Regression test: a full temporary filesystem must name the temporary file, +// exit 2, and must not panic while spilling a sorted chunk (#16851). #[test] #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] fn test_spill_write_error_does_not_panic() { @@ -1574,13 +1574,17 @@ fn test_spill_write_error_does_not_panic() { scene .ucmd() .args(&[ - "--buffer-size=1", + // Larger than the 8 KiB temporary-file buffer, so ENOSPC is hit + // while writing the chunk and not only on the final flush. + "--buffer-size=64K", "--temporary-directory", tmp_dir, "input.txt", ]) - .fails_with_code(1) + .fails_with_code(2) + .stderr_contains("close failed:") .stderr_contains("No space left on device") + .stderr_contains(tmp_dir) .stderr_does_not_contain("panicked"); } From 09d7bd5a29b90173b0cd987fde5076fb8d8e3e9f Mon Sep 17 00:00:00 2001 From: Aditya <152765789+adityawrk@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:14:03 +0530 Subject: [PATCH 2/2] sort: make the ENOSPC message test portable Errno 28 is ENOSPC on Unix and ERROR_OUT_OF_PAPER on Windows, so the unit test expected "No space left on device" and observed "The printer is out of paper." Check the close-failed format with a disk-full error instead of a raw errno. --- src/uu/sort/src/sort.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index 54d958c657a..25850be9623 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -3480,8 +3480,11 @@ mod tests { #[test] fn tmp_file_enospc_names_the_file_and_exits_2() { uucore::locale::setup_localization("sort").unwrap(); - // 28 is ENOSPC on Linux and macOS. - let error = std::io::Error::from_raw_os_error(28); + // A raw errno is not portable: 28 is ENOSPC on Unix and + // ERROR_OUT_OF_PAPER on Windows. The message test checks the + // `close failed: : ` shape with a disk-full error. + let error = std::io::Error::new(std::io::ErrorKind::StorageFull, "No space left on device"); + let expected = strip_errno(&error); let err = SortError::TmpFileCloseFailed { path: PathBuf::from("t/chunk"), error, @@ -3493,10 +3496,7 @@ mod tests { "unexpected message: {message}" ); assert!(message.contains("t/chunk"), "unexpected message: {message}"); - assert!( - message.contains("No space left on device"), - "unexpected message: {message}" - ); + assert!(message.contains(&expected), "unexpected message: {message}"); } fn tokenize_helper(line: &[u8], separator: Option) -> Vec {