diff --git a/src/exec.rs b/src/exec.rs index 1c4a594..fccad60 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -97,6 +97,32 @@ fn has_path_sep(name: &str) -> bool { name.contains('/') || name.contains('\\') || path::is_windows_abs(name) } +/// Windows caps a command line at 32,767 characters. Past this length (program and arguments, +/// counted in UTF-8 bytes, which is never less than the UTF-16 length) arguments for an MSYS +/// program go in a response file instead. +const MSYS_CMDLINE_MAX: usize = 30_000; + +/// Add `args`, already quoted with `msys_quote`, to an MSYS program's command line. When they +/// would make it longer than Windows allows, they go in a response file and the program gets +/// `@""`, which the MSYS runtime replaces with the file's contents, parsed like a +/// command line. (Git Bash hands arguments from one MSYS process to the next without the +/// Windows command line, so it has no such limit.) Returns that file: keep it until the +/// program has read it. +fn add_msys_args(cmd: &mut Proc, program: &Path, args: Vec) -> Option { + let len = program.as_os_str().len() + args.iter().map(|a| a.len() + 1).sum::(); + if len > MSYS_CMDLINE_MAX { + if let Ok((f, file)) = crate::io::response_file(args.join(" ").as_bytes()) { + // The quote goes after the @: a quoted @ is taken literally. + cmd.raw_arg(format!("@\"{}\"", file.display())); + return Some(f); + } + } + for a in args { + cmd.raw_arg(a); + } + None +} + /// Quote an argument for an MSYS2/Cygwin program started from a native process /// (whose runtime re-parses the command line with globbing). pub fn msys_quote(a: &str) -> String { @@ -1503,6 +1529,8 @@ impl Shell { return r; } } + // The arguments of an MSYS program, when they are too long for a command line. + let mut rsp: Option = None; let mut cmd; let native; let mut msys_child = false; @@ -1561,9 +1589,7 @@ impl Shell { let fname = res.path.file_name().map(|f| f.to_string_lossy().to_lowercase()).unwrap_or_default(); let same = !has_path_sep(typed) && (fname == typed.to_lowercase() || fname == format!("{}.exe", typed.to_lowercase())); cmd = if same && !assigns.iter().any(|(k, _)| k == "PATH") { Proc::new(typed) } else { Proc::new(&res.path) }; - for a in &argv[1..] { - cmd.raw_arg(msys_quote(a)); - } + rsp = add_msys_args(&mut cmd, &res.path, argv[1..].iter().map(|a| msys_quote(a)).collect()); native = false; msys_child = true; } @@ -1588,10 +1614,10 @@ impl Shell { } args.push(if msys { path::to_posix(&res.path) } else { res.path.to_string_lossy().into_owned() }); args.extend(argv[1..].iter().cloned()); - for a in &args { - if msys { - cmd.raw_arg(msys_quote(a)); - } else { + if msys { + rsp = add_msys_args(&mut cmd, &ip, args.iter().map(|a| msys_quote(a)).collect()); + } else { + for a in &args { cmd.arg(conv(a)); } } @@ -1680,6 +1706,16 @@ impl Shell { crate::io::append_started(&appends, child.id()); } if self.spawn_only { + if let Some(f) = rsp.take() { + // The program reads its response file as it starts; keep the file until it exits. + if let Ok(h) = std::os::windows::io::AsHandle::as_handle(&child).try_clone_to_owned() { + std::thread::spawn(move || { + let raw = std::os::windows::io::AsRawHandle::as_raw_handle(&h) as crate::sys::HANDLE; + unsafe { crate::sys::WaitForSingleObject(raw, u32::MAX) }; // INFINITE + drop(f); + }); + } + } self.spawned = Some(child); return Ok(0); } diff --git a/src/io.rs b/src/io.rs index 81c191f..63304f3 100644 --- a/src/io.rs +++ b/src/io.rs @@ -123,6 +123,20 @@ impl MemReader { /// A new temporary file that Windows deletes once the last handle to it, ours or a /// child's, is closed. fn temp_file() -> io::Result { + temp_file_named("gash-heredoc").map(|(f, _)| f) +} + +/// A response file holding `content`, for an MSYS program to read through an `@file` +/// argument (see `exec::add_msys_args`). Windows deletes it once the last handle is closed. +pub fn response_file(content: &[u8]) -> io::Result<(File, std::path::PathBuf)> { + let (mut f, path) = temp_file_named("gash-args")?; + f.write_all(content)?; + f.flush()?; + Ok((f, path)) +} + +/// Like `temp_file`, and also returns the path. The file name starts with `prefix`. +fn temp_file_named(prefix: &str) -> io::Result<(File, std::path::PathBuf)> { use std::os::windows::fs::OpenOptionsExt; use std::sync::atomic::{AtomicU32, Ordering}; const FILE_ATTRIBUTE_TEMPORARY: u32 = 0x100; @@ -136,11 +150,13 @@ fn temp_file() -> io::Result { let mut last = None; for _ in 0..16 { let name = format!( - "gash-heredoc-{}-{}-{:08x}.tmp", + "{}-{}-{}-{:08x}.tmp", + prefix, std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed), nanos ); + let path = dir.join(name); match std::fs::OpenOptions::new() .read(true) .write(true) @@ -148,9 +164,9 @@ fn temp_file() -> io::Result { .share_mode(0x7) // read | write | delete .attributes(FILE_ATTRIBUTE_TEMPORARY) .custom_flags(FILE_FLAG_DELETE_ON_CLOSE) - .open(dir.join(name)) + .open(&path) { - Ok(f) => return Ok(f), + Ok(f) => return Ok((f, path)), Err(e) if e.kind() == io::ErrorKind::AlreadyExists => last = Some(e), Err(e) => return Err(e), } diff --git a/tests/scripts/073_msys_long_args.code b/tests/scripts/073_msys_long_args.code new file mode 100644 index 0000000..c227083 --- /dev/null +++ b/tests/scripts/073_msys_long_args.code @@ -0,0 +1 @@ +0 \ No newline at end of file diff --git a/tests/scripts/073_msys_long_args.out b/tests/scripts/073_msys_long_args.out new file mode 100644 index 0000000..b1bdd72 --- /dev/null +++ b/tests/scripts/073_msys_long_args.out @@ -0,0 +1,14 @@ +args=1200 chars=49293 +1200 +ls: 0 +cat: 0 +background ls: 0 +[xxxxxxxxxxxxx +[a b] +[it's] +[back\slash] +["quoted"] +[@at] +[*] +[] +native: 126 diff --git a/tests/scripts/073_msys_long_args.sh b/tests/scripts/073_msys_long_args.sh new file mode 100644 index 0000000..7d47149 --- /dev/null +++ b/tests/scripts/073_msys_long_args.sh @@ -0,0 +1,24 @@ +# MSYS programs get argument lists longer than a Windows command line (32,767 characters), as in +# Git Bash, where the MSYS runtime passes them on without the command line (#20). +t=$(mktemp -d) +cd "$t" || exit 1 +for i in $(seq 1 1200); do : > "file-with-a-moderately-long-name-$i.txt"; done +set -- file-*.txt +echo "args=$# chars=$(printf '%s ' "$@" | wc -c)" +ls file-*.txt | wc -l +echo "ls: ${PIPESTATUS[0]}" +/usr/bin/cat file-*.txt > /dev/null +echo "cat: $?" +ls file-*.txt > /dev/null & +wait $! +echo "background ls: $?" + +# Quoting survives: spaces, quotes, backslashes, a leading @, glob characters, an empty argument. +long=$(printf 'x%.0s' $(seq 1 40000)) +/usr/bin/printf '[%s]\n' "$long" "a b" "it's" 'back\slash' '"quoted"' "@at" '*' '' | cut -c1-14 + +# A native program still hits the Windows limit, as in Git Bash. +cmd.exe /d /c "exit 0" "$long" 2>/dev/null +echo "native: $?" + +cd / && rm -rf "$t"