Skip to content
Merged
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
13 changes: 3 additions & 10 deletions src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
36 changes: 34 additions & 2 deletions src/sys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u64> {
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
}
Expand Down Expand Up @@ -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));
}
}

Expand Down
67 changes: 67 additions & 0 deletions tests/append_only_stdout.rs
Original file line number Diff line number Diff line change
@@ -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<PathBuf> {
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));
}
1 change: 1 addition & 0 deletions tests/scripts/074_append_while_spawning.code
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0
2 changes: 2 additions & 0 deletions tests/scripts/074_append_while_spawning.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
lines: 100000, jobs: 40, other: 0
distinct lines: 100000
13 changes: 13 additions & 0 deletions tests/scripts/074_append_while_spawning.sh
Original file line number Diff line number Diff line change
@@ -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"
Loading