Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 43 additions & 7 deletions src/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
/// `@"<file>"`, 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<String>) -> Option<std::fs::File> {
let len = program.as_os_str().len() + args.iter().map(|a| a.len() + 1).sum::<usize>();
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 {
Expand Down Expand Up @@ -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<std::fs::File> = None;
let mut cmd;
let native;
let mut msys_child = false;
Expand Down Expand Up @@ -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;
}
Expand All @@ -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));
}
}
Expand Down Expand Up @@ -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);
}
Expand Down
22 changes: 19 additions & 3 deletions src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<File> {
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;
Expand All @@ -136,21 +150,23 @@ fn temp_file() -> io::Result<File> {
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)
.create_new(true)
.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),
}
Expand Down
1 change: 1 addition & 0 deletions tests/scripts/073_msys_long_args.code
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0
14 changes: 14 additions & 0 deletions tests/scripts/073_msys_long_args.out
Original file line number Diff line number Diff line change
@@ -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
24 changes: 24 additions & 0 deletions tests/scripts/073_msys_long_args.sh
Original file line number Diff line number Diff line change
@@ -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"
Loading