diff --git a/README.md b/README.md index 11826f1..9898e16 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,19 @@ GASH_COMPAT_JOBS=8 cargo test --test compat # parallel `tests/regen_expected.ps1` regenerates the expected outputs from Git Bash. +The parity suite in [`tests/parity`](tests/parity) runs its cases and the compat scripts under +Git Bash and under gash, and compares stdout, stderr, exit code and the files each run leaves +behind. `cargo test` skips it, because it needs its own copy of Git for Windows and takes about a +minute. [`tests/parity/setup-ref.ps1`](tests/parity/setup-ref.ps1) makes that copy under +`%LOCALAPPDATA%\gash-parity`: + +```bash +powershell -ExecutionPolicy Bypass -File tests/parity/setup-ref.ps1 # once +cargo test --test parity -- --ignored +``` + +A line in [`tests/parity/accepted.txt`](tests/parity/accepted.txt) accepts a difference. + ## Contributing **Every commit must be attributed to the model that produced it, if any.** End the commit diff --git a/tests/compat.rs b/tests/compat.rs index 237f172..602b808 100644 --- a/tests/compat.rs +++ b/tests/compat.rs @@ -18,25 +18,20 @@ //! `LC_ALL=C`, and `LANG`, `LC_*`, `BASH_ENV`, `ENV`, `SHELLOPTS`, `BASHOPTS`, //! `CDPATH`, `GLOBIGNORE`, `POSIXLY_CORRECT` are removed. +mod support; + use std::fs; -use std::io::{Read, Write}; +use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::mpsc; -use std::sync::{Arc, Mutex}; +use std::sync::Mutex; use std::thread; use std::time::{Duration, Instant}; +use support::{run_command, stderr_excerpt, stdout_diff, RunOutput}; + const TIMEOUT: Duration = Duration::from_secs(20); -/// How long to keep waiting for stdout/stderr EOF after the process exited -/// (a leaked background process may keep the pipes open). -const PIPE_GRACE: Duration = Duration::from_secs(3); -const MAX_DIFF_LINES: usize = 15; -const MAX_STDERR_LINES: usize = 10; -const MAX_LINE_CHARS: usize = 200; -/// Above this many lines on either side, fall back to a positional diff. -const MAX_LCS_LINES: usize = 3000; const REMOVED_ENV: &[&str] = &[ "LANG", @@ -49,16 +44,6 @@ const REMOVED_ENV: &[&str] = &[ "POSIXLY_CORRECT", ]; -struct RunOutput { - stdout: Vec, - stderr: Vec, - code: Option, - timed_out: bool, - pipes_left_open: bool, - spawn_error: Option, - elapsed: Duration, -} - struct Outcome { name: String, passed: bool, @@ -219,13 +204,8 @@ fn check_script(exe: &Path, dir: &Path, name: &str) -> Outcome { } fn run_script(exe: &Path, dir: &Path, name: &str) -> RunOutput { - let start = Instant::now(); let mut cmd = Command::new(exe); - cmd.arg(name) - .current_dir(dir) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); + cmd.arg(name).current_dir(dir).stdin(Stdio::null()); for (key, _) in std::env::vars_os() { if let Some(k) = key.to_str() { let upper = k.to_ascii_uppercase(); @@ -235,307 +215,5 @@ fn run_script(exe: &Path, dir: &Path, name: &str) -> RunOutput { } } cmd.env("LC_ALL", "C"); - - let mut child = match cmd.spawn() { - Ok(child) => child, - Err(e) => { - return RunOutput { - stdout: Vec::new(), - stderr: Vec::new(), - code: None, - timed_out: false, - pipes_left_open: false, - spawn_error: Some(e.to_string()), - elapsed: start.elapsed(), - }; - } - }; - - let job = ProcessJob::attach(&child); - let stdout = PipeReader::start(child.stdout.take().expect("stdout is piped")); - let stderr = PipeReader::start(child.stderr.take().expect("stderr is piped")); - - let mut timed_out = false; - let status = loop { - match child.try_wait() { - Ok(Some(status)) => break Some(status), - Ok(None) => {} - Err(_) => break None, - } - if start.elapsed() >= TIMEOUT { - timed_out = true; - kill_tree(&mut child, &job); - break child.wait().ok(); - } - thread::sleep(Duration::from_millis(5)); - }; - - let deadline = Instant::now() + PIPE_GRACE; - let (stdout, out_open) = stdout.finish(deadline); - let (stderr, err_open) = stderr.finish(deadline); - RunOutput { - stdout, - stderr, - code: status.and_then(|s| s.code()), - timed_out, - pipes_left_open: out_open || err_open, - spawn_error: None, - elapsed: start.elapsed(), - } -} - -/// Kills the child and everything it spawned. On Windows killing a process -/// does not kill its children, and an orphaned grandchild (an external -/// command, a forked subshell) would otherwise linger and keep our pipes open. -/// The child is placed in a Job Object right after spawning (descendants -/// inherit it even when their Windows parent has already exited, which is -/// common with MSYS fork/exec); `taskkill /T` is a fallback. -fn kill_tree(child: &mut std::process::Child, job: &ProcessJob) { - job.terminate(); - if cfg!(windows) { - let _ = Command::new("taskkill") - .args(["/T", "/F", "/PID", &child.id().to_string()]) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status(); - } - let _ = child.kill(); -} - -#[cfg(windows)] -mod job { - use std::ffi::c_void; - use std::os::windows::io::AsRawHandle; - - type Handle = *mut c_void; - - #[link(name = "kernel32")] - unsafe extern "system" { - fn CreateJobObjectW(attributes: *mut c_void, name: *const u16) -> Handle; - fn AssignProcessToJobObject(job: Handle, process: Handle) -> i32; - fn TerminateJobObject(job: Handle, exit_code: u32) -> i32; - fn CloseHandle(handle: Handle) -> i32; - } - - pub struct ProcessJob(Handle); - - impl ProcessJob { - pub fn attach(child: &std::process::Child) -> ProcessJob { - // SAFETY: plain Win32 calls; a null handle is tolerated everywhere below. - unsafe { - let job = CreateJobObjectW(std::ptr::null_mut(), std::ptr::null()); - if !job.is_null() && AssignProcessToJobObject(job, child.as_raw_handle()) == 0 { - CloseHandle(job); - return ProcessJob(std::ptr::null_mut()); - } - ProcessJob(job) - } - } - - pub fn terminate(&self) { - if !self.0.is_null() { - // SAFETY: self.0 is a live job handle owned by this struct. - unsafe { - TerminateJobObject(self.0, 1); - } - } - } - } - - impl Drop for ProcessJob { - fn drop(&mut self) { - if !self.0.is_null() { - // SAFETY: closing the handle we created exactly once. - unsafe { - CloseHandle(self.0); - } - } - } - } -} - -#[cfg(not(windows))] -mod job { - pub struct ProcessJob; - impl ProcessJob { - pub fn attach(_child: &std::process::Child) -> ProcessJob { - ProcessJob - } - pub fn terminate(&self) {} - } -} - -use job::ProcessJob; - -/// Drains a pipe on a background thread so the child never blocks on a full -/// pipe while we poll `try_wait`; partial data is still available if the pipe -/// never reaches EOF. -struct PipeReader { - data: Arc>>, - done: mpsc::Receiver<()>, -} - -impl PipeReader { - fn start(mut pipe: R) -> PipeReader { - let data = Arc::new(Mutex::new(Vec::new())); - let (tx, done) = mpsc::channel(); - let sink = Arc::clone(&data); - thread::spawn(move || { - let mut buf = [0u8; 8192]; - loop { - match pipe.read(&mut buf) { - Ok(0) => break, - Ok(n) => sink.lock().unwrap().extend_from_slice(&buf[..n]), - Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, - Err(_) => break, - } - } - let _ = tx.send(()); - }); - PipeReader { data, done } - } - - /// Returns the collected bytes and whether the pipe was still open at the deadline. - fn finish(self, deadline: Instant) -> (Vec, bool) { - let wait = deadline.saturating_duration_since(Instant::now()); - let still_open = self.done.recv_timeout(wait).is_err(); - let bytes = std::mem::take(&mut *self.data.lock().unwrap()); - (bytes, still_open) - } -} - -/// Splits into lines that keep their trailing `\n` (the last one may lack it). -fn split_lines(bytes: &[u8]) -> Vec<&[u8]> { - bytes.split_inclusive(|&b| b == b'\n').collect() -} - -#[derive(Clone, Copy)] -enum Edit { - Equal, - Delete(usize), // line index in expected - Insert(usize), // line index in actual -} - -fn diff_lines(a: &[&[u8]], b: &[&[u8]]) -> Vec { - if a.len() > MAX_LCS_LINES || b.len() > MAX_LCS_LINES { - // Positional comparison for huge outputs. - let mut edits = Vec::new(); - for i in 0..a.len().max(b.len()) { - match (a.get(i), b.get(i)) { - (Some(x), Some(y)) if x == y => edits.push(Edit::Equal), - (x, y) => { - if x.is_some() { - edits.push(Edit::Delete(i)); - } - if y.is_some() { - edits.push(Edit::Insert(i)); - } - } - } - } - return edits; - } - // lcs[i][j] = length of the LCS of a[i..] and b[j..] - let (n, m) = (a.len(), b.len()); - let width = m + 1; - let mut lcs = vec![0u16; (n + 1) * (m + 1)]; - for i in (0..n).rev() { - for j in (0..m).rev() { - lcs[i * width + j] = if a[i] == b[j] { - lcs[(i + 1) * width + j + 1] + 1 - } else { - lcs[(i + 1) * width + j].max(lcs[i * width + j + 1]) - }; - } - } - let (mut i, mut j) = (0, 0); - let mut edits = Vec::new(); - while i < n || j < m { - if i < n && j < m && a[i] == b[j] { - edits.push(Edit::Equal); - i += 1; - j += 1; - } else if j >= m || (i < n && lcs[(i + 1) * width + j] >= lcs[i * width + j + 1]) { - edits.push(Edit::Delete(i)); - i += 1; - } else { - edits.push(Edit::Insert(j)); - j += 1; - } - } - edits -} - -fn stdout_diff(expected: &[u8], actual: &[u8]) -> String { - let a = split_lines(expected); - let b = split_lines(actual); - let edits = diff_lines(&a, &b); - let changed: Vec = edits - .iter() - .filter_map(|e| match *e { - Edit::Equal => None, - Edit::Delete(i) => Some(format!(" - {:>4} | {}", i + 1, show_line(a[i]))), - Edit::Insert(j) => Some(format!(" + {:>4} | {}", j + 1, show_line(b[j]))), - }) - .collect(); - let mut s = format!( - " stdout differs ({} expected lines, {} actual; {} changed; - expected, + actual):\n", - a.len(), - b.len(), - changed.len() - ); - for line in changed.iter().take(MAX_DIFF_LINES) { - s.push_str(line); - s.push('\n'); - } - if changed.len() > MAX_DIFF_LINES { - s.push_str(&format!(" ... {} more changed lines\n", changed.len() - MAX_DIFF_LINES)); - } - s -} - -fn stderr_excerpt(stderr: &[u8]) -> String { - if stderr.is_empty() { - return " stderr: (empty)\n".to_string(); - } - let lines = split_lines(stderr); - let mut s = format!( - " stderr (first {} of {} lines):\n", - lines.len().min(MAX_STDERR_LINES), - lines.len() - ); - for line in lines.iter().take(MAX_STDERR_LINES) { - s.push_str(" | "); - s.push_str(&show_line(line)); - s.push('\n'); - } - s -} - -/// Renders one output line for the report: control characters escaped, -/// missing final newline marked, very long lines truncated. -fn show_line(line: &[u8]) -> String { - let (body, has_newline) = match line.strip_suffix(b"\n") { - Some(body) => (body, true), - None => (line, false), - }; - let text = String::from_utf8_lossy(body); - let mut out = String::new(); - for (count, c) in text.chars().enumerate() { - if count >= MAX_LINE_CHARS { - out.push_str("..."); - break; - } - match c { - '\t' => out.push_str("\\t"), - '\r' => out.push_str("\\r"), - c if c.is_control() => out.push_str(&format!("\\x{:02x}", c as u32)), - c => out.push(c), - } - } - if !has_newline { - out.push_str(" [no newline at end]"); - } - out + run_command(cmd, TIMEOUT, false) } diff --git a/tests/parity.rs b/tests/parity.rs new file mode 100644 index 0000000..85d6010 --- /dev/null +++ b/tests/parity.rs @@ -0,0 +1,38 @@ +//! Live differential parity suite against a reference Git Bash, run by `parity/harness.rs`. + +mod support; +#[path = "parity/harness.rs"] +mod harness; + +use std::path::Path; + +use harness::{posix, Suite}; + +const SUITE: Suite = Suite { + accepted: "accepted.txt", + host_command, +}; + +#[test] +#[ignore = "needs the reference Git copy from tests/parity/setup-ref.ps1, run with cargo test --test parity -- --ignored"] +fn parity() { + let mut cases = harness::compat_cases(); + cases.extend(harness::group_cases(&harness::parity_dir().join("cases"))); + harness::run(&SUITE, cases); +} + +#[test] +fn host_command_line() { + assert_eq!( + host_command("cd sub\necho it's", Path::new("C:\\p q\\cwd")), + "eval 'cd sub\necho it'\"'\"'s' < /dev/null && pwd -P >| '/c/p q/cwd'" + ); +} + +fn host_command(body: &str, cwd_file: &Path) -> String { + format!("eval {} < /dev/null && pwd -P >| {}", quote(body), quote(&posix(cwd_file))) +} + +fn quote(s: &str) -> String { + format!("'{}'", s.replace('\'', "'\"'\"'")) +} diff --git a/tests/parity/.gitattributes b/tests/parity/.gitattributes new file mode 100644 index 0000000..9ac4c51 --- /dev/null +++ b/tests/parity/.gitattributes @@ -0,0 +1,2 @@ +# Cases, fixtures and helper scripts are byte-exact (bash on MSYS chokes on CRLF). +* -text diff --git a/tests/parity/accepted.txt b/tests/parity/accepted.txt new file mode 100644 index 0000000..f3d6b10 --- /dev/null +++ b/tests/parity/accepted.txt @@ -0,0 +1,18 @@ +# Known divergences of gash from the reference shell. +# +# One entry per line: +# case-glob case id pattern with * and ?, e.g. compat/05* or host/* +# observable stdout, stderr, code, tree, cwd, survivors or all, +# or stdout: / stderr: for single lines, +# quoted as stdout:"" when the glob has spaces +# reason free text, required +# +# A line glob matches a whole normalised line (* and ?, case-sensitive, +# no line ending). Matching lines are dropped from the reference and the +# gash output before they are compared again. +# +# A covered divergence reports as ACCEPTED. An entry that covers nothing, +# or a line entry that matched no line, fails the run when its case glob +# matches a case of the run, unless such a case was dropped. +# +# GASH_PARITY_ACCEPTED= loads these files instead of this one. diff --git a/tests/parity/cases/boundary/argv_msys_drive.sh b/tests/parity/cases/boundary/argv_msys_drive.sh new file mode 100644 index 0000000..1cdfc56 --- /dev/null +++ b/tests/parity/cases/boundary/argv_msys_drive.sh @@ -0,0 +1,5 @@ +# A drive-letter argument holding a quote, a newline or a trailing backslash reaches an MSYS program as one word. + +/usr/bin/printf '[%s]\n' 'C:\x\" -la' next +/usr/bin/printf '[%s]\n' 'C:\Program Files\' next +/usr/bin/printf '[%s]\n' $'C:\\file\n-la' next diff --git a/tests/parity/cases/boundary/argv_msys_glob.sh b/tests/parity/cases/boundary/argv_msys_glob.sh new file mode 100644 index 0000000..f34b146 --- /dev/null +++ b/tests/parity/cases/boundary/argv_msys_glob.sh @@ -0,0 +1,12 @@ +# parity: mode=c +# parity: serial=1 +# parity: fixture=native + +echo "quoted glob chars:" +env printf '[%s]\n' '*' '*.txt' '?.txt' '[ab].txt' 'x*y' '{a,b}' +echo "unquoted glob:" +env printf '[%s]\n' *.txt +echo "star inside a spaced arg:" +env printf '[%s]\n' 'a * b' "* .txt" +echo "quoted tilde:" +env printf '[%s]\n' '~' '~/x' diff --git a/tests/parity/cases/boundary/argv_msys_long.sh b/tests/parity/cases/boundary/argv_msys_long.sh new file mode 100644 index 0000000..b267873 --- /dev/null +++ b/tests/parity/cases/boundary/argv_msys_long.sh @@ -0,0 +1,23 @@ +# parity: serial=1 + +# Over 32767 characters of command line. +args=() +for i in $(seq 1 6000); do args+=("arg-$i"); done +args+=('a b' 'say "hi"' 'q\"' 'end\' '' '@x' $'two\nlines' '*' "it's" 'é') +echo "msys child:" +/usr/bin/printf '[%s]\n' "${args[@]}" | wc -l +/usr/bin/printf '[%s]\n' "${args[@]}" | tail -n 11 +echo "grep over many files:" +printf 'needle\n' > hay.txt +files=() +for i in $(seq 1 3000); do files+=(./hay.txt); done +grep -c needle "${files[@]}" | sort | uniq -c +echo "background:" +/usr/bin/printf '%s\n' "${args[@]}" > bg.out & +wait +wc -l < bg.out +echo "arguments naming files after @ stay literal:" +touch f +printf 'from-file\n' > g +/usr/bin/printf '[%s]\n' @f @g @missing x@g +env printf '[%s]\n' @g diff --git a/tests/parity/cases/boundary/argv_msys_parent.sh b/tests/parity/cases/boundary/argv_msys_parent.sh new file mode 100644 index 0000000..4f5ee53 --- /dev/null +++ b/tests/parity/cases/boundary/argv_msys_parent.sh @@ -0,0 +1,8 @@ +# gash started by an MSYS program reads its args from the command line the MSYS runtime built. + +echo "timeout:" +/usr/bin/timeout 5 bash -c "printf '%s\n' 'a\\\\b'" +echo "awkward args:" +printf 'EXPANDED\n' > x +/usr/bin/timeout 5 bash -c 'printf "[%s]\n" "$@"' x 'a\\b' 'c\d' 'q"r' "it's" '' '@x' '*' 'sp ace' 'tail\\' '{a,b}' +rm -f x diff --git a/tests/parity/cases/boundary/argv_msys_unicode.sh b/tests/parity/cases/boundary/argv_msys_unicode.sh new file mode 100644 index 0000000..80b1ea8 --- /dev/null +++ b/tests/parity/cases/boundary/argv_msys_unicode.sh @@ -0,0 +1,5 @@ +# parity: mode=c +# parity: serial=1 + +env printf '[%s]\n' 'héllo' 'ü' '日本語' 'emoji 😀' | od -An -tx1 +echo "msys echo: $(env echo 'grüße')" diff --git a/tests/parity/cases/boundary/argv_native_ps.sh b/tests/parity/cases/boundary/argv_native_ps.sh new file mode 100644 index 0000000..63956ce --- /dev/null +++ b/tests/parity/cases/boundary/argv_native_ps.sh @@ -0,0 +1,6 @@ +# parity: mode=c +# parity: serial=1 +# parity: fixture=native + +s=$(cygpath -w "$PWD/printargs.ps1") +MSYS_NO_PATHCONV=1 powershell -NoProfile -ExecutionPolicy Bypass -File "$s" 'a b' plain 'end\' 'q\"x' '' '*' | tr -d '\r' diff --git a/tests/parity/cases/boundary/crlf_herestring.sh b/tests/parity/cases/boundary/crlf_herestring.sh new file mode 100644 index 0000000..8380d3f --- /dev/null +++ b/tests/parity/cases/boundary/crlf_herestring.sh @@ -0,0 +1,10 @@ +# parity: mode=c +# parity: serial=1 + +read -r first <<< $'crlf\r' +printf 'herestring read: ' +printf '%s' "$first" | od -An -c +while IFS= read -r l; do + printf 'herestring loop: ' + printf '%s' "$l" | od -An -c +done <<< $'one\r\ntwo\r' diff --git a/tests/parity/cases/boundary/crlf_native_subst.sh b/tests/parity/cases/boundary/crlf_native_subst.sh new file mode 100644 index 0000000..77ca996 --- /dev/null +++ b/tests/parity/cases/boundary/crlf_native_subst.sh @@ -0,0 +1,13 @@ +# parity: mode=c +# parity: serial=1 + +v=$(MSYS_NO_PATHCONV=1 cmd.exe /d /c echo hello) +printf 'cmd subst: ' +printf '%s' "$v" | od -An -c +[[ $v == hello ]] && echo "cmd equals hello: yes" || echo "cmd equals hello: no" +v=$(powershell -NoProfile -Command 'Write-Output a; Write-Output b') +printf 'ps subst: ' +printf '%s' "$v" | od -An -c +n=0 +while read -r l; do n=$((n + 1)); done < <(MSYS_NO_PATHCONV=1 cmd.exe /d /c "echo x& echo y") +echo "process subst lines: $n" diff --git a/tests/parity/cases/boundary/crlf_while_read_file.sh b/tests/parity/cases/boundary/crlf_while_read_file.sh new file mode 100644 index 0000000..f255cb0 --- /dev/null +++ b/tests/parity/cases/boundary/crlf_while_read_file.sh @@ -0,0 +1,9 @@ +# parity: mode=c +# parity: serial=1 + +printf 'one\r\ntwo\r\nlast' > crlf.txt +while read -r l || [ -n "$l" ]; do + printf 'file line: ' + printf '%s' "$l" | od -An -c +done < crlf.txt +echo "msys wc: $(wc -c < crlf.txt)" diff --git a/tests/parity/cases/boundary/cwd_children.sh b/tests/parity/cases/boundary/cwd_children.sh new file mode 100644 index 0000000..0a2134f --- /dev/null +++ b/tests/parity/cases/boundary/cwd_children.sh @@ -0,0 +1,9 @@ +# parity: mode=c +# parity: serial=1 + +mkdir -p 'sub dir' +cd 'sub dir' +echo "builtin pwd: $(pwd)" +echo "msys pwd: $(/usr/bin/pwd)" +echo "cmd cd: $(MSYS_NO_PATHCONV=1 cmd.exe /d /c cd | tr -d '\r')" +echo "PWD env msys: $(env | grep '^PWD=')" diff --git a/tests/parity/cases/boundary/home_expansion.sh b/tests/parity/cases/boundary/home_expansion.sh new file mode 100644 index 0000000..f22cb02 --- /dev/null +++ b/tests/parity/cases/boundary/home_expansion.sh @@ -0,0 +1,13 @@ +# parity: mode=c +# parity: serial=1 + +echo "tilde: ~" +echo "tilde slash: ~/x" +echo "HOME: $HOME" +x=~/y +echo "assign: $x" +cd ~ && echo "cd ~: $(pwd)" +echo "msys env HOME: $(env | grep '^HOME=')" +echo "cmd HOME: $(MSYS_NO_PATHCONV=1 cmd.exe /d /c echo %HOME% | tr -d '\r')" +MSYS_NO_PATHCONV=1 cmd.exe /d /c "echo cmd-wrote> %HOME%\p_home_cmd.txt" +echo "builtin read: $(tr -d '\r' < ~/p_home_cmd.txt 2>&1)" diff --git a/tests/parity/cases/boundary/msystem.sh b/tests/parity/cases/boundary/msystem.sh new file mode 100644 index 0000000..e651eba --- /dev/null +++ b/tests/parity/cases/boundary/msystem.sh @@ -0,0 +1,7 @@ +# parity: mode=c +# parity: serial=1 + +echo "builtin: MSYSTEM=${MSYSTEM-unset} OSTYPE=$OSTYPE" +env | grep '^MSYSTEM=' | sed 's/^/msys: /' +MSYS_NO_PATHCONV=1 cmd.exe /d /c "echo MSYSTEM=%MSYSTEM%" | tr -d '\r' | sed 's/^/cmd: /' +echo "uname: $(uname -s | cut -d_ -f1)" diff --git a/tests/parity/cases/boundary/nested_shells_start.sh b/tests/parity/cases/boundary/nested_shells_start.sh new file mode 100644 index 0000000..bf32ddc --- /dev/null +++ b/tests/parity/cases/boundary/nested_shells_start.sh @@ -0,0 +1,7 @@ +# parity: mode=c +# parity: serial=1 + +bash -c 'echo "bash: BASH=$BASH"; echo "bash: v${BASH_VERSINFO[0]} SHLVL=$SHLVL"' +sh -c 'echo "sh: BASH=$BASH"; echo "sh: SHLVL=$SHLVL"' +env bash -c 'echo "env bash: BASH=$BASH"; echo "env bash: SHLVL=$SHLVL"' +echo "outer: SHLVL=$SHLVL" diff --git a/tests/parity/cases/boundary/path_home_bin.sh b/tests/parity/cases/boundary/path_home_bin.sh new file mode 100644 index 0000000..c30f628 --- /dev/null +++ b/tests/parity/cases/boundary/path_home_bin.sh @@ -0,0 +1,8 @@ +# parity: mode=c +# parity: serial=1 +# parity: home=home-dotfiles + +export PATH="$HOME/bin:$PATH" +echo "command -v: $(command -v parity-hello)" +parity-hello +echo "msys env lookup: $(env parity-hello 2>&1)" diff --git a/tests/parity/cases/boundary/pathconv_msys_child.sh b/tests/parity/cases/boundary/pathconv_msys_child.sh new file mode 100644 index 0000000..135a47c --- /dev/null +++ b/tests/parity/cases/boundary/pathconv_msys_child.sh @@ -0,0 +1,5 @@ +# parity: mode=c +# parity: serial=1 + +echo "msys child sees:" +env printf '[%s]\n' /quiet /c/x --opt=/c/x /a:/b /tmp/y x=/c/y //double diff --git a/tests/parity/cases/boundary/pathconv_no_pathconv.sh b/tests/parity/cases/boundary/pathconv_no_pathconv.sh new file mode 100644 index 0000000..81a1cd3 --- /dev/null +++ b/tests/parity/cases/boundary/pathconv_no_pathconv.sh @@ -0,0 +1,5 @@ +# parity: mode=c +# parity: serial=1 + +echo "cmd sees with MSYS_NO_PATHCONV:" +MSYS_NO_PATHCONV=1 cmd.exe /d /c echo /quiet /c/x --opt=/c/x /a:/b /tmp/y x=/c/y | tr -d '\r' diff --git a/tests/parity/cases/boundary/paths_builtin_forms.sh b/tests/parity/cases/boundary/paths_builtin_forms.sh new file mode 100644 index 0000000..1f4e326 --- /dev/null +++ b/tests/parity/cases/boundary/paths_builtin_forms.sh @@ -0,0 +1,13 @@ +# parity: mode=c +# parity: serial=1 +# parity: fixture=native + +m=$(cygpath -m "$PWD") +w=$(cygpath -w "$PWD") +for p in "$PWD/a.txt" "$m/a.txt" "$w\\a.txt"; do + [ -f "$p" ] && echo "test -f: yes" || echo "test -f: no" + read -r line < "$p" && echo "read: $line" +done +cd "$w" && echo "cd win: $(pwd)" +cd "$m" && echo "cd mixed: $(pwd)" +cd "$(cygpath -uW)" && echo "cd posix: $(pwd)" diff --git a/tests/parity/cases/boundary/paths_msys_forms.sh b/tests/parity/cases/boundary/paths_msys_forms.sh new file mode 100644 index 0000000..5880d69 --- /dev/null +++ b/tests/parity/cases/boundary/paths_msys_forms.sh @@ -0,0 +1,9 @@ +# parity: mode=c +# parity: serial=1 +# parity: fixture=native + +m=$(cygpath -m "$PWD") +w=$(cygpath -w "$PWD") +echo "posix: $(cat "$PWD/a.txt" 2>&1)" +echo "mixed: $(cat "$m/a.txt" 2>&1)" +echo "win: $(cat "$w\\a.txt" 2>&1)" diff --git a/tests/parity/cases/boundary/paths_msystem_prefix.sh b/tests/parity/cases/boundary/paths_msystem_prefix.sh new file mode 100644 index 0000000..127626a --- /dev/null +++ b/tests/parity/cases/boundary/paths_msystem_prefix.sh @@ -0,0 +1,5 @@ +# parity: mode=c + +p=/${MSYSTEM,,} +echo "builtin: $([ -d "$p/bin" ] && echo dir || echo missing)" +echo "native: $(cmd.exe //d //c echo "$p/bin" | tr -d '\r')" diff --git a/tests/parity/cases/boundary/paths_native_forms.sh b/tests/parity/cases/boundary/paths_native_forms.sh new file mode 100644 index 0000000..1617b50 --- /dev/null +++ b/tests/parity/cases/boundary/paths_native_forms.sh @@ -0,0 +1,9 @@ +# parity: mode=c +# parity: serial=1 +# parity: fixture=native + +m=$(cygpath -m "$PWD") +w=$(cygpath -w "$PWD") +echo "cmd type posix: $(cmd.exe //d //c type "$PWD/a.txt" 2>&1 | tr -d '\r')" +echo "cmd type mixed: $(cmd.exe //d //c type "$m/a.txt" 2>&1 | tr -d '\r')" +echo "cmd type win: $(cmd.exe //d //c type "$w\\a.txt" 2>&1 | tr -d '\r')" diff --git a/tests/parity/cases/boundary/tmp_builtin_to_native.sh b/tests/parity/cases/boundary/tmp_builtin_to_native.sh new file mode 100644 index 0000000..3751c0f --- /dev/null +++ b/tests/parity/cases/boundary/tmp_builtin_to_native.sh @@ -0,0 +1,13 @@ +# parity: mode=c +# parity: serial=1 + +echo builtin-wrote > /tmp/p_b2n.txt +echo "cmd type: $(MSYS_NO_PATHCONV=1 cmd.exe /d /c "type %TEMP%\p_b2n.txt" 2>&1 | tr -d '\r')" +echo "ps get: $(powershell -NoProfile -Command 'Get-Content (Join-Path $env:TMP p_b2n.txt)' 2>&1 | tr -d '\r')" +MSYS_NO_PATHCONV=1 cmd.exe /d /c "echo cmd-wrote> %TEMP%\p_n2b.txt" +if [ -f /tmp/p_n2b.txt ]; then + IFS= read -r line < /tmp/p_n2b.txt + printf 'read: %s\n' "${line%$'\r'}" +else + echo "read: /tmp/p_n2b.txt missing" +fi diff --git a/tests/parity/cases/boundary/tmp_cold_moved_tmp_shared.sh b/tests/parity/cases/boundary/tmp_cold_moved_tmp_shared.sh new file mode 100644 index 0000000..f030c5f --- /dev/null +++ b/tests/parity/cases/boundary/tmp_cold_moved_tmp_shared.sh @@ -0,0 +1,11 @@ +# parity: mode=c +# parity: serial=1 +# parity: cold=1 +# parity: env=TMP=@CASE@\fixture +# parity: env=TEMP=@CASE@\fixture + +echo "builtin TMP: $TMP" +echo "cygpath -w /tmp: $(cygpath -w /tmp)" +echo builtin-wrote > /tmp/p_csd.txt +echo "msys cat /tmp: $(cat /tmp/p_csd.txt 2>&1)" +echo "native: $(MSYS_NO_PATHCONV=1 cmd.exe /d /c "if exist %TEMP%\p_csd.txt (echo sees it) else (echo misses it)" | tr -d '\r')" diff --git a/tests/parity/cases/boundary/tmp_cold_tmp_over_temp.sh b/tests/parity/cases/boundary/tmp_cold_tmp_over_temp.sh new file mode 100644 index 0000000..9a748ac --- /dev/null +++ b/tests/parity/cases/boundary/tmp_cold_tmp_over_temp.sh @@ -0,0 +1,9 @@ +# parity: mode=c +# parity: serial=1 +# parity: cold=1 +# parity: env=TMP=@CASE@\fixture + +echo "cygpath -w /tmp: $(cygpath -w /tmp)" +echo builtin-wrote > /tmp/p_order.txt +echo "msys cat /tmp: $(cat /tmp/p_order.txt 2>&1)" +echo "native: $(MSYS_NO_PATHCONV=1 cmd.exe /d /c "if exist %TMP%\p_order.txt (echo sees it) else (echo misses it)" | tr -d '\r')" diff --git a/tests/parity/cases/boundary/tmp_lc_roundtrip.sh b/tests/parity/cases/boundary/tmp_lc_roundtrip.sh new file mode 100644 index 0000000..e5460fd --- /dev/null +++ b/tests/parity/cases/boundary/tmp_lc_roundtrip.sh @@ -0,0 +1,9 @@ +# parity: mode=lc +# parity: serial=1 + +echo "builtin: TMP=$TMP TEMP=$TEMP" +echo builtin-wrote > /tmp/p_lc.txt +echo "msys cat: $(cat /tmp/p_lc.txt 2>&1)" +echo "cmd type: $(MSYS_NO_PATHCONV=1 cmd.exe /d /c "type %TEMP%\p_lc.txt" 2>&1 | tr -d '\r')" +MSYS_NO_PATHCONV=1 cmd.exe /d /c "echo cmd-wrote> %TMP%\p_lc_cmd.txt" 2>&1 | tr -d '\r' | sed 's/^/cmd write: /' +echo "msys cat back: $(cat /tmp/p_lc_cmd.txt 2>&1 | tr -d '\r')" diff --git a/tests/parity/cases/boundary/tmp_msys_to_builtin.sh b/tests/parity/cases/boundary/tmp_msys_to_builtin.sh new file mode 100644 index 0000000..86a154b --- /dev/null +++ b/tests/parity/cases/boundary/tmp_msys_to_builtin.sh @@ -0,0 +1,12 @@ +# parity: mode=c +# parity: serial=1 + +echo copied > "$PARITY_PROBE_DIR/src.txt" +cp "$PARITY_PROBE_DIR/src.txt" /tmp/p_m2b_cp.txt +touch /tmp/p_m2b_touch +read -r line < /tmp/p_m2b_cp.txt +echo "read cp: $line" +[ -f /tmp/p_m2b_touch ] && echo "test -f touch: yes" || echo "test -f touch: no" +for f in /tmp/p_m2b*; do echo "glob: $f"; done +echo builtin-wrote > /tmp/p_b2m.txt +echo "cat: $(cat /tmp/p_b2m.txt 2>&1)" diff --git a/tests/parity/cases/boundary/tmpvars_children.sh b/tests/parity/cases/boundary/tmpvars_children.sh new file mode 100644 index 0000000..36517d2 --- /dev/null +++ b/tests/parity/cases/boundary/tmpvars_children.sh @@ -0,0 +1,6 @@ +# parity: mode=c +# parity: serial=1 + +echo "builtin: TMP=$TMP TEMP=$TEMP TMPDIR=${TMPDIR-unset}" +env | grep -E '^(TMP|TEMP|TMPDIR)=' | sort | sed 's/^/msys: /' +MSYS_NO_PATHCONV=1 cmd.exe /d /c "echo TMP=%TMP% TEMP=%TEMP% TMPDIR=%TMPDIR%" | tr -d '\r' | sed 's/^/cmd: /' diff --git a/tests/parity/cases/boundary/tmpvars_posix_export.sh b/tests/parity/cases/boundary/tmpvars_posix_export.sh new file mode 100644 index 0000000..5d4c6b0 --- /dev/null +++ b/tests/parity/cases/boundary/tmpvars_posix_export.sh @@ -0,0 +1,9 @@ +# parity: mode=c +# parity: serial=1 + +export TMP=/tmp TEMP=/tmp +echo "builtin: TMP=$TMP TEMP=$TEMP" +env | grep -E '^(TMP|TEMP)=' | sort | sed 's/^/msys: /' +MSYS_NO_PATHCONV=1 cmd.exe /d /c "echo TMP=%TMP% TEMP=%TEMP%" | tr -d '\r' | sed 's/^/cmd: /' +MSYS_NO_PATHCONV=1 cmd.exe /d /c "echo cmd-wrote> %TEMP%\p_px.txt" 2>&1 | tr -d '\r' | sed 's/^/cmd write: /' +echo "msys cat: $(cat /tmp/p_px.txt 2>&1 | tr -d '\r')" diff --git a/tests/parity/cases/host/host_bg_job.sh b/tests/parity/cases/host/host_bg_job.sh new file mode 100644 index 0000000..a5f69c7 --- /dev/null +++ b/tests/parity/cases/host/host_bg_job.sh @@ -0,0 +1,15 @@ +# parity: mode=host + +( + until [ -e "$PARITY_PROBE_DIR/go" ]; do sleep 0.1; done + echo job-output + : > "$PARITY_PROBE_DIR/done" + exit 4 +) & +job=$! +echo before-go +: > "$PARITY_PROBE_DIR/go" +until [ -e "$PARITY_PROBE_DIR/done" ]; do sleep 0.1; done +echo after-done +wait "$job" +echo "job rc=$?" diff --git a/tests/parity/cases/host/host_cd.sh b/tests/parity/cases/host/host_cd.sh new file mode 100644 index 0000000..80e1740 --- /dev/null +++ b/tests/parity/cases/host/host_cd.sh @@ -0,0 +1,3 @@ +# parity: mode=host + +mkdir -p sub/deeper && cd sub/deeper && echo "moved to $(basename "$PWD")" diff --git a/tests/parity/cases/host/host_console_none.sh b/tests/parity/cases/host/host_console_none.sh new file mode 100644 index 0000000..489330b --- /dev/null +++ b/tests/parity/cases/host/host_console_none.sh @@ -0,0 +1,7 @@ +# parity: mode=host +# parity: console=none + +echo hidden +MSYS_NO_PATHCONV=1 cmd.exe /d /c echo native-in-hidden | tr -d '\r' +echo "msys: $(uname -s | cut -d_ -f1)" +echo "ps: $(powershell -NoProfile -Command 'Write-Output ps-in-hidden' | tr -d '\r')" diff --git a/tests/parity/cases/host/host_fail.sh b/tests/parity/cases/host/host_fail.sh new file mode 100644 index 0000000..9932c6d --- /dev/null +++ b/tests/parity/cases/host/host_fail.sh @@ -0,0 +1,3 @@ +# parity: mode=host + +echo before && ls /parity-does-not-exist diff --git a/tests/parity/cases/host/host_heredoc.sh b/tests/parity/cases/host/host_heredoc.sh new file mode 100644 index 0000000..81ce55a --- /dev/null +++ b/tests/parity/cases/host/host_heredoc.sh @@ -0,0 +1,11 @@ +# parity: mode=host + +cat <<'EOF' +line one + indented $HOME 'single' "double" +EOF +x=3 +cat < "$ps1" + until [ "$(powershell -NoProfile -ExecutionPolicy Bypass -File "$(cygpath -w "$ps1")" | tr -d '\r')" -ge 2 ] 2> /dev/null; do :; done + : > "$PARITY_PROBE_DIR/ready" +) & +echo started +sleep 3600.$PARITY_KILL_TAG | cat +echo not-reached diff --git a/tests/parity/cases/host/host_plain.sh b/tests/parity/cases/host/host_plain.sh new file mode 100644 index 0000000..903773d --- /dev/null +++ b/tests/parity/cases/host/host_plain.sh @@ -0,0 +1,4 @@ +# parity: mode=host + +echo plain +pwd diff --git a/tests/parity/cases/host/host_stdin.sh b/tests/parity/cases/host/host_stdin.sh new file mode 100644 index 0000000..3a7a49a --- /dev/null +++ b/tests/parity/cases/host/host_stdin.sh @@ -0,0 +1,7 @@ +# parity: mode=host +# parity: timeout=30 + +cat +echo "cat rc=$?" +if read -r x; then echo "read got [$x]"; else echo "read eof rc=$?"; fi +echo "head bytes: $(head -c 5 | wc -c)" diff --git a/tests/parity/cases/startup/interactive_rc.sh b/tests/parity/cases/startup/interactive_rc.sh new file mode 100644 index 0000000..d5779e9 --- /dev/null +++ b/tests/parity/cases/startup/interactive_rc.sh @@ -0,0 +1,5 @@ +# parity: home=home-bashrc-only + +bash -i -c 'echo "bashrc: ${HOME_RC_MARK-unset}"' 2>/dev/null +printf 'export RCFILE_MARK=rcfile\n' > rc +bash --rcfile rc -i -c 'echo "rcfile: ${RCFILE_MARK-unset} ${HOME_RC_MARK-unset}"' 2>/dev/null diff --git a/tests/parity/cases/startup/login_etc_profile.sh b/tests/parity/cases/startup/login_etc_profile.sh new file mode 100644 index 0000000..05ec8d6 --- /dev/null +++ b/tests/parity/cases/startup/login_etc_profile.sh @@ -0,0 +1,4 @@ +# parity: mode=lc +# parity: env=GASH_ETC_PROFILE=1 + +echo "MANPATH=${MANPATH-unset}" diff --git a/tests/parity/cases/startup/login_profile.sh b/tests/parity/cases/startup/login_profile.sh new file mode 100644 index 0000000..df5bd70 --- /dev/null +++ b/tests/parity/cases/startup/login_profile.sh @@ -0,0 +1,4 @@ +# parity: mode=lc +# parity: home=home-dotfiles + +echo "marks: ${HOME_PROFILE_MARK-unset} ${HOME_RC_MARK-unset}" diff --git a/tests/parity/fixtures/home-bashrc-only/.bashrc b/tests/parity/fixtures/home-bashrc-only/.bashrc new file mode 100644 index 0000000..3fe14e0 --- /dev/null +++ b/tests/parity/fixtures/home-bashrc-only/.bashrc @@ -0,0 +1,5 @@ +export HOME_RC_MARK=rc +alias pgreet='echo greet from alias' +pfunc() { + echo "pfunc args: $*" +} diff --git a/tests/parity/fixtures/home-dotfiles/.bash_profile b/tests/parity/fixtures/home-dotfiles/.bash_profile new file mode 100644 index 0000000..6f2ac00 --- /dev/null +++ b/tests/parity/fixtures/home-dotfiles/.bash_profile @@ -0,0 +1,5 @@ +export HOME_PROFILE_MARK=profile +export PATH="$HOME/bin:$PATH" +if [ -f "$HOME/.bashrc" ]; then + . "$HOME/.bashrc" +fi diff --git a/tests/parity/fixtures/home-dotfiles/.bashrc b/tests/parity/fixtures/home-dotfiles/.bashrc new file mode 100644 index 0000000..3fe14e0 --- /dev/null +++ b/tests/parity/fixtures/home-dotfiles/.bashrc @@ -0,0 +1,5 @@ +export HOME_RC_MARK=rc +alias pgreet='echo greet from alias' +pfunc() { + echo "pfunc args: $*" +} diff --git a/tests/parity/fixtures/home-dotfiles/bin/parity-hello b/tests/parity/fixtures/home-dotfiles/bin/parity-hello new file mode 100644 index 0000000..7f8adbf --- /dev/null +++ b/tests/parity/fixtures/home-dotfiles/bin/parity-hello @@ -0,0 +1,2 @@ +#!/bin/sh +echo "hello from home bin" diff --git a/tests/parity/fixtures/native/a.txt b/tests/parity/fixtures/native/a.txt new file mode 100644 index 0000000..4a58007 --- /dev/null +++ b/tests/parity/fixtures/native/a.txt @@ -0,0 +1 @@ +alpha diff --git a/tests/parity/fixtures/native/b.txt b/tests/parity/fixtures/native/b.txt new file mode 100644 index 0000000..652d57d --- /dev/null +++ b/tests/parity/fixtures/native/b.txt @@ -0,0 +1 @@ +bravo diff --git a/tests/parity/fixtures/native/printargs.ps1 b/tests/parity/fixtures/native/printargs.ps1 new file mode 100644 index 0000000..464e356 --- /dev/null +++ b/tests/parity/fixtures/native/printargs.ps1 @@ -0,0 +1,2 @@ +"argc: $($args.Count)" +foreach ($a in $args) { "[$a]" } diff --git a/tests/parity/harness.rs b/tests/parity/harness.rs new file mode 100644 index 0000000..232c866 --- /dev/null +++ b/tests/parity/harness.rs @@ -0,0 +1,1363 @@ +//! Harness of the live differential parity suite. It runs each case through a reference Git Bash, gash, and the reference again. +//! Gash must match the reference on each observable the two reference runs agree on. Each test entry hands it a `Suite` and its cases. +//! +//! The reference runs against a suite-owned Git install copy, whose MSYS +//! `/tmp` mount the harness pins to the run's own tmp dir. +//! Run output goes to `/tmp/parity/run-/`, and only +//! the newest few run dirs are kept. +//! +//! Environment knobs: +//! * `GASH_PARITY_REF` reference shell (default `\bin\bash.exe`). +//! * `GASH_PARITY_FILTER` only run cases whose id contains this substring. +//! * `GASH_PARITY_JOBS` parallel workers for cases without `serial` or `cold` (default 4). +//! * `GASH_PARITY_TIMEOUT` seconds per shell run (default 90). +//! * `GASH_PARITY_MAX_DROP` percent of dropped cases a group may have (default 5), one drop is always allowed. +//! * `GASH_PARITY_ENV` `K=V;K=V` overlay for every run, with `@CASE@` in V replaced as in `env=`. +//! * `GASH_PARITY_GASH` gash binary to test (default the one cargo built). +//! * `GASH_PARITY_ACCEPTED` `;`-separated accepted lists that replace the entry's default list. +//! +//! Case header keys, one `# parity: key=value` line each at the top of the case file: +//! * `mode=` `script` (default) runs the case file, `c` and `lc` run its body with `-c` and `-l -c`, `host` runs it through the entry's host command. +//! * `fixture=` copies `tests/parity/fixtures/` into the run's fixture dir. +//! * `home=` copies `tests/parity/fixtures/` into the case home. +//! * `serial=1` runs the case alone after the parallel ones, clears the run tmp dir before each shell run and adds it to `tree`. +//! * `cold=1` runs the case after the others, kills every copy process and clears the run tmp dir before each shell run, and adds that dir to `tree`. +//! * `timeout=` timeout of each shell run of the case. +//! * `kill-after=` taskkills the shell tree once `/` exists or after 60 s without it, observable `survivors`. +//! * `console=none` spawns the shell with `CREATE_NO_WINDOW`. +//! * `env=K=V` sets K for the run, with `@CASE@` in V replaced by the Windows path of the run's case dir. +//! +//! Variables the harness sets for a case: +//! * `PARITY_PROBE_DIR` the run's probe dir, outside `tree`, which holds the `kill-after` marker and the `mode=host` cwd file. +//! * `PARITY_KILL_TAG` digit string of a `kill-after` case, `survivors` counts the processes whose command line carries it. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; +use std::thread; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use crate::support::{line_diff, run_command, run_command_watched, stderr_excerpt, ProcessJob, RunOutput}; + +const DEFAULT_TIMEOUT_S: u64 = 90; +const DEFAULT_JOBS: usize = 4; +const DEFAULT_MAX_DROP: f64 = 5.0; +const DETAIL_DIFF_LINES: usize = 80; +const HOLDER_SECONDS: &str = "86400"; +const KILL_WAIT: Duration = Duration::from_secs(60); +const CREATE_NO_WINDOW: u32 = 0x0800_0000; +/// Run dirs kept under `/tmp/parity`, the current one included. +const KEEP_RUNS: usize = 5; + +static KILL_TAGS: AtomicUsize = AtomicUsize::new(0); + +const REMOVED_ENV: &[&str] = &[ + "LANG", + "BASH_ENV", + "ENV", + "SHELLOPTS", + "BASHOPTS", + "CDPATH", + "GLOBIGNORE", + "POSIXLY_CORRECT", + "MSYSTEM", + "GASH_ROOT", + "GASH_COREUTILS", + "GASH_ETC_PROFILE", + "HOME", + // Left behind when cargo was started from a Git Bash. + "_", + "EXEPATH", + "PLINK_PROTOCOL", + "PWD", + "OLDPWD", + "SHLVL", + "TERM", + "TMPDIR", + "PS1", + "HOSTNAME", + "DISPLAY", + "SSH_ASKPASS", + "CONFIG_SITE", + "ACLOCAL_PATH", + "MANPATH", + "INFOPATH", +]; +const REMOVED_ENV_PREFIXES: &[&str] = &["CARGO", "RUST", "LC_", "MINGW_", "MSYSTEM_", "ORIGINAL_", "PKG_CONFIG_"]; + +const OBSERVABLES: &[&str] = &["stdout", "stderr", "code", "tree", "cwd", "survivors", "all"]; + +/// What one test entry adds to the shared harness. +pub struct Suite { + /// Accepted list under `tests/parity` used when `GASH_PARITY_ACCEPTED` is unset. + pub accepted: &'static str, + /// The `bash -c -l` argument for a `mode=host` case, built from its body and the file that receives the final `pwd -P`. + pub host_command: fn(&str, &Path) -> String, +} + +#[derive(Clone, Copy, PartialEq)] +enum Mode { + Script, + C, + Lc, + Host, +} + +pub struct Case { + id: String, + group: String, + file: PathBuf, + mode: Mode, + body: String, + /// Script argument and working dir for the `compat` group, which runs in place. + in_place: Option<(String, PathBuf)>, + fixture: Option, + home: Option, + env: Vec<(String, String)>, + serial: bool, + cold: bool, + timeout: Option, + kill_after: Option, + no_console: bool, +} + +struct Config<'a> { + suite: &'a Suite, + copy: PathBuf, + ref_shell: PathBuf, + gash_shell: PathBuf, + gash_dir: PathBuf, + run: PathBuf, + tmp: PathBuf, + timeout: Duration, + base_env: Vec<(String, String)>, + overlay: Vec<(String, String)>, +} + +#[derive(Clone, Copy, PartialEq)] +enum Which { + R1, + G, + R2, +} + +impl Which { + fn dir(self) -> &'static str { + match self { + Which::R1 => "r1", + Which::G => "g", + Which::R2 => "r2", + } + } +} + +struct RunResult { + out: RunOutput, + tree: Vec, + cwd: Option>, + survivors: Option>, +} + +#[derive(Clone, Copy, PartialEq)] +enum Status { + Pass, + Diff, + Accepted, + Dropped, +} + +impl Status { + fn label(self) -> &'static str { + match self { + Status::Pass => "PASS", + Status::Diff => "DIFF", + Status::Accepted => "ACCEPTED", + Status::Dropped => "DROPPED", + } + } +} + +struct Report { + id: String, + group: String, + status: Status, + marks: Vec, + detail: String, + used_entries: Vec, +} + +impl Report { + fn line(&self) -> String { + let mut s = format!("{} {}", self.status.label(), self.id); + for m in &self.marks { + s.push(' '); + s.push_str(m); + } + s + } +} + +struct Entry { + /// Index over all loaded lists. + id: usize, + file: String, + line: usize, + case_glob: String, + observable: String, + /// Line glob for stdout and stderr. + sub_glob: Option, +} + +impl Entry { + fn covers(&self, id: &str, observable: &str) -> bool { + if !glob_match(self.case_glob.as_bytes(), id.as_bytes()) { + return false; + } + if self.observable == "all" { + return true; + } + if self.observable != observable { + return false; + } + self.sub_glob.is_none() + } + + fn covers_lines(&self, id: &str, observable: &str) -> bool { + self.sub_glob.is_some() + && self.observable == observable + && glob_match(self.case_glob.as_bytes(), id.as_bytes()) + } +} + +/// Path spellings of the run's directories, longest first, each with its token. +struct Tokens(Vec<(Vec, &'static str)>); + +impl Tokens { + fn new(paths: &[(&Path, &'static str)]) -> Tokens { + let mut list = Vec::new(); + for (path, token) in paths { + for v in path_variants(path) { + list.push((v, *token)); + } + } + list.sort_by(|a, b| b.0.len().cmp(&a.0.len())); + Tokens(list) + } + + fn apply(&self, bytes: &[u8]) -> Vec { + let mut out = bytes.to_vec(); + for (pattern, token) in &self.0 { + out = replace_all(&out, pattern, token.as_bytes()); + } + out + } +} + +fn repo() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} + +pub fn parity_dir() -> PathBuf { + repo().join("tests").join("parity") +} + +/// Panics on any failure. +pub fn run(suite: &Suite, mut cases: Vec) { + let started = Instant::now(); + let repo = repo(); + let local = std::env::var_os("LOCALAPPDATA").expect("LOCALAPPDATA is not set"); + let copy = PathBuf::from(local).join("gash-parity").join("Git"); + assert!( + copy.join("usr").join("bin").join("cygpath.exe").is_file(), + "reference Git copy missing at {}, run tests/parity/setup-ref.ps1 first", + copy.display() + ); + let ref_shell = std::env::var_os("GASH_PARITY_REF") + .map(PathBuf::from) + .unwrap_or_else(|| copy.join("bin").join("bash.exe")); + assert!(ref_shell.is_file(), "reference shell missing at {}", ref_shell.display()); + + let filter = std::env::var("GASH_PARITY_FILTER").unwrap_or_default(); + let jobs = env_count("GASH_PARITY_JOBS", DEFAULT_JOBS as u64) as usize; + let max_drop = env_number("GASH_PARITY_MAX_DROP", DEFAULT_MAX_DROP); + let timeout = Duration::from_secs(env_count("GASH_PARITY_TIMEOUT", DEFAULT_TIMEOUT_S)); + let overlay = parse_overlay(&std::env::var("GASH_PARITY_ENV").unwrap_or_default()); + + let entries = load_accepted(suite, &repo); + + cases.sort_by(|a, b| a.id.cmp(&b.id)); + for pair in cases.windows(2) { + assert!(pair[0].id != pair[1].id, "case id {} is loaded twice", pair[0].id); + } + cases.retain(|c| c.id.contains(filter.as_str())); + assert!(!cases.is_empty(), "no parity cases match GASH_PARITY_FILTER={filter:?}"); + + let out_dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("parity"); + prune_runs(&out_dir, KEEP_RUNS - 1); + let run = out_dir.join(format!("run-{}", utc_stamp())); + assert!(!run.exists(), "run dir {} already exists", run.display()); + let tmp = run.join("tmp"); + let gash_dir = run.join("gashbin"); + for dir in [&tmp, &gash_dir, &run.join("detail")] { + fs::create_dir_all(dir).unwrap_or_else(|e| panic!("cannot create {}: {e}", dir.display())); + } + let gash_exe = std::env::var_os("GASH_PARITY_GASH") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_BIN_EXE_gash"))); + assert!(gash_exe.is_file(), "gash binary missing at {}", gash_exe.display()); + say(&format!("parity: gash binary {}", gash_exe.display())); + for name in ["bash.exe", "sh.exe"] { + fs::copy(&gash_exe, gash_dir.join(name)) + .unwrap_or_else(|e| panic!("cannot copy {} into {}: {e}", gash_exe.display(), gash_dir.display())); + } + + let cfg = Config { + suite, + base_env: base_env(©), + gash_shell: gash_dir.join("bash.exe"), + gash_dir, + copy, + ref_shell, + run, + tmp, + timeout, + overlay, + }; + say(&format!("parity: run dir {}", cfg.run.display())); + + let alive = copy_processes(&cfg, false); + assert!( + alive.is_empty(), + "processes from {} are alive and pin its /tmp mount, stop them first:\n{}", + cfg.copy.display(), + alive.join("\n") + ); + + let mut reports: Vec = Vec::new(); + let (cold, warm): (Vec, Vec) = cases.into_iter().partition(|c| c.cold); + let (serial, parallel): (Vec, Vec) = warm.into_iter().partition(|c| c.serial); + + if !parallel.is_empty() || !serial.is_empty() { + let holder = Holder::start(&cfg); + reports.extend(run_parallel(&cfg, ¶llel, jobs, &entries)); + for case in &serial { + let r = run_case(&cfg, case, &entries); + say(&r.line()); + reports.push(r); + } + holder.stop(); + } + for case in &cold { + let r = run_case(&cfg, case, &entries); + say(&r.line()); + reports.push(r); + } + kill_copy_processes(&cfg); + + reports.sort_by(|a, b| a.id.cmp(&b.id)); + let mut failures: Vec = Vec::new(); + let count = |s: Status| reports.iter().filter(|r| r.status == s).count(); + let diffs = count(Status::Diff); + if diffs > 0 { + failures.push(format!("{diffs} cases diverge from the reference")); + } + + let mut groups: BTreeMap<&str, (usize, usize)> = BTreeMap::new(); + for r in &reports { + let g = groups.entry(r.group.as_str()).or_default(); + g.0 += 1; + if r.status == Status::Dropped { + g.1 += 1; + } + } + for (group, (ran, dropped)) in &groups { + if *dropped > 1 && (*dropped as f64) * 100.0 / (*ran as f64) > max_drop { + failures.push(format!("group {group} dropped {dropped} of {ran} cases, ceiling is one case or {max_drop}%")); + } + } + + // An entry is only checked when its case glob matches a case of this run. + let used: BTreeSet = reports.iter().flat_map(|r| r.used_entries.iter().copied()).collect(); + for e in &entries { + let matching: Vec<&Report> = + reports.iter().filter(|r| glob_match(e.case_glob.as_bytes(), r.id.as_bytes())).collect(); + let unchecked = matching.iter().any(|r| r.status == Status::Dropped); + if !matching.is_empty() && !used.contains(&e.id) && !unchecked { + failures.push(format!("{} line {} matched no divergence", e.file, e.line)); + } + } + + for r in &reports { + if !r.detail.is_empty() { + let path = cfg.run.join("detail").join(format!("{}.txt", r.id.replace('/', "__"))); + fs::write(&path, &r.detail).unwrap_or_else(|e| panic!("cannot write {}: {e}", path.display())); + } + } + let final_line = format!( + "parity: {} pass, {} diff, {} accepted, {} dropped ({:.1}s)", + count(Status::Pass), + diffs, + count(Status::Accepted), + count(Status::Dropped), + started.elapsed().as_secs_f64() + ); + let mut summary: String = reports.iter().map(|r| r.line() + "\n").collect(); + for f in &failures { + summary.push_str(&format!("FAILURE {f}\n")); + } + summary.push_str(&final_line); + summary.push('\n'); + let summary_path = cfg.run.join("summary.txt"); + fs::write(&summary_path, &summary).unwrap_or_else(|e| panic!("cannot write {}: {e}", summary_path.display())); + + let still = copy_processes(&cfg, false); + if !still.is_empty() { + failures.push(format!("processes from the copy still alive after the run: {}", still.join(", "))); + } + say(&final_line); + if !failures.is_empty() { + panic!("parity failed:\n{}\nsummary: {}", failures.join("\n"), summary_path.display()); + } +} + +/// Prints past the test harness's output capture. +fn say(line: &str) { + let mut out = std::io::stdout().lock(); + let _ = writeln!(out, "{line}"); + let _ = out.flush(); +} + +fn env_number(name: &str, default: f64) -> f64 { + match std::env::var(name) { + Ok(v) => v + .trim() + .parse::() + .ok() + .filter(|n| *n > 0.0) + .unwrap_or_else(|| panic!("{name}={v:?} is not a positive number")), + Err(_) => default, + } +} + +fn env_count(name: &str, default: u64) -> u64 { + match std::env::var(name) { + Ok(v) => v + .trim() + .parse::() + .ok() + .filter(|n| *n > 0) + .unwrap_or_else(|| panic!("{name}={v:?} is not a positive integer")), + Err(_) => default, + } +} + +/// Splits a `;`-separated knob value, dropping empty items. +fn env_list(name: &str) -> Option> { + let value = std::env::var(name).ok()?; + let items: Vec = value.split(';').map(str::trim).filter(|s| !s.is_empty()).map(String::from).collect(); + assert!(!items.is_empty(), "{name}={value:?} names nothing"); + Some(items) +} + +fn parse_overlay(text: &str) -> Vec<(String, String)> { + text.split(';') + .filter(|s| !s.trim().is_empty()) + .map(|s| { + let (k, v) = s.split_once('=').unwrap_or_else(|| panic!("GASH_PARITY_ENV entry {s:?} is not K=V")); + (k.to_string(), v.to_string()) + }) + .collect() +} + +/// Repo-relative paths resolve against the repo root. +fn load_accepted(suite: &Suite, repo: &Path) -> Vec { + let files = env_list("GASH_PARITY_ACCEPTED") + .unwrap_or_else(|| vec![format!("tests/parity/{}", suite.accepted)]); + let mut entries = Vec::new(); + for file in files { + parse_accepted(&repo.join(&file), &file, &mut entries); + } + entries +} + +fn parse_accepted(path: &Path, name: &str, entries: &mut Vec) { + let text = fs::read_to_string(path).unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display())); + for (i, raw) in text.lines().enumerate() { + let line = raw.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let (case_glob, rest) = split_word(line); + let (obs, mut reason) = split_word(rest); + let (observable, mut sub_glob) = match obs.split_once(':') { + Some((o, g)) => (o, Some(g)), + None => (obs, None), + }; + let mut closed = true; + if sub_glob.is_some_and(|g| g.starts_with('"')) { + let quoted = &rest[observable.len() + 2..]; + closed = false; + if let Some((g, tail)) = quoted.split_once('"') { + closed = tail.is_empty() || tail.starts_with(char::is_whitespace); + sub_glob = Some(g); + reason = tail.trim(); + } + } + let sub_ok = match sub_glob { + None => true, + Some(g) => !g.is_empty() && (observable == "stdout" || observable == "stderr"), + }; + let known = OBSERVABLES.contains(&observable); + let valid = known && sub_ok && closed && !reason.is_empty(); + assert!( + valid, + "{} line {}: expected ` [:] `, got {raw:?}", + path.display(), + i + 1 + ); + entries.push(Entry { + id: entries.len(), + file: name.to_string(), + line: i + 1, + case_glob: case_glob.to_string(), + observable: observable.to_string(), + sub_glob: sub_glob.map(String::from), + }); + } +} + +fn split_word(s: &str) -> (&str, &str) { + match s.split_once(char::is_whitespace) { + Some((word, rest)) => (word, rest.trim_start()), + None => (s, ""), + } +} + +/// The `tests/scripts` cases as group `compat`, each run in place. +pub fn compat_cases() -> Vec { + let scripts = repo().join("tests").join("scripts"); + let mut cases = Vec::new(); + for file in sh_files(&scripts) { + let mut case = parse_case("compat", &file); + let name = file.file_name().unwrap().to_string_lossy().into_owned(); + case.in_place = Some((name, scripts.clone())); + case.env.insert(0, ("LC_ALL".to_string(), "C".to_string())); + cases.push(case); + } + cases +} + +/// One group per subdirectory of `root`. +pub fn group_cases(root: &Path) -> Vec { + let mut cases = Vec::new(); + if root.is_dir() { + for dir in read_dir_sorted(root).into_iter().filter(|p| p.is_dir()) { + let group = dir.file_name().unwrap().to_string_lossy().into_owned(); + cases.extend(flat_cases(&dir, &group)); + } + } + cases +} + +/// The `*.sh` files of `dir` as one group. +fn flat_cases(dir: &Path, group: &str) -> Vec { + sh_files(dir).iter().map(|file| parse_case(group, file)).collect() +} + +fn read_dir_sorted(dir: &Path) -> Vec { + let mut paths: Vec = fs::read_dir(dir) + .unwrap_or_else(|e| panic!("cannot read {}: {e}", dir.display())) + .map(|e| e.unwrap_or_else(|e| panic!("cannot read {}: {e}", dir.display())).path()) + .collect(); + paths.sort(); + paths +} + +fn sh_files(dir: &Path) -> Vec { + read_dir_sorted(dir) + .into_iter() + .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "sh")) + .collect() +} + +fn parse_case(group: &str, file: &Path) -> Case { + let stem = file.file_stem().unwrap().to_string_lossy().into_owned(); + let text = fs::read(file).unwrap_or_else(|e| panic!("cannot read {}: {e}", file.display())); + let text = String::from_utf8_lossy(&text).into_owned(); + let mut case = Case { + id: format!("{group}/{stem}"), + group: group.to_string(), + file: file.to_path_buf(), + mode: Mode::Script, + body: String::new(), + in_place: None, + fixture: None, + home: None, + env: Vec::new(), + serial: false, + cold: false, + timeout: None, + kill_after: None, + no_console: false, + }; + let bad = |what: &str| -> ! { panic!("{}: {what}", file.display()) }; + let fixture_dir = |value: &str| -> PathBuf { + let dir = parity_dir().join("fixtures").join(value); + if !dir.is_dir() { + bad(&format!("fixture {} does not exist", dir.display())); + } + dir + }; + let mut lines = text.split_inclusive('\n').peekable(); + while let Some(line) = lines.peek() { + let Some(header) = line.trim_end().strip_prefix("# parity:") else { break }; + let (key, value) = header.trim().split_once('=').unwrap_or_else(|| bad("header is not key=value")); + match key { + "mode" => { + case.mode = match value { + "script" => Mode::Script, + "c" => Mode::C, + "lc" => Mode::Lc, + "host" => Mode::Host, + _ => bad(&format!("unknown mode {value:?}")), + } + } + "fixture" => case.fixture = Some(fixture_dir(value)), + "home" => case.home = Some(fixture_dir(value)), + "kill-after" => { + if value.is_empty() || value.contains(['/', '\\']) { + bad("kill-after needs a plain file name"); + } + case.kill_after = Some(value.to_string()); + } + "console" => { + if value != "none" { + bad("console only takes none"); + } + case.no_console = true; + } + "env" => { + let (k, v) = value.split_once('=').unwrap_or_else(|| bad("env header needs env=K=V")); + case.env.push((k.to_string(), v.to_string())); + } + "serial" => { + if value != "1" { + bad("serial only takes 1"); + } + case.serial = true; + } + "cold" => { + if value != "1" { + bad("cold only takes 1"); + } + case.cold = true; + } + "timeout" => { + let secs = value.parse::().ok().filter(|s| *s > 0).unwrap_or_else(|| bad("timeout needs seconds")); + case.timeout = Some(Duration::from_secs(secs)); + } + _ => bad(&format!("unknown header key {key:?}")), + } + lines.next(); + } + case.body = lines.collect::().trim_start_matches(['\r', '\n']).trim_end().to_string(); + if case.mode != Mode::Script && case.body.is_empty() { + bad("empty command body"); + } + case +} + +fn base_env(copy: &Path) -> Vec<(String, String)> { + let mut env: Vec<(String, String)> = std::env::vars_os() + .map(|(k, v)| (k.to_string_lossy().into_owned(), v.to_string_lossy().into_owned())) + .filter(|(k, _)| { + let upper = k.to_ascii_uppercase(); + !REMOVED_ENV.contains(&upper.as_str()) + && !REMOVED_ENV_PREFIXES.iter().any(|p| upper.starts_with(p)) + }) + .collect(); + let root = win(copy); + for (k, v) in [ + ("GIT_EDITOR", "true"), + ("GASH_ROOT", root.as_str()), + ("GASH_COREUTILS", "0"), + ("GIT_OPTIONAL_LOCKS", "0"), + ("GIT_PAGER", "cat"), + ("PAGER", "cat"), + ("GIT_CONFIG_COUNT", "1"), + ("GIT_CONFIG_KEY_0", "core.fsmonitor"), + ("GIT_CONFIG_VALUE_0", "false"), + ] + .into_iter() + { + set_env(&mut env, k, v); + } + env +} + +/// Sets a variable, replacing an existing one whose name differs only in case. +fn set_env(env: &mut Vec<(String, String)>, key: &str, value: &str) { + match env.iter_mut().find(|(k, _)| k.eq_ignore_ascii_case(key)) { + Some(slot) => *slot = (key.to_string(), value.to_string()), + None => env.push((key.to_string(), value.to_string())), + } +} + +fn expand_env_value(value: &str, case_dir: &Path) -> String { + value.replace("@CASE@", &win(case_dir)) +} + +/// Deletes the oldest `run-*` dirs under `dir` until `keep` are left. +fn prune_runs(dir: &Path, keep: usize) { + if !dir.is_dir() { + return; + } + let runs: Vec = read_dir_sorted(dir) + .into_iter() + .filter(|p| p.is_dir() && p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("run-"))) + .collect(); + for old in &runs[..runs.len().saturating_sub(keep)] { + fs::remove_dir_all(old).unwrap_or_else(|e| panic!("cannot prune old run dir {}: {e}", old.display())); + } +} + +struct Holder { + child: Child, + job: ProcessJob, +} + +impl Holder { + /// A long sleep from the copy that pins its `/tmp` mount to the run tmp dir. + fn start(cfg: &Config) -> Holder { + let mut env = cfg.base_env.clone(); + set_env(&mut env, "TMP", &win(&cfg.tmp)); + set_env(&mut env, "TEMP", &win(&cfg.tmp)); + let sleep = cfg.copy.join("usr").join("bin").join("sleep.exe"); + let mut child = Command::new(&sleep) + .arg(HOLDER_SECONDS) + .env_clear() + .envs(env.iter().map(|(k, v)| (k, v))) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap_or_else(|e| panic!("cannot start holder {}: {e}", sleep.display())); + let job = ProcessJob::attach_kill_on_close(&child); + if !job.is_attached() { + let _ = child.kill(); + panic!("cannot put the holder into a kill-on-close job"); + } + thread::sleep(Duration::from_millis(300)); + + let mut cmd = Command::new(cfg.copy.join("usr").join("bin").join("cygpath.exe")); + cmd.args(["-w", "/tmp"]).env_clear().envs(env.iter().map(|(k, v)| (k, v))).stdin(Stdio::null()); + let out = run_command(cmd, Duration::from_secs(30), true); + let mapped = String::from_utf8_lossy(&out.stdout).trim().to_string(); + let alive = matches!(child.try_wait(), Ok(None)); + if !alive || !mapped.eq_ignore_ascii_case(&win(&cfg.tmp)) { + job.terminate(); + panic!( + "holder check failed: alive={alive}, /tmp maps to {mapped:?}, want {:?}, cygpath stderr {:?}", + win(&cfg.tmp), + String::from_utf8_lossy(&out.stderr) + ); + } + say(&format!("parity: holder pid {} pins /tmp to {mapped}", child.id())); + Holder { child, job } + } + + fn stop(mut self) { + self.job.terminate(); + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// Lists, and with `kill` stops, every process whose image lives under the copy. +fn copy_processes(cfg: &Config, kill: bool) -> Vec { + let script = format!( + "$p = @(Get-Process -ErrorAction SilentlyContinue | Where-Object {{ $_.Path -and $_.Path -like '{}\\*' }}); {} foreach ($x in $p) {{ '{{0}} {{1}}' -f $x.Id, $x.Path }}", + win(&cfg.copy).replace('\'', "''"), + if kill { "$p | Stop-Process -Force -ErrorAction SilentlyContinue;" } else { "" } + ); + let out = Command::new("powershell") + .args(["-NoProfile", "-NonInteractive", "-Command", &script]) + .stdin(Stdio::null()) + .output() + .unwrap_or_else(|e| panic!("cannot run powershell to list copy processes: {e}")); + assert!( + out.status.success(), + "powershell process listing failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).collect() +} + +/// Leaves no copy process alive, which resets the copy's mount table. +fn kill_copy_processes(cfg: &Config) { + for _ in 0..20 { + if copy_processes(cfg, true).is_empty() { + break; + } + thread::sleep(Duration::from_millis(200)); + } + let left = copy_processes(cfg, false); + assert!(left.is_empty(), "copy processes survive the kill: {}", left.join(", ")); + thread::sleep(Duration::from_millis(500)); +} + +fn run_parallel(cfg: &Config, cases: &[Case], jobs: usize, entries: &[Entry]) -> Vec { + let next = AtomicUsize::new(0); + let results: Mutex> = Mutex::new(Vec::new()); + thread::scope(|scope| { + for _ in 0..jobs.min(cases.len()) { + scope.spawn(|| loop { + let i = next.fetch_add(1, Ordering::SeqCst); + if i >= cases.len() { + break; + } + let r = run_case(cfg, &cases[i], entries); + say(&r.line()); + results.lock().unwrap().push(r); + }); + } + }); + results.into_inner().unwrap() +} + +fn run_case(cfg: &Config, case: &Case, entries: &[Entry]) -> Report { + let case_root = cfg.run.join("cases").join(&case.group).join(case.id.split_once('/').unwrap().1); + let dirs = [Which::R1, Which::G, Which::R2].map(|w| case_root.join(w.dir())); + let tokens = Tokens::new(&[ + (&dirs[0], ""), + (&dirs[1], ""), + (&dirs[2], ""), + (&cfg.tmp, ""), + (&cfg.copy, ""), + (&cfg.gash_dir, ""), + ]); + let runs = [Which::R1, Which::G, Which::R2].map(|w| { + if case.cold { + kill_copy_processes(cfg); + } + run_one(cfg, case, w, &case_root.join(w.dir()), &tokens) + }); + judge(case, &runs, &dirs, &tokens, entries) +} + +fn run_one(cfg: &Config, case: &Case, which: Which, dir: &Path, tokens: &Tokens) -> RunResult { + let fixture = dir.join("fixture"); + let home = dir.join("home"); + let probe = dir.join("probe"); + for d in [&fixture, &home, &probe] { + fs::create_dir_all(d).unwrap_or_else(|e| panic!("cannot create {}: {e}", d.display())); + } + if let Some(template) = &case.fixture { + copy_tree(template, &fixture); + } + if let Some(template) = &case.home { + copy_tree(template, &home); + } + let walk_tmp = case.serial || case.cold; + if walk_tmp { + clear_dir(&cfg.tmp); + } + + let shell = match which { + Which::G => &cfg.gash_shell, + _ => &cfg.ref_shell, + }; + let mut cmd = Command::new(shell); + let cwd = match &case.in_place { + Some((name, dir)) => { + cmd.arg(name); + dir.clone() + } + None => { + match case.mode { + Mode::Script => { + cmd.arg(fwd(&case.file)); + } + Mode::C => { + cmd.args(["-c", &case.body]); + } + Mode::Lc => { + cmd.args(["-l", "-c", &case.body]); + } + // The entry's host command goes in below. + Mode::Host => {} + } + fixture.clone() + } + }; + + let mut env = cfg.base_env.clone(); + set_env(&mut env, "HOME", &win(&home)); + set_env(&mut env, "TMP", &win(&cfg.tmp)); + set_env(&mut env, "TEMP", &win(&cfg.tmp)); + set_env(&mut env, "SHELL", &win(shell)); + set_env(&mut env, "PARITY_PROBE_DIR", &fwd(&probe)); + let kill_tag = case.kill_after.as_ref().map(|_| kill_tag()); + if let Some(tag) = &kill_tag { + set_env(&mut env, "PARITY_KILL_TAG", tag); + } + for (k, v) in cfg.overlay.iter().chain(case.env.iter()) { + let value = expand_env_value(v, dir); + set_env(&mut env, k, &value); + } + let cwd_file = probe.join("cwd"); + let host = case.mode == Mode::Host && case.in_place.is_none(); + if host { + cmd.args(["-c", "-l", &(cfg.suite.host_command)(&case.body, &cwd_file)]); + } + cmd.current_dir(&cwd).env_clear().envs(env.iter().map(|(k, v)| (k, v))); + if case.no_console { + no_window(&mut cmd); + } + cmd.stdin(Stdio::null()); + + let timeout = case.timeout.unwrap_or(cfg.timeout); + let mut survivors = None; + let out = match (&case.kill_after, &kill_tag) { + (Some(marker), Some(tag)) => { + let mut killer = Killer::new(probe.join(marker), tag); + let out = run_command_watched(cmd, timeout, true, &mut |pid, exited| killer.watch(pid, exited)); + survivors = Some(killer.result.into_bytes()); + out + } + _ => run_command(cmd, timeout, true), + }; + if let Some(err) = &out.spawn_error { + panic!("{}: cannot spawn {}: {err}", case.id, shell.display()); + } + for (name, bytes) in [("stdout.txt", &out.stdout), ("stderr.txt", &out.stderr)] { + let path = dir.join(name); + fs::write(&path, bytes).unwrap_or_else(|e| panic!("cannot write {}: {e}", path.display())); + } + + let mut roots = vec![("fixture", fixture.clone()), ("home", home.clone())]; + if walk_tmp { + roots.push(("tmp", cfg.tmp.clone())); + } + let mut tree = Vec::new(); + for (label, root) in &roots { + walk(root, label, tokens, &mut tree); + } + RunResult { + out, + tree, + cwd: if host { Some(read_or_missing(&cwd_file)) } else { None }, + survivors, + } +} + +fn read_or_missing(path: &Path) -> Vec { + fs::read(path).unwrap_or_else(|_| b"(missing)".to_vec()) +} + +#[cfg(windows)] +fn no_window(cmd: &mut Command) { + use std::os::windows::process::CommandExt; + cmd.creation_flags(CREATE_NO_WINDOW); +} + +#[cfg(not(windows))] +fn no_window(_cmd: &mut Command) {} + +/// A digit string no other process on the machine carries in its command line. +fn kill_tag() -> String { + let nanos = SystemTime::now().duration_since(UNIX_EPOCH).expect("clock before 1970").subsec_nanos(); + format!("7{}{:09}{}", std::process::id(), nanos, KILL_TAGS.fetch_add(1, Ordering::SeqCst)) +} + +/// Tree-kills the shell once the case writes its marker and counts the tagged survivors. +struct Killer { + marker: PathBuf, + tag: String, + started: Instant, + fired: bool, + marker_seen: bool, + result: String, +} + +impl Killer { + fn new(marker: PathBuf, tag: &str) -> Killer { + Killer { + marker, + tag: tag.to_string(), + started: Instant::now(), + fired: false, + marker_seen: false, + result: String::new(), + } + } + + fn watch(&mut self, pid: u32, exited: bool) { + if !exited { + if !self.fired && (self.marker.exists() || self.started.elapsed() >= KILL_WAIT) { + self.fired = true; + self.marker_seen = self.marker.exists(); + let _ = Command::new("taskkill") + .args(["/T", "/F", "/PID", &pid.to_string()]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } + return; + } + thread::sleep(Duration::from_secs(1)); + let count = kill_tagged(&self.tag); + self.result = match (self.fired, self.marker_seen) { + (true, true) => count, + (true, false) => format!("marker missing after {}s, {count}", KILL_WAIT.as_secs()), + (false, _) => format!("shell exited before the kill, {count}"), + }; + } +} + +/// Stops every process whose command line carries `tag` and returns how many there were. +fn kill_tagged(tag: &str) -> String { + let script = format!( + "$p = @(Get-CimInstance Win32_Process | Where-Object {{ $_.ProcessId -ne $PID -and $_.CommandLine -like '*{tag}*' }}); \ + foreach ($x in $p) {{ Stop-Process -Id $x.ProcessId -Force -ErrorAction SilentlyContinue }}; $p.Count" + ); + let out = Command::new("powershell") + .args(["-NoProfile", "-NonInteractive", "-Command", &script]) + .stdin(Stdio::null()) + .output() + .unwrap_or_else(|e| panic!("cannot run powershell to count tagged processes: {e}")); + assert!(out.status.success(), "tagged process count failed: {}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +fn copy_tree(from: &Path, to: &Path) { + for src in read_dir_sorted(from) { + let dst = to.join(src.file_name().unwrap()); + if src.is_dir() { + fs::create_dir_all(&dst).unwrap_or_else(|e| panic!("cannot create {}: {e}", dst.display())); + copy_tree(&src, &dst); + } else { + fs::copy(&src, &dst).unwrap_or_else(|e| panic!("cannot copy {}: {e}", src.display())); + } + } +} + +fn clear_dir(dir: &Path) { + for path in read_dir_sorted(dir) { + let res = if path.is_dir() { fs::remove_dir_all(&path) } else { fs::remove_file(&path) }; + res.unwrap_or_else(|e| panic!("cannot clear {}: {e}", path.display())); + } +} + +/// Appends one line per entry under `root`, hashing file content after token normalisation. +fn walk(root: &Path, label: &str, tokens: &Tokens, out: &mut Vec) { + let Ok(entries) = fs::read_dir(root) else { + out.extend_from_slice(format!("{label} unreadable\n").as_bytes()); + return; + }; + let mut paths: Vec = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect(); + paths.sort(); + for path in paths { + let rel = format!("{label}/{}", path.file_name().unwrap().to_string_lossy()); + let Ok(meta) = fs::symlink_metadata(&path) else { + out.extend_from_slice(format!("{rel} unreadable\n").as_bytes()); + continue; + }; + if meta.file_type().is_symlink() { + let target = fs::read_link(&path).map(|t| t.to_string_lossy().into_owned()).unwrap_or_default(); + let target = String::from_utf8_lossy(&tokens.apply(target.as_bytes())).into_owned(); + out.extend_from_slice(format!("{rel} l {target}\n").as_bytes()); + } else if meta.is_dir() { + out.extend_from_slice(format!("{rel} d\n").as_bytes()); + walk(&path, &rel, tokens, out); + } else { + match fs::read(&path) { + Ok(bytes) => { + let norm = tokens.apply(&bytes); + out.extend_from_slice(format!("{rel} f {} {:016x}\n", norm.len(), fnv1a(&norm)).as_bytes()); + } + Err(e) => out.extend_from_slice(format!("{rel} f unreadable {e}\n").as_bytes()), + } + } + } +} + +fn fnv1a(bytes: &[u8]) -> u64 { + let mut h: u64 = 0xcbf29ce484222325; + for &b in bytes { + h ^= b as u64; + h = h.wrapping_mul(0x100000001b3); + } + h +} + +/// One compared observable after normalisation. +struct Obs { + name: &'static str, + vals: [Vec; 3], +} + +fn judge(case: &Case, runs: &[RunResult; 3], dirs: &[PathBuf; 3], tokens: &Tokens, entries: &[Entry]) -> Report { + let code = |r: &RunResult| -> Vec { + match (r.out.timed_out, r.out.code) { + (true, _) => b"timeout".to_vec(), + (false, Some(c)) => c.to_string().into_bytes(), + (false, None) => b"none".to_vec(), + } + }; + let mut obs = vec![ + Obs { name: "stdout", vals: [0, 1, 2].map(|i| tokens.apply(&runs[i].out.stdout)) }, + Obs { name: "stderr", vals: [0, 1, 2].map(|i| shell_prefix(&tokens.apply(&runs[i].out.stderr))) }, + Obs { name: "code", vals: [0, 1, 2].map(|i| code(&runs[i])) }, + Obs { name: "tree", vals: [0, 1, 2].map(|i| runs[i].tree.clone()) }, + ]; + if runs[0].cwd.is_some() { + obs.push(Obs { name: "cwd", vals: [0, 1, 2].map(|i| tokens.apply(runs[i].cwd.as_deref().unwrap_or_default())) }); + } + if runs[0].survivors.is_some() { + obs.push(Obs { name: "survivors", vals: [0, 1, 2].map(|i| runs[i].survivors.clone().unwrap_or_default()) }); + } + + let mut detail = format!("{}\ncase file: {}\n", case.id, case.file.display()); + for (i, w) in [Which::R1, Which::G, Which::R2].iter().enumerate() { + let o = &runs[i].out; + detail.push_str(&format!( + "{}: dir {}, code {}, {:.1}s{}{}\n", + w.dir(), + dirs[i].display(), + String::from_utf8_lossy(&code(&runs[i])), + o.elapsed.as_secs_f64(), + if o.timed_out { ", timed out" } else { "" }, + if o.pipes_left_open { ", pipes left open" } else { "" } + )); + } + + let mut marks = Vec::new(); + let mut used = Vec::new(); + let mut diverged = false; + let mut unaccepted = false; + let ref_timeout = runs[0].out.timed_out || runs[2].out.timed_out; + let flaky_key = obs.iter().any(|o| (o.name == "stdout" || o.name == "code") && o.vals[0] != o.vals[2]); + if ref_timeout || flaky_key { + if ref_timeout { + marks.push("ref-timeout".to_string()); + } + for o in obs.iter().filter(|o| o.vals[0] != o.vals[2]) { + marks.push(format!("flaky:{}", o.name)); + detail.push_str(&line_diff(o.name, "r1", "r2", &o.vals[0], &o.vals[2], DETAIL_DIFF_LINES)); + } + return finish(case, Status::Dropped, marks, detail, used, runs, tokens); + } + + for o in &obs { + if o.vals[0] != o.vals[2] { + marks.push(format!("flaky:{}", o.name)); + detail.push_str(&line_diff(&format!("flaky {}", o.name), "r1", "r2", &o.vals[0], &o.vals[2], DETAIL_DIFF_LINES)); + continue; + } + if o.vals[0] == o.vals[1] { + continue; + } + diverged = true; + let hit: Vec = entries.iter().filter(|e| e.covers(&case.id, o.name)).map(|e| e.id).collect(); + let line_entries: Vec<&Entry> = entries.iter().filter(|e| e.covers_lines(&case.id, o.name)).collect(); + if !hit.is_empty() { + used.extend(hit); + marks.push(format!("accepted:{}", o.name)); + } else if !line_entries.is_empty() { + let (ref_kept, ref_hits) = drop_lines(&o.vals[0], &line_entries); + let (gash_kept, gash_hits) = drop_lines(&o.vals[1], &line_entries); + used.extend(ref_hits); + used.extend(gash_hits); + if ref_kept == gash_kept { + marks.push(format!("accepted:{}(lines)", o.name)); + } else { + unaccepted = true; + marks.push(o.name.to_string()); + let what = format!("{} without accepted lines", o.name); + detail.push_str(&line_diff(&what, "ref", "gash", &ref_kept, &gash_kept, DETAIL_DIFF_LINES)); + } + } else { + unaccepted = true; + marks.push(o.name.to_string()); + } + detail.push_str(&line_diff(o.name, "ref", "gash", &o.vals[0], &o.vals[1], DETAIL_DIFF_LINES)); + } + + let status = match (diverged, unaccepted) { + (false, _) => Status::Pass, + (true, true) => Status::Diff, + (true, false) => Status::Accepted, + }; + finish(case, status, marks, detail, used, runs, tokens) +} + +/// Drops every line a line entry's glob matches, ignoring the line ending. +fn drop_lines(bytes: &[u8], line_entries: &[&Entry]) -> (Vec, Vec) { + let mut kept = Vec::new(); + let mut hits = Vec::new(); + for line in bytes.split_inclusive(|&b| b == b'\n') { + let body = line.strip_suffix(b"\n").unwrap_or(line); + let body = body.strip_suffix(b"\r").unwrap_or(body); + let matched: Vec = line_entries + .iter() + .filter(|e| e.sub_glob.as_ref().is_some_and(|g| glob_match(g.as_bytes(), body))) + .map(|e| e.id) + .collect(); + if matched.is_empty() { + kept.extend_from_slice(line); + } else { + hits.extend(matched); + } + } + (kept, hits) +} + +fn finish( + case: &Case, + status: Status, + marks: Vec, + mut detail: String, + used_entries: Vec, + runs: &[RunResult; 3], + tokens: &Tokens, +) -> Report { + if status == Status::Pass { + detail.clear(); + } else { + detail.insert_str(0, &format!("{} ", status.label())); + detail.push_str("ref (r1)\n"); + detail.push_str(&stderr_excerpt(&shell_prefix(&tokens.apply(&runs[0].out.stderr)))); + detail.push_str("gash\n"); + detail.push_str(&stderr_excerpt(&shell_prefix(&tokens.apply(&runs[1].out.stderr)))); + } + Report { id: case.id.clone(), group: case.group.clone(), status, marks, detail, used_entries } +} + +/// Replaces a leading shell name prefix on each stderr line with `: `. +fn shell_prefix(bytes: &[u8]) -> Vec { + const PREFIXES: &[&[u8]] = &[ + b"bash.exe: ", + b"bash: ", + b"sh.exe: ", + b"sh: ", + b"gash.exe: ", + b"gash: ", + b"/usr/bin/bash.exe: ", + b"/usr/bin/bash: ", + b"/bin/bash.exe: ", + b"/bin/bash: ", + b"/usr/bin/sh.exe: ", + b"/usr/bin/sh: ", + b"/bin/sh.exe: ", + b"/bin/sh: ", + ]; + let mut out = Vec::with_capacity(bytes.len()); + for line in bytes.split_inclusive(|&b| b == b'\n') { + match PREFIXES.iter().find(|p| line.starts_with(p)) { + Some(p) => { + out.extend_from_slice(b": "); + out.extend_from_slice(&line[p.len()..]); + } + None => out.extend_from_slice(line), + } + } + out +} + +fn replace_all(hay: &[u8], pattern: &[u8], with: &[u8]) -> Vec { + if pattern.is_empty() || hay.len() < pattern.len() { + return hay.to_vec(); + } + let mut out = Vec::with_capacity(hay.len()); + let mut i = 0; + while i < hay.len() { + if hay[i..].starts_with(pattern) { + out.extend_from_slice(with); + i += pattern.len(); + } else { + out.push(hay[i]); + i += 1; + } + } + out +} + +/// `C:\a\b`, `C:/a/b` and `/c/a/b`, each with either drive letter case. +fn path_variants(path: &Path) -> Vec> { + let w = win(path); + let b = w.as_bytes(); + if b.len() < 3 || b[1] != b':' { + return vec![w.into_bytes()]; + } + let back = &w[2..]; + let fwd = back.replace('\\', "/"); + let lower = b[0].to_ascii_lowercase() as char; + let mut out = Vec::new(); + for d in [lower.to_ascii_uppercase(), lower] { + out.push(format!("{d}:{back}").into_bytes()); + out.push(format!("{d}:{fwd}").into_bytes()); + out.push(format!("/{d}{fwd}").into_bytes()); + } + out +} + +fn win(path: &Path) -> String { + path.to_string_lossy().replace('/', "\\") +} + +fn fwd(path: &Path) -> String { + path.to_string_lossy().replace('\\', "/") +} + +pub fn posix(path: &Path) -> String { + let f = fwd(path); + match f.as_bytes() { + [d, b':', b'/', ..] => format!("/{}{}", (*d as char).to_ascii_lowercase(), &f[2..]), + _ => f, + } +} + +/// Glob with `*` and `?`. +fn glob_match(pattern: &[u8], text: &[u8]) -> bool { + let (mut p, mut t) = (0, 0); + let mut star: Option<(usize, usize)> = None; + while t < text.len() { + if p < pattern.len() && (pattern[p] == b'?' || (pattern[p] != b'*' && pattern[p] == text[t])) { + p += 1; + t += 1; + } else if p < pattern.len() && pattern[p] == b'*' { + star = Some((p, t)); + p += 1; + } else if let Some((sp, st)) = star { + p = sp + 1; + t = st + 1; + star = Some((sp, st + 1)); + } else { + return false; + } + } + pattern[p..].iter().all(|&c| c == b'*') +} + +/// UTC `YYYYMMDD-HHMMSS`. +fn utc_stamp() -> String { + let secs = SystemTime::now().duration_since(UNIX_EPOCH).expect("clock before 1970").as_secs() as i64; + let (days, rem) = (secs.div_euclid(86400), secs.rem_euclid(86400)); + // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm). + let z = days + 719468; + let era = z.div_euclid(146097); + let doe = z - era * 146097; + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + if month <= 2 { 1 } else { 0 }; + format!("{year:04}{month:02}{day:02}-{:02}{:02}{:02}", rem / 3600, rem % 3600 / 60, rem % 60) +} diff --git a/tests/parity/setup-ref.ps1 b/tests/parity/setup-ref.ps1 new file mode 100644 index 0000000..a6d4cae --- /dev/null +++ b/tests/parity/setup-ref.ps1 @@ -0,0 +1,37 @@ +param( + # Git for Windows install the reference copy mirrors + [string]$Source = 'C:\Program Files\Git' +) +$ErrorActionPreference = 'Stop' + +$dst = Join-Path $env:LOCALAPPDATA 'gash-parity\Git' +$markerName = 'gash-parity-copy.txt' +$marker = Join-Path $dst $markerName + +if (-not (Test-Path -LiteralPath (Join-Path $Source 'usr\bin\cygpath.exe'))) { + Write-Host "$Source is not a Git for Windows install, usr\bin\cygpath.exe is missing" + exit 1 +} + +# The mirror deletes whatever else the destination holds. +if ((Test-Path -LiteralPath $dst) -and -not (Test-Path -LiteralPath $marker)) { + if (Get-ChildItem -LiteralPath $dst -Force | Select-Object -First 1) { + Write-Host "$dst exists and has no $markerName, so it is not a copy made by this script. Remove it first." + exit 1 + } +} + +New-Item -ItemType Directory -Force -Path $dst | Out-Null +Set-Content -LiteralPath $marker -Value "Parity reference copy of $Source" + +# /XF keeps the marker out of the purge. +# Exit codes below 8 mean success (files copied, extra files, mismatches). +robocopy $Source $dst /MIR /XF $markerName /NFL /NDL /NJH /NJS /NP /R:1 /W:1 | Out-Null +$code = $LASTEXITCODE +if ($code -ge 8) { + Write-Host "robocopy failed with exit code $code" + exit $code +} + +Write-Host $dst +exit 0 diff --git a/tests/scripts/069_kill_wait_status.sh b/tests/scripts/069_kill_wait_status.sh index fc11989..98521eb 100644 --- a/tests/scripts/069_kill_wait_status.sh +++ b/tests/scripts/069_kill_wait_status.sh @@ -1,6 +1,7 @@ # wait reports 128+signal for a job stopped with kill, as bash does. -sleep 30 & p=$!; kill $p; wait $p; echo "TERM: $?" -sleep 30 & p=$!; kill -9 $p; wait $p 2>/dev/null; echo "KILL: $?" -sleep 30 & p=$!; kill -s HUP $p; wait $p; echo "HUP: $?" -sleep 30 & kill %1; wait %1; echo "job spec: $?" -ping -n 30 127.0.0.1 > /dev/null & p=$!; kill $p; wait $p; echo "native program: $?" +# Under load Git Bash reports status 0 for a job killed while it starts. +sleep 30 & p=$!; sleep 0.3; kill $p; wait $p; echo "TERM: $?" +sleep 30 & p=$!; sleep 0.3; kill -9 $p; wait $p 2>/dev/null; echo "KILL: $?" +sleep 30 & p=$!; sleep 0.3; kill -s HUP $p; wait $p; echo "HUP: $?" +sleep 30 & sleep 0.3; kill %1; wait %1; echo "job spec: $?" +ping -n 30 127.0.0.1 > /dev/null & p=$!; sleep 0.3; kill $p; wait $p; echo "native program: $?" diff --git a/tests/support/mod.rs b/tests/support/mod.rs new file mode 100644 index 0000000..5917701 --- /dev/null +++ b/tests/support/mod.rs @@ -0,0 +1,417 @@ +//! Process running and line diffs shared by the `compat` and `parity` test targets. + +// Each test target uses a different subset of this module. +#![allow(dead_code)] + +use std::io::Read; +use std::process::{Command, Stdio}; +use std::sync::mpsc; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::{Duration, Instant}; + +/// How long a leaked background process may hold the pipes open after the child exits. +pub const PIPE_GRACE: Duration = Duration::from_secs(3); +pub const MAX_DIFF_LINES: usize = 15; +pub const MAX_STDERR_LINES: usize = 10; +pub const MAX_LINE_CHARS: usize = 200; +/// Above this many lines on either side, fall back to a positional diff. +pub const MAX_LCS_LINES: usize = 3000; + +pub struct RunOutput { + pub stdout: Vec, + pub stderr: Vec, + pub code: Option, + pub timed_out: bool, + pub pipes_left_open: bool, + pub spawn_error: Option, + pub elapsed: Duration, +} + +/// Runs `cmd`, killing its process tree at `timeout` and, with `kill_on_close`, on return. +pub fn run_command(cmd: Command, timeout: Duration, kill_on_close: bool) -> RunOutput { + run_command_watched(cmd, timeout, kill_on_close, &mut |_, _| {}) +} + +/// Like `run_command`, calling `watch(pid, exited)` on every poll and once after exit, before the pipes drain. +pub fn run_command_watched( + mut cmd: Command, + timeout: Duration, + kill_on_close: bool, + watch: &mut dyn FnMut(u32, bool), +) -> RunOutput { + let start = Instant::now(); + let failed = |error: String| RunOutput { + stdout: Vec::new(), + stderr: Vec::new(), + code: None, + timed_out: false, + pipes_left_open: false, + spawn_error: Some(error), + elapsed: start.elapsed(), + }; + cmd.stdout(Stdio::piped()).stderr(Stdio::piped()); + let mut child = match cmd.spawn() { + Ok(child) => child, + Err(e) => return failed(e.to_string()), + }; + + let job = if kill_on_close { + ProcessJob::attach_kill_on_close(&child) + } else { + ProcessJob::attach(&child) + }; + if kill_on_close && cfg!(windows) && !job.is_attached() { + let _ = child.kill(); + let _ = child.wait(); + return failed("cannot put the child into a kill-on-close job".to_string()); + } + let stdout = PipeReader::start(child.stdout.take().expect("stdout is piped")); + let stderr = PipeReader::start(child.stderr.take().expect("stderr is piped")); + + let pid = child.id(); + let mut timed_out = false; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break Some(status), + Ok(None) => watch(pid, false), + Err(_) => break None, + } + if start.elapsed() >= timeout { + timed_out = true; + kill_tree(&mut child, &job); + break child.wait().ok(); + } + thread::sleep(Duration::from_millis(5)); + }; + watch(pid, true); + + let deadline = Instant::now() + PIPE_GRACE; + let (stdout, out_open) = stdout.finish(deadline); + let (stderr, err_open) = stderr.finish(deadline); + RunOutput { + stdout, + stderr, + code: status.and_then(|s| s.code()), + timed_out, + pipes_left_open: out_open || err_open, + spawn_error: None, + elapsed: start.elapsed(), + } +} + +/// Kills the child and its descendants through the job, with `taskkill /T` as a fallback. +pub fn kill_tree(child: &mut std::process::Child, job: &ProcessJob) { + job.terminate(); + if cfg!(windows) { + let _ = Command::new("taskkill") + .args(["/T", "/F", "/PID", &child.id().to_string()]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } + let _ = child.kill(); +} + +#[cfg(windows)] +mod job { + use std::ffi::c_void; + use std::os::windows::io::AsRawHandle; + + type Handle = *mut c_void; + + const JOB_OBJECT_EXTENDED_LIMIT_INFORMATION: i32 = 9; + const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: u32 = 0x2000; + + #[repr(C)] + #[derive(Default)] + struct BasicLimitInformation { + per_process_user_time_limit: i64, + per_job_user_time_limit: i64, + limit_flags: u32, + minimum_working_set_size: usize, + maximum_working_set_size: usize, + active_process_limit: u32, + affinity: usize, + priority_class: u32, + scheduling_class: u32, + } + + #[repr(C)] + #[derive(Default)] + struct ExtendedLimitInformation { + basic: BasicLimitInformation, + io_counters: [u64; 6], + process_memory_limit: usize, + job_memory_limit: usize, + peak_process_memory_used: usize, + peak_job_memory_used: usize, + } + + #[link(name = "kernel32")] + unsafe extern "system" { + fn CreateJobObjectW(attributes: *mut c_void, name: *const u16) -> Handle; + fn SetInformationJobObject(job: Handle, class: i32, info: *const c_void, len: u32) -> i32; + fn AssignProcessToJobObject(job: Handle, process: Handle) -> i32; + fn TerminateJobObject(job: Handle, exit_code: u32) -> i32; + fn CloseHandle(handle: Handle) -> i32; + } + + pub struct ProcessJob(Handle); + + impl ProcessJob { + pub fn attach(child: &std::process::Child) -> ProcessJob { + Self::create(child, false) + } + + /// Like `attach`, and closing the job kills every process still in it. + pub fn attach_kill_on_close(child: &std::process::Child) -> ProcessJob { + Self::create(child, true) + } + + fn create(child: &std::process::Child, kill_on_close: bool) -> ProcessJob { + // SAFETY: plain Win32 calls on the live child handle and the job created here. + unsafe { + let job = CreateJobObjectW(std::ptr::null_mut(), std::ptr::null()); + if job.is_null() { + return ProcessJob(job); + } + if kill_on_close { + let mut info = ExtendedLimitInformation::default(); + info.basic.limit_flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + let ok = SetInformationJobObject( + job, + JOB_OBJECT_EXTENDED_LIMIT_INFORMATION, + &info as *const ExtendedLimitInformation as *const c_void, + std::mem::size_of::() as u32, + ); + if ok == 0 { + CloseHandle(job); + return ProcessJob(std::ptr::null_mut()); + } + } + if AssignProcessToJobObject(job, child.as_raw_handle()) == 0 { + CloseHandle(job); + return ProcessJob(std::ptr::null_mut()); + } + ProcessJob(job) + } + } + + pub fn is_attached(&self) -> bool { + !self.0.is_null() + } + + pub fn terminate(&self) { + if !self.0.is_null() { + // SAFETY: self.0 is a live job handle owned by this struct. + unsafe { + TerminateJobObject(self.0, 1); + } + } + } + } + + impl Drop for ProcessJob { + fn drop(&mut self) { + if !self.0.is_null() { + // SAFETY: closing the handle we created exactly once. + unsafe { + CloseHandle(self.0); + } + } + } + } +} + +#[cfg(not(windows))] +mod job { + pub struct ProcessJob; + impl ProcessJob { + pub fn attach(_child: &std::process::Child) -> ProcessJob { + ProcessJob + } + pub fn attach_kill_on_close(_child: &std::process::Child) -> ProcessJob { + ProcessJob + } + pub fn is_attached(&self) -> bool { + false + } + pub fn terminate(&self) {} + } +} + +pub use job::ProcessJob; + +/// Drains a pipe on its own thread, keeping what arrived even when EOF never comes. +pub struct PipeReader { + data: Arc>>, + done: mpsc::Receiver<()>, +} + +impl PipeReader { + pub fn start(mut pipe: R) -> PipeReader { + let data = Arc::new(Mutex::new(Vec::new())); + let (tx, done) = mpsc::channel(); + let sink = Arc::clone(&data); + thread::spawn(move || { + let mut buf = [0u8; 8192]; + loop { + match pipe.read(&mut buf) { + Ok(0) => break, + Ok(n) => sink.lock().unwrap().extend_from_slice(&buf[..n]), + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(_) => break, + } + } + let _ = tx.send(()); + }); + PipeReader { data, done } + } + + /// Returns the collected bytes and whether the pipe was still open at the deadline. + pub fn finish(self, deadline: Instant) -> (Vec, bool) { + let wait = deadline.saturating_duration_since(Instant::now()); + let still_open = self.done.recv_timeout(wait).is_err(); + let bytes = std::mem::take(&mut *self.data.lock().unwrap()); + (bytes, still_open) + } +} + +/// Splits into lines that keep their trailing `\n` (the last one may lack it). +pub fn split_lines(bytes: &[u8]) -> Vec<&[u8]> { + bytes.split_inclusive(|&b| b == b'\n').collect() +} + +#[derive(Clone, Copy)] +enum Edit { + Equal, + Delete(usize), // line index in `a` + Insert(usize), // line index in `b` +} + +fn diff_lines(a: &[&[u8]], b: &[&[u8]]) -> Vec { + if a.len() > MAX_LCS_LINES || b.len() > MAX_LCS_LINES { + let mut edits = Vec::new(); + for i in 0..a.len().max(b.len()) { + match (a.get(i), b.get(i)) { + (Some(x), Some(y)) if x == y => edits.push(Edit::Equal), + (x, y) => { + if x.is_some() { + edits.push(Edit::Delete(i)); + } + if y.is_some() { + edits.push(Edit::Insert(i)); + } + } + } + } + return edits; + } + // lcs[i][j] = length of the LCS of a[i..] and b[j..] + let (n, m) = (a.len(), b.len()); + let width = m + 1; + let mut lcs = vec![0u16; (n + 1) * (m + 1)]; + for i in (0..n).rev() { + for j in (0..m).rev() { + lcs[i * width + j] = if a[i] == b[j] { + lcs[(i + 1) * width + j + 1] + 1 + } else { + lcs[(i + 1) * width + j].max(lcs[i * width + j + 1]) + }; + } + } + let (mut i, mut j) = (0, 0); + let mut edits = Vec::new(); + while i < n || j < m { + if i < n && j < m && a[i] == b[j] { + edits.push(Edit::Equal); + i += 1; + j += 1; + } else if j >= m || (i < n && lcs[(i + 1) * width + j] >= lcs[i * width + j + 1]) { + edits.push(Edit::Delete(i)); + i += 1; + } else { + edits.push(Edit::Insert(j)); + j += 1; + } + } + edits +} + +pub fn stdout_diff(expected: &[u8], actual: &[u8]) -> String { + line_diff("stdout", "expected", "actual", expected, actual, MAX_DIFF_LINES) +} + +pub fn line_diff(what: &str, left_name: &str, right_name: &str, left: &[u8], right: &[u8], max_lines: usize) -> String { + let a = split_lines(left); + let b = split_lines(right); + let edits = diff_lines(&a, &b); + let changed: Vec = edits + .iter() + .filter_map(|e| match *e { + Edit::Equal => None, + Edit::Delete(i) => Some(format!(" - {:>4} | {}", i + 1, show_line(a[i]))), + Edit::Insert(j) => Some(format!(" + {:>4} | {}", j + 1, show_line(b[j]))), + }) + .collect(); + let mut s = format!( + " {what} differs ({} {left_name} lines, {} {right_name}; {} changed; - {left_name}, + {right_name}):\n", + a.len(), + b.len(), + changed.len() + ); + for line in changed.iter().take(max_lines) { + s.push_str(line); + s.push('\n'); + } + if changed.len() > max_lines { + s.push_str(&format!(" ... {} more changed lines\n", changed.len() - max_lines)); + } + s +} + +pub fn stderr_excerpt(stderr: &[u8]) -> String { + if stderr.is_empty() { + return " stderr: (empty)\n".to_string(); + } + let lines = split_lines(stderr); + let mut s = format!( + " stderr (first {} of {} lines):\n", + lines.len().min(MAX_STDERR_LINES), + lines.len() + ); + for line in lines.iter().take(MAX_STDERR_LINES) { + s.push_str(" | "); + s.push_str(&show_line(line)); + s.push('\n'); + } + s +} + +/// Escapes control characters, marks a missing newline and truncates long lines. +pub fn show_line(line: &[u8]) -> String { + let (body, has_newline) = match line.strip_suffix(b"\n") { + Some(body) => (body, true), + None => (line, false), + }; + let text = String::from_utf8_lossy(body); + let mut out = String::new(); + for (count, c) in text.chars().enumerate() { + if count >= MAX_LINE_CHARS { + out.push_str("..."); + break; + } + match c { + '\t' => out.push_str("\\t"), + '\r' => out.push_str("\\r"), + c if c.is_control() => out.push_str(&format!("\\x{:02x}", c as u32)), + c => out.push(c), + } + } + if !has_newline { + out.push_str(" [no newline at end]"); + } + out +}