Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/uu/sort/locales/en-US.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -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}:
Expand Down
1 change: 1 addition & 0 deletions src/uu/sort/locales/fr-FR.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -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} :
Expand Down
73 changes: 70 additions & 3 deletions src/uu/sort/src/ext_sort/threaded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
};
Expand Down Expand Up @@ -293,8 +293,13 @@ fn write<I: WriteableTmpFile>(
compress_prog: Option<&str>,
separator: u8,
) -> UResult<I::Closed> {
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<dyn UError>
})?;
tmp_file.finished_writing()
}

Expand All @@ -308,9 +313,12 @@ fn write_lines<T: Write>(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);

Expand Down Expand Up @@ -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::<SortError>()
.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::<WriteablePlainTmpFile>(&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::<WriteablePlainTmpFile>(&chunk, (ro, tmp_path), None, b'\n') else {
panic!("expected the temporary file write to fail");
};
assert_close_failed(err.as_ref(), &expected);
}
}
73 changes: 64 additions & 9 deletions src/uu/sort/src/merge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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>(
Expand Down Expand Up @@ -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<dyn UError>
})?;
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<dyn UError>,
) -> UResult<()> {
let write_result = loop {
match self.write_next(out, settings) {
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(_)) {
Expand Down Expand Up @@ -522,6 +559,19 @@ impl WriteableTmpFile for WriteablePlainTmpFile {
}

fn finished_writing(self) -> UResult<Self::Closed> {
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: <temp file>`, 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 })
}

Expand Down Expand Up @@ -599,7 +649,12 @@ impl WriteableTmpFile for WriteableCompressedTmpFile {
}

fn finished_writing(self) -> UResult<Self::Closed> {
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,
Expand Down
30 changes: 30 additions & 0 deletions src/uu/sort/src/sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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: <file>` 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 },

Expand Down Expand Up @@ -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();
// A raw errno is not portable: 28 is ENOSPC on Unix and

@xtqqczze xtqqczze Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// ERROR_OUT_OF_PAPER on Windows. The message test checks the
// `close failed: <path>: <error>` 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,
};
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(&expected), "unexpected message: {message}");
}

fn tokenize_helper(line: &[u8], separator: Option<u8>) -> Vec<Field> {
let mut buffer = vec![];
let precomputed = Precomputed::default();
Expand Down
12 changes: 8 additions & 4 deletions tests/by-util/test_sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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");
}

Expand Down
Loading