Skip to content

Commit 47a64b8

Browse files
authored
Rollup merge of #108218 - ChrisDenton:cmd-escape, r=cuviper
Windows: Quote more batch file arguments Make sure to always quote batch file arguments that contain command prompt special characters. Additionally add `/d` command line parameter to disable any autorun scripts that may change the way variable expansion works. This makes it more consistent across systems and may help avoid surprises. ## Background Info [`CreateProcess`](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw) with the `lpApplicationName` set can only be used to run `.exe` files and not script files such as `.bat`. However, for historical reasons, we do have special handling so that `.bat` files will be correctly run with `cmd.exe` as the application. In Windows, command line arguments are passed as a single string (not an array). Applications can parse this string however they like but most follow the standard MSVC C/C++ convention. But `cmd.exe` uses different argument parsing rules to other Windows programs (because it emulates old DOS). This PR aims to help smooth over some of the differences. r? libs
2 parents 6acdb2d + f01bdfa commit 47a64b8

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

std/src/sys/windows/args.rs

+10-1
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@ pub(crate) fn make_bat_command_line(
270270
// It is necessary to surround the command in an extra pair of quotes,
271271
// hence the trailing quote here. It will be closed after all arguments
272272
// have been added.
273-
let mut cmd: Vec<u16> = "cmd.exe /c \"".encode_utf16().collect();
273+
let mut cmd: Vec<u16> = "cmd.exe /d /c \"".encode_utf16().collect();
274274

275275
// Push the script name surrounded by its quote pair.
276276
cmd.push(b'"' as u16);
@@ -290,6 +290,15 @@ pub(crate) fn make_bat_command_line(
290290
// reconstructed by the batch script by default.
291291
for arg in args {
292292
cmd.push(' ' as u16);
293+
// Make sure to always quote special command prompt characters, including:
294+
// * Characters `cmd /?` says require quotes.
295+
// * `%` for environment variables, as in `%TMP%`.
296+
// * `|<>` pipe/redirect characters.
297+
const SPECIAL: &[u8] = b"\t &()[]{}^=;!'+,`~%|<>";
298+
let force_quotes = match arg {
299+
Arg::Regular(arg) if !force_quotes => arg.bytes().iter().any(|c| SPECIAL.contains(c)),
300+
_ => force_quotes,
301+
};
293302
append_arg(&mut cmd, arg, force_quotes)?;
294303
}
295304

0 commit comments

Comments
 (0)