From 2614d760a895b01d79a799cc904b05ce08d6979e Mon Sep 17 00:00:00 2001 From: Yunus Ardaguney Date: Sun, 29 Nov 2026 20:19:39 +0300 Subject: [PATCH 1/3] cmp, diffutils: handle stdout write errors without panicking (#165) --- src/cmp.rs | 64 ++++++++++++++++++++++++++++----------- src/main.rs | 18 ++++++++--- tests/by-util/test_cmp.rs | 58 +++++++++++++++++++++++++++++++++++ 3 files changed, 119 insertions(+), 21 deletions(-) diff --git a/src/cmp.rs b/src/cmp.rs index 5868a74d..9856310b 100644 --- a/src/cmp.rs +++ b/src/cmp.rs @@ -419,15 +419,14 @@ pub fn cmp(params: &Params) -> Result { &mut output, params, )?; - stdout.write_all(output.as_slice()).map_err(|e| { - format!( - "{}: error printing output: {e}", - params.executable.to_string_lossy() - ) - })?; + stdout + .write_all(output.as_slice()) + .map_err(|e| stdout_error(¶ms.executable, &e))?; output.clear(); } else { - report_difference(from_byte, to_byte, at_byte, at_line, params); + write_difference(&mut stdout, from_byte, to_byte, at_byte, at_line, params) + .and_then(|()| stdout.flush()) + .map_err(|e| stdout_error(¶ms.executable, &e))?; return Ok(Cmp::Different); } } @@ -451,6 +450,9 @@ pub fn cmp(params: &Params) -> Result { to.consume(consumed); } + stdout + .flush() + .map_err(|e| stdout_error(¶ms.executable, &e))?; Ok(compare) } @@ -477,7 +479,20 @@ pub fn main(opts: Peekable) -> ExitCode { }; if params.help { - println!("{}", usage_string(¶ms.executable.to_string_lossy())); + let mut out = io::stdout().lock(); + let written = writeln!( + out, + "{}", + usage_string(¶ms.executable.to_string_lossy()) + ) + .and_then(|()| out.flush()); + if let Err(e) = written { + let msg = stdout_error(¶ms.executable, &e); + if !msg.is_empty() { + eprintln!("{msg}"); + return ExitCode::from(2); + } + } return ExitCode::SUCCESS; } @@ -491,7 +506,7 @@ pub fn main(opts: Peekable) -> ExitCode { Ok(Cmp::Equal) => ExitCode::SUCCESS, Ok(Cmp::Different) => ExitCode::from(1), Err(e) => { - if !params.quiet { + if !params.quiet && !e.is_empty() { eprintln!("{e}"); } ExitCode::from(2) @@ -698,15 +713,16 @@ fn report_eof( } #[inline] -fn report_difference( +fn write_difference( + out: &mut W, from_byte: u8, to_byte: u8, at_byte: BytesLimitU64, at_line: u64, params: &Params, -) { +) -> io::Result<()> { if params.quiet { - return; + return Ok(()); } let term = if is_posix_locale("LC_MESSAGES") && !params.print_bytes { @@ -714,23 +730,37 @@ fn report_difference( } else { "byte" }; - print!( + write!( + out, "{} {} differ: {term} {}, line {}", params.from.to_string_lossy(), params.to.to_string_lossy(), at_byte, at_line - ); + )?; if params.print_bytes { - print!( + write!( + out, " is {:>3o} {} {:>3o} {}", from_byte, format_visible_byte(from_byte), to_byte, format_visible_byte(to_byte) - ); + )?; + } + writeln!(out) +} + +fn stdout_error(executable: &std::ffi::OsStr, err: &io::Error) -> String { + if err.kind() == io::ErrorKind::BrokenPipe { + String::new() + } else { + format_failure_to_read_input_file( + &OsString::from(executable), + &OsString::from("standard output"), + err, + ) } - println!(); } #[cfg(test)] diff --git a/src/main.rs b/src/main.rs index 2be28099..1f06ad28 100644 --- a/src/main.rs +++ b/src/main.rs @@ -43,10 +43,20 @@ fn name(binary_path: &Path) -> &OsStr { const VERSION: &str = env!("CARGO_PKG_VERSION"); fn usage(name: &str) { - println!("{name} {VERSION} (multi-call binary)\n"); - println!("Usage: {name} [function [arguments...]]\n"); - println!("Currently defined functions:\n"); - println!(" cmp, diff\n"); + let s = format!( + "{name} {VERSION} (multi-call binary)\n\nUsage: {name} [function [arguments...]]\n\nCurrently defined functions:\n\n cmp, diff\n" + ); + let mut out = std::io::stdout().lock(); + let written = std::io::Write::write_all(&mut out, s.as_bytes()) + .and_then(|()| std::io::Write::flush(&mut out)); + if let Err(e) = written { + if e.kind() != std::io::ErrorKind::BrokenPipe { + let _ = std::io::Write::write_fmt( + &mut std::io::stderr().lock(), + format_args!("{name}: standard output: {e}\n"), + ); + } + } } fn second_arg_error(name: &OsStr) -> ! { diff --git a/tests/by-util/test_cmp.rs b/tests/by-util/test_cmp.rs index 7a2cfa38..8f964041 100644 --- a/tests/by-util/test_cmp.rs +++ b/tests/by-util/test_cmp.rs @@ -421,3 +421,61 @@ fn cmp_difference_term_follows_messages_locale( .fails_with_code(1) .stdout_is(format!("a b differ: {term} 1, line 1\n")); } + +#[cfg(target_os = "linux")] +#[test] +fn write_error() { + use std::fs::File; + let (at, ts) = at_and_ts!(); + at.write("a", "left\n"); + at.write("b", "right\n"); + + ts.ucmd() + .args(&["a", "b"]) + .set_stdout(File::create("/dev/full").unwrap()) + .fails_with_code(2) + .stderr_is("cmp: standard output: No space left on device\n"); +} + +#[cfg(target_os = "linux")] +#[test] +fn write_error_verbose() { + use std::fs::File; + let (at, ts) = at_and_ts!(); + at.write("a", "left\n"); + at.write("b", "right\n"); + + ts.ucmd() + .args(&["-l", "a", "b"]) + .set_stdout(File::create("/dev/full").unwrap()) + .fails_with_code(2) + .stderr_is("cmp: standard output: No space left on device\n"); +} + +#[cfg(target_os = "linux")] +#[test] +fn write_error_help() { + use std::fs::File; + let (_at, ts) = at_and_ts!(); + + ts.ucmd() + .arg("--help") + .set_stdout(File::create("/dev/full").unwrap()) + .fails_with_code(2) + .stderr_is("cmp: standard output: No space left on device\n"); +} + +#[cfg(target_os = "linux")] +#[test] +fn multicall_write_error() { + use std::fs::File; + use std::process::Command; + + let output = Command::new(crate::TESTS_BINARY) + .stdout(File::create("/dev/full").unwrap()) + .output() + .unwrap(); + assert_ne!(output.status.code(), Some(134)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("Expected utility name as second argument, got nothing.")); +} From 75dc64576cb4149e84cd4687d263ca6bf23ca9a0 Mon Sep 17 00:00:00 2001 From: Yunus Ardaguney Date: Sun, 29 Nov 2026 20:46:58 +0300 Subject: [PATCH 2/3] cmp: flush stdout before reporting EOF to catch write errors --- src/cmp.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cmp.rs b/src/cmp.rs index 9856310b..aae92565 100644 --- a/src/cmp.rs +++ b/src/cmp.rs @@ -375,6 +375,10 @@ pub fn cmp(params: &Params) -> Result { ¶ms.to.to_string_lossy() }; + stdout + .flush() + .map_err(|e| stdout_error(¶ms.executable, &e))?; + report_eof(at_byte, at_line, start_of_line, eof_on, params); return Ok(Cmp::Different); } From 5b556dc512887c2c8ffe92bc713c2cced8238ba3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yunus=20Arda=20G=C3=BCney?= <64425746+yunusarda-sudo@users.noreply.github.com> Date: Mon, 30 Nov 2026 07:59:54 +0300 Subject: [PATCH 3/3] cmp, diffutils: exit 2 on usage write errors and add CmpError Reuse format_failure_to_read_input_file for the multicall usage path, take &OsString in stdout_error, and check the exit code and stderr in the multicall /dev/full test. --- src/cmp.rs | 63 ++++++++++++++++++++++++--------------- src/main.rs | 36 +++++++++++++--------- tests/by-util/test_cmp.rs | 14 +++++++-- 3 files changed, 72 insertions(+), 41 deletions(-) diff --git a/src/cmp.rs b/src/cmp.rs index aae92565..5effdf45 100644 --- a/src/cmp.rs +++ b/src/cmp.rs @@ -313,9 +313,17 @@ pub enum Cmp { Different, } -pub fn cmp(params: &Params) -> Result { - let mut from = prepare_reader(¶ms.from, ¶ms.skip_a, params)?; - let mut to = prepare_reader(¶ms.to, ¶ms.skip_b, params)?; +#[derive(Debug)] +pub enum CmpError { + /// A reader that went away, as with `| head`. + BrokenPipe, + Message(String), +} + +pub fn cmp(params: &Params) -> Result { + let mut from = + prepare_reader(¶ms.from, ¶ms.skip_a, params).map_err(CmpError::Message)?; + let mut to = prepare_reader(¶ms.to, ¶ms.skip_b, params).map_err(CmpError::Message)?; let mut offset_width = params.max_bytes.unwrap_or(BytesLimitU64::MAX); @@ -355,13 +363,21 @@ pub fn cmp(params: &Params) -> Result { let mut compare = Cmp::Equal; loop { // Fill up our buffers. - let from_buf = from - .fill_buf() - .map_err(|e| format_failure_to_read_input_file(¶ms.executable, ¶ms.from, &e))?; - - let to_buf = to - .fill_buf() - .map_err(|e| format_failure_to_read_input_file(¶ms.executable, ¶ms.to, &e))?; + let from_buf = from.fill_buf().map_err(|e| { + CmpError::Message(format_failure_to_read_input_file( + ¶ms.executable, + ¶ms.from, + &e, + )) + })?; + + let to_buf = to.fill_buf().map_err(|e| { + CmpError::Message(format_failure_to_read_input_file( + ¶ms.executable, + ¶ms.to, + &e, + )) + })?; // Check for EOF conditions. if from_buf.is_empty() && to_buf.is_empty() { @@ -422,7 +438,7 @@ pub fn cmp(params: &Params) -> Result { offset_width, &mut output, params, - )?; + ); stdout .write_all(output.as_slice()) .map_err(|e| stdout_error(¶ms.executable, &e))?; @@ -491,11 +507,10 @@ pub fn main(opts: Peekable) -> ExitCode { ) .and_then(|()| out.flush()); if let Err(e) = written { - let msg = stdout_error(¶ms.executable, &e); - if !msg.is_empty() { + if let CmpError::Message(msg) = stdout_error(¶ms.executable, &e) { eprintln!("{msg}"); - return ExitCode::from(2); } + return ExitCode::from(2); } return ExitCode::SUCCESS; } @@ -510,8 +525,10 @@ pub fn main(opts: Peekable) -> ExitCode { Ok(Cmp::Equal) => ExitCode::SUCCESS, Ok(Cmp::Different) => ExitCode::from(1), Err(e) => { - if !params.quiet && !e.is_empty() { - eprintln!("{e}"); + if let CmpError::Message(e) = e { + if !params.quiet { + eprintln!("{e}"); + } } ExitCode::from(2) } @@ -612,7 +629,7 @@ fn format_verbose_difference( offset_width: usize, output: &mut Vec, params: &Params, -) -> Result<(), String> { +) { assert!(!params.quiet); let mut at_byte_buf = itoa::Buffer::new(); @@ -668,8 +685,6 @@ fn format_verbose_difference( output.push(b'\n'); } - - Ok(()) } #[inline] @@ -755,15 +770,15 @@ fn write_difference( writeln!(out) } -fn stdout_error(executable: &std::ffi::OsStr, err: &io::Error) -> String { +fn stdout_error(executable: &OsString, err: &io::Error) -> CmpError { if err.kind() == io::ErrorKind::BrokenPipe { - String::new() + CmpError::BrokenPipe } else { - format_failure_to_read_input_file( - &OsString::from(executable), + CmpError::Message(format_failure_to_read_input_file( + executable, &OsString::from("standard output"), err, - ) + )) } } diff --git a/src/main.rs b/src/main.rs index 1f06ad28..51d3ed08 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ use std::{ env::ArgsOs, ffi::{OsStr, OsString}, + io::{self, Write}, iter::Peekable, path::{Path, PathBuf}, process::ExitCode, @@ -42,26 +43,34 @@ fn name(binary_path: &Path) -> &OsStr { const VERSION: &str = env!("CARGO_PKG_VERSION"); -fn usage(name: &str) { +fn usage(name: &str) -> io::Result<()> { let s = format!( "{name} {VERSION} (multi-call binary)\n\nUsage: {name} [function [arguments...]]\n\nCurrently defined functions:\n\n cmp, diff\n" ); - let mut out = std::io::stdout().lock(); - let written = std::io::Write::write_all(&mut out, s.as_bytes()) - .and_then(|()| std::io::Write::flush(&mut out)); - if let Err(e) = written { - if e.kind() != std::io::ErrorKind::BrokenPipe { - let _ = std::io::Write::write_fmt( - &mut std::io::stderr().lock(), - format_args!("{name}: standard output: {e}\n"), - ); - } + let mut out = io::stdout().lock(); + out.write_all(s.as_bytes())?; + out.flush() +} + +fn report_stdout_error(name: &str, err: &io::Error) { + if err.kind() != io::ErrorKind::BrokenPipe { + eprintln!( + "{}", + utils::format_failure_to_read_input_file( + &OsString::from(name), + &OsString::from("standard output"), + err, + ) + ); } } fn second_arg_error(name: &OsStr) -> ! { eprintln!("Expected utility name as second argument, got nothing."); - usage(&name.to_string_lossy()); + if let Err(e) = usage(&name.to_string_lossy()) { + report_stdout_error(&name.to_string_lossy(), &e); + std::process::exit(2); + } std::process::exit(0); } @@ -86,9 +95,8 @@ fn main() -> ExitCode { name if name.ends_with(b"diff") => diff::main(args), name if name.ends_with(b"cmp") => cmp::main(args), name => { - use std::io::{stderr, Write as _}; let _ = writeln!( - stderr(), + io::stderr(), "{}: utility not supported", String::from_utf8_lossy(name) ); diff --git a/tests/by-util/test_cmp.rs b/tests/by-util/test_cmp.rs index 8f964041..c9dbc674 100644 --- a/tests/by-util/test_cmp.rs +++ b/tests/by-util/test_cmp.rs @@ -475,7 +475,15 @@ fn multicall_write_error() { .stdout(File::create("/dev/full").unwrap()) .output() .unwrap(); - assert_ne!(output.status.code(), Some(134)); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("Expected utility name as second argument, got nothing.")); + let name = std::path::Path::new(crate::TESTS_BINARY) + .file_stem() + .unwrap() + .to_string_lossy(); + assert_eq!(output.status.code(), Some(2)); + assert_eq!( + String::from_utf8_lossy(&output.stderr), + format!( + "Expected utility name as second argument, got nothing.\n{name}: standard output: No space left on device\n" + ) + ); }