From 4a83ecc4e528a6e8624bc659a5139fa8c38d817a Mon Sep 17 00:00:00 2001 From: muvahhid kilic Date: Fri, 6 Nov 2026 23:48:31 +0300 Subject: [PATCH] Read a shared handle's position without setting it Before a program is started with a `>>` handle, gash checks whether the handle is behind the end of the file. It read the position with `stream_position`, which is `SetFilePointerEx(h, 0, FILE_CURRENT)`: that reads the position and then sets it to what it read. When a program started earlier with the handle wrote in between, the position went back over that write, and the next write landed on top of it. `seek_std_append`, for a stdout or stderr that was append-only, had the same race: before every builtin write and every child it moved the handle to the end with `SetFilePointerEx(FILE_END)`, which reads the length and then sets the position. The position is now read with `NtQueryInformationFile`, which doesn't set it, and both places move the handle only when it is behind the end (`sys::seek_end_if_behind`). Writes through the handle only move it forward, so while every writer uses that one handle it is left alone. This was the occasional failure of 066_msys_append_concurrent.sh. Co-Authored-By: Claude Opus 5.5 --- src/io.rs | 13 +--- src/sys.rs | 36 ++++++++++- tests/append_only_stdout.rs | 67 ++++++++++++++++++++ tests/scripts/074_append_while_spawning.code | 1 + tests/scripts/074_append_while_spawning.out | 2 + tests/scripts/074_append_while_spawning.sh | 13 ++++ 6 files changed, 120 insertions(+), 12 deletions(-) create mode 100644 tests/append_only_stdout.rs create mode 100644 tests/scripts/074_append_while_spawning.code create mode 100644 tests/scripts/074_append_while_spawning.out create mode 100644 tests/scripts/074_append_while_spawning.sh diff --git a/src/io.rs b/src/io.rs index 0ba2efd..ac6e1fc 100644 --- a/src/io.rs +++ b/src/io.rs @@ -419,16 +419,9 @@ impl Handle { Handle::File(f) => (Stdio::from(f.try_clone()?), None), Handle::Append(f) => { // Writes through this handle leave its position at the end (see `write_all`), so it - // needs moving only when another handle to the file has appended since. Seeking - // every time could move it back over output that a program still writing through - // it adds meanwhile. The length is read first: writers on this handle only move - // the position forward, so they can't make it look behind. - let mut g = &**f; - if let (Ok(len), Ok(pos)) = (f.metadata().map(|m| m.len()), g.stream_position()) { - if pos < len { - let _ = g.seek(SeekFrom::End(0)); - } - } + // needs moving only when another handle to the file has appended since. Programs + // started with it before may still be writing through it. + sys::seek_end_if_behind(f.as_raw_handle() as sys::HANDLE); (Stdio::from(f.try_clone()?), None) } Handle::PipeR(p) => (Stdio::from(p.try_clone()?), None), diff --git a/src/sys.rs b/src/sys.rs index f133f02..42589ef 100644 --- a/src/sys.rs +++ b/src/sys.rs @@ -163,9 +163,40 @@ const FILE_APPEND_DATA: DWORD = 0x0004; const FILE_GENERIC_READ: DWORD = 0x0012_0089; const FILE_GENERIC_WRITE: DWORD = 0x0012_0116; const FILE_ACCESS_INFORMATION: u32 = 8; +const FILE_POSITION_INFORMATION: u32 = 14; const FILE_SHARE_ALL: DWORD = 0x7; // read | write | delete const FILE_END: DWORD = 2; +/// The position of `h`'s file object. `SetFilePointerEx(h, 0, FILE_CURRENT)`, what +/// `stream_position` does, sets the position it has just read, so when a program sharing the +/// handle writes in between, it moves the position back over that write, and the next write +/// lands on top of it. This only reads it. +fn file_position(h: HANDLE) -> Option { + let mut iosb = IO_STATUS_BLOCK { status: 0, information: 0 }; + let mut pos: i64 = 0; + let st = unsafe { + NtQueryInformationFile(h, &mut iosb, &mut pos as *mut i64 as *mut _, 8, FILE_POSITION_INFORMATION) + }; + (st >= 0).then_some(pos as u64) +} + +/// Move `h`, a file handle that programs we started may be writing through, to the end of its +/// file if it isn't there, that is if another handle to the file has appended since. Moving +/// it there takes two calls (SetFilePointerEx reads the length, then sets the position), so a +/// write through `h` in between would be undone; leaving the position alone when it is at the +/// end keeps that to the case where it was behind anyway. The length is read first: writes +/// through `h` only move the position forward, so they can't make it look behind. +pub fn seek_end_if_behind(h: HANDLE) { + let mut info = BY_HANDLE_FILE_INFORMATION::default(); + if unsafe { GetFileInformationByHandle(h, &mut info) } == 0 { + return; + } + let len = ((info.nFileSizeHigh as u64) << 32) | info.nFileSizeLow as u64; + if file_position(h).is_some_and(|pos| pos < len) { + unsafe { SetFilePointerEx(h, 0, std::ptr::null_mut(), FILE_END) }; + } +} + fn valid(h: HANDLE) -> bool { !h.is_null() && h as isize != -1 } @@ -244,11 +275,12 @@ fn is_append_only(h: HANDLE) -> bool { /// Move stdout or stderr to the end of its file if `make_append_only_stdio_writable` /// replaced it, as O_APPEND would before a write. Called before we write to it and before -/// a child inherits it. +/// a child inherits it, while children started before may still be writing through it, so +/// only when another handle has appended since (`seek_end_if_behind`). pub fn seek_std_append(n: DWORD) { let flag = if n == STD_ERROR_HANDLE { &STDERR_APPEND } else { &STDOUT_APPEND }; if flag.load(Ordering::Relaxed) { - unsafe { SetFilePointerEx(std_handle(n), 0, std::ptr::null_mut(), FILE_END) }; + seek_end_if_behind(std_handle(n)); } } diff --git a/tests/append_only_stdout.rs b/tests/append_only_stdout.rs new file mode 100644 index 0000000..9948e3e --- /dev/null +++ b/tests/append_only_stdout.rs @@ -0,0 +1,67 @@ +//! gash started with stdout and stderr opened append-only, as Node's `'a'` flag opens them +//! for a child (see `sys::make_append_only_stdio_writable`): output that programs it starts +//! and its own builtins write at the same time all ends up in the file. +//! +//! Skipped when Git for Windows' MSYS tools are not installed. + +use std::fs::{self, OpenOptions}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +/// `$OUT` is the file stdout and stderr go to. The jobs start once awk is writing. +const SCRIPT: &str = r#" +/usr/bin/awk 'BEGIN { for (i = 1; i <= 100000; i++) { print "line " i; fflush() } }' & +until [ -s "$OUT" ]; do :; done +for i in $(seq 1 40); do /usr/bin/echo "job $i" & done +for i in $(seq 1 200); do echo "builtin $i"; done +wait +"#; + +fn git_awk() -> Option { + let mut roots = Vec::new(); + if let Ok(pf) = std::env::var("ProgramFiles") { + roots.push(Path::new(&pf).join("Git")); + } + roots.push(PathBuf::from(r"C:\Program Files\Git")); + roots.into_iter().map(|r| r.join("usr").join("bin").join("awk.exe")).find(|p| p.is_file()) +} + +/// Removes the output file even when an assertion fails. +struct Scratch(PathBuf); + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = fs::remove_file(&self.0); + } +} + +#[test] +fn append_only_stdout_keeps_concurrent_output() { + if git_awk().is_none() { + eprintln!("skipping: Git for Windows' awk not found"); + return; + } + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.subsec_nanos()) + .unwrap_or(0); + let scratch = Scratch(std::env::temp_dir().join(format!("gash-append-stdout-{}-{nanos}.txt", std::process::id()))); + // FILE_APPEND_DATA without FILE_WRITE_DATA, like Node's 'a'. + let out = OpenOptions::new().append(true).create(true).open(&scratch.0).unwrap(); + let err = out.try_clone().unwrap(); + let status = Command::new(env!("CARGO_BIN_EXE_gash")) + .arg("-c") + .arg(SCRIPT) + .env("OUT", &scratch.0) + .stdin(Stdio::null()) + .stdout(out) + .stderr(err) + .status() + .expect("run gash"); + let text = fs::read_to_string(&scratch.0).unwrap(); + let count = |prefix: &str| text.lines().filter(|l| l.starts_with(prefix)).count(); + let got = (count("line "), count("job "), count("builtin "), text.lines().count()); + let tail: Vec<&str> = text.lines().filter(|l| !l.starts_with("line ")).take(20).collect(); + assert_eq!(got, (100000, 40, 200, 100240), "(awk lines, jobs, builtin lines, all lines); other lines: {tail:?}"); + assert_eq!(status.code(), Some(0)); +} diff --git a/tests/scripts/074_append_while_spawning.code b/tests/scripts/074_append_while_spawning.code new file mode 100644 index 0000000..c227083 --- /dev/null +++ b/tests/scripts/074_append_while_spawning.code @@ -0,0 +1 @@ +0 \ No newline at end of file diff --git a/tests/scripts/074_append_while_spawning.out b/tests/scripts/074_append_while_spawning.out new file mode 100644 index 0000000..e2a873c --- /dev/null +++ b/tests/scripts/074_append_while_spawning.out @@ -0,0 +1,2 @@ +lines: 100000, jobs: 40, other: 0 +distinct lines: 100000 diff --git a/tests/scripts/074_append_while_spawning.sh b/tests/scripts/074_append_while_spawning.sh new file mode 100644 index 0000000..7ab3db6 --- /dev/null +++ b/tests/scripts/074_append_while_spawning.sh @@ -0,0 +1,13 @@ +# Starting programs with a >> handle that another program is writing through at the same time +# doesn't move its position back over that program's output. +t=$(mktemp -d) +cd "$t" || exit 1 +{ + /usr/bin/awk 'BEGIN { for (i = 1; i <= 100000; i++) { print "line " i; fflush() } }' & + until [ -s m ]; do :; done + for i in $(seq 1 40); do /usr/bin/echo "job $i" & done + wait +} >> m +echo "lines: $(grep -c '^line [0-9]*$' m), jobs: $(grep -c '^job [0-9]*$' m), other: $(grep -vc -e '^line [0-9]*$' -e '^job [0-9]*$' m)" +echo "distinct lines: $(grep '^line' m | sort -u | wc -l)" +cd / && rm -rf "$t"