Skip to main content

aft_base/
windows_command.rs

1//! Safe Windows process invocation for `.cmd` and `.bat` wrapper scripts.
2
3#[cfg(windows)]
4use std::ffi::OsStr;
5#[cfg(windows)]
6use std::io;
7#[cfg(windows)]
8use std::path::Path;
9#[cfg(windows)]
10use std::process::Command;
11
12#[cfg(windows)]
13const BATCH_COMMAND_ENV: &str = "AFT_BATCH_COMMAND";
14#[cfg(windows)]
15const BATCH_ARGUMENT_ENV_PREFIX: &str = "AFT_BATCH_ARGUMENT_";
16
17/// Whether `path` must be dispatched by `cmd.exe` on Windows.
18#[cfg(windows)]
19pub fn is_batch_file(path: &Path) -> bool {
20    path.extension()
21        .and_then(|ext| ext.to_str())
22        .is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat"))
23}
24
25/// Whether `key` is reserved for the batch-shim launcher.
26///
27/// Callers that add their own child environment must not override these values,
28/// because `cmd.exe` expands the command tail using them.
29#[cfg(windows)]
30pub fn is_batch_internal_env(key: &str, argument_count: usize) -> bool {
31    if key.eq_ignore_ascii_case(BATCH_COMMAND_ENV) {
32        return true;
33    }
34
35    let Some(suffix) = key.get(BATCH_ARGUMENT_ENV_PREFIX.len()..) else {
36        return false;
37    };
38    if !key[..BATCH_ARGUMENT_ENV_PREFIX.len()].eq_ignore_ascii_case(BATCH_ARGUMENT_ENV_PREFIX) {
39        return false;
40    }
41
42    suffix
43        .parse::<usize>()
44        .ok()
45        .is_some_and(|index| index < argument_count && suffix == index.to_string())
46}
47
48/// Build a safe `cmd.exe` invocation for a `.cmd`/`.bat` shim.
49///
50/// Windows cannot spawn batch files directly. Passing a batch path and its arguments
51/// as separate `cmd /C` arguments is unreliable because `cmd.exe` reparses its
52/// command tail. Keep the executable path and arguments in the environment (so
53/// literal `%` remains literal after single-pass expansion), then pass one
54/// explicitly quoted command tail.
55#[cfg(windows)]
56pub fn batch_command<I, S>(binary: &Path, args: I) -> io::Result<Command>
57where
58    I: IntoIterator<Item = S>,
59    S: AsRef<OsStr>,
60{
61    use std::os::windows::process::CommandExt;
62
63    let command_path = binary.to_str().ok_or_else(|| {
64        io::Error::new(
65            io::ErrorKind::InvalidInput,
66            "batch path cannot be represented safely for cmd.exe",
67        )
68    })?;
69    if command_path.contains(['\0', '\r', '\n', '"']) {
70        return Err(io::Error::new(
71            io::ErrorKind::InvalidInput,
72            "batch path cannot be represented safely for cmd.exe",
73        ));
74    }
75    // `fs::canonicalize` produces extended-length (`\\?\`) paths on Windows.
76    // CreateProcess accepts those paths, but cmd.exe does not reliably execute a
77    // batch file through that namespace, and npm shims additionally derive
78    // `%~dp0` paths that fail with "The system cannot find the path specified."
79    // Convert only the namespace spelling; the path remains canonical.
80    let command_path = crate::windows_path::non_verbatim_path_text(command_path)
81        .unwrap_or_else(|| command_path.to_string());
82
83    let mut command_line = format!("\"\"%{BATCH_COMMAND_ENV}%\"");
84    let mut argument_env = Vec::new();
85    for (index, arg) in args.into_iter().enumerate() {
86        let arg = arg.as_ref().to_str().ok_or_else(|| {
87            io::Error::new(
88                io::ErrorKind::InvalidInput,
89                "batch argument cannot be represented safely for cmd.exe",
90            )
91        })?;
92        if arg.contains(['\0', '\r', '\n', '"']) {
93            return Err(io::Error::new(
94                io::ErrorKind::InvalidInput,
95                "batch argument cannot be represented safely for cmd.exe",
96            ));
97        }
98        let name = format!("{BATCH_ARGUMENT_ENV_PREFIX}{index}");
99        command_line.push_str(" \"");
100        command_line.push('%');
101        command_line.push_str(&name);
102        command_line.push_str("%\"");
103        // The value is expanded just before a closing quote. A program that
104        // parses its command line with the C runtime rules reads 2n
105        // backslashes before a quote as n literal backslashes and then the
106        // quote; an odd run would escape the quote and merge this argument
107        // with the next one. Double only the trailing run: arguments contain
108        // no other quotes, so interior backslashes are already literal.
109        let trailing = arg.len() - arg.trim_end_matches('\\').len();
110        let mut value = String::with_capacity(arg.len() + trailing);
111        value.push_str(arg);
112        value.extend(std::iter::repeat_n('\\', trailing));
113        argument_env.push((name, value));
114    }
115    command_line.push('"');
116
117    let mut command = Command::new(
118        crate::environment::non_empty_os_var("ComSpec")
119            .or_else(|| crate::environment::non_empty_os_var("COMSPEC"))
120            .unwrap_or_else(|| "cmd.exe".into()),
121    );
122    command
123        .args(["/d", "/s", "/v:off", "/c"])
124        // `cmd.exe` must receive the complete command tail verbatim. Normal
125        // argument escaping would add another quoting layer and break paths
126        // containing spaces.
127        .raw_arg(command_line)
128        .env(BATCH_COMMAND_ENV, command_path)
129        .envs(argument_env);
130    Ok(command)
131}
132
133#[cfg(all(test, windows))]
134mod tests {
135    use super::*;
136
137    #[test]
138    fn batch_shim_forwards_trailing_backslash_arguments_to_crt_programs() {
139        let temp = tempfile::tempdir().unwrap();
140        let source = temp.path().join("argv.rs");
141        let recorder = temp.path().join("argv.exe");
142        // Rust's Windows argument parser follows the Microsoft C runtime
143        // rules, so this program sees exactly what a CRT-built tool would.
144        std::fs::write(
145            &source,
146            "fn main() { for arg in std::env::args().skip(1) { println!(\"{arg}\"); } }\n",
147        )
148        .unwrap();
149        let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());
150        let compile = std::process::Command::new(rustc)
151            .arg(&source)
152            .arg("-o")
153            .arg(&recorder)
154            .current_dir(temp.path())
155            .output()
156            .unwrap();
157        assert!(
158            compile.status.success(),
159            "{} {}",
160            String::from_utf8_lossy(&compile.stdout),
161            String::from_utf8_lossy(&compile.stderr)
162        );
163        let shim = temp.path().join("forward.cmd");
164        std::fs::write(
165            &shim,
166            format!("@echo off\r\n\"{}\" %*\r\n", recorder.display()),
167        )
168        .unwrap();
169        let output = batch_command(&shim, ["C:\\space dir\\", "next", "two\\\\"])
170            .unwrap()
171            .output()
172            .unwrap();
173        assert!(output.status.success(), "{output:?}");
174        assert_eq!(
175            String::from_utf8_lossy(&output.stdout).replace("\r\n", "\n"),
176            "C:\\space dir\\\nnext\ntwo\\\\\n"
177        );
178    }
179
180    #[test]
181    fn cmd_compatible_path_only_converts_dos_and_unc_namespaces() {
182        assert_eq!(
183            crate::windows_path::non_verbatim_path_text(r"\\?\C:\cache\server.cmd").unwrap(),
184            r"C:\cache\server.cmd"
185        );
186        assert_eq!(
187            crate::windows_path::non_verbatim_path_text(r"\\?\unc\host\share\server.cmd").unwrap(),
188            r"\\host\share\server.cmd"
189        );
190        assert_eq!(
191            crate::windows_path::non_verbatim_path_text(r"\\?\Volume{1234}\server.cmd"),
192            None
193        );
194    }
195
196    #[test]
197    fn batch_command_invokes_a_spaced_shim_with_args() {
198        let temp = tempfile::tempdir().unwrap();
199        let shim = temp.path().join("language server.cmd");
200        std::fs::write(&shim, "@echo off\r\necho %~1\r\n").unwrap();
201
202        let output = batch_command(&shim, ["--stdio"]).unwrap().output().unwrap();
203
204        assert!(output.status.success());
205        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "--stdio");
206    }
207
208    #[test]
209    fn batch_command_invokes_canonicalized_npm_style_shim() {
210        let temp = tempfile::tempdir().unwrap();
211        let root = temp.path().join("npm cache 100%");
212        let bin = root.join("node_modules").join(".bin");
213        let package = root.join("node_modules").join("language-server");
214        std::fs::create_dir_all(&bin).unwrap();
215        std::fs::create_dir_all(&package).unwrap();
216        let shim = bin.join("language-server.cmd");
217        let target = package.join("server.cmd");
218        std::fs::write(
219            &shim,
220            "@echo off\r\nset dp0=%~dp0\r\n\"%dp0%\\..\\language-server\\server.cmd\" %*\r\n",
221        )
222        .unwrap();
223        std::fs::write(&target, "@echo off\r\necho %~1\r\n").unwrap();
224        let canonical_shim = std::fs::canonicalize(&shim).unwrap();
225        assert!(canonical_shim.to_string_lossy().starts_with(r"\\?\"));
226
227        let output = batch_command(&canonical_shim, ["--stdio"])
228            .unwrap()
229            .output()
230            .unwrap();
231
232        assert!(
233            output.status.success(),
234            "stderr: {}",
235            String::from_utf8_lossy(&output.stderr)
236        );
237        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "--stdio");
238    }
239
240    #[test]
241    fn batch_command_preserves_percent_in_argument() {
242        let temp = tempfile::tempdir().unwrap();
243        let shim = temp.path().join("formatter.cmd");
244        std::fs::write(&shim, "@echo off\r\necho %~1\r\n").unwrap();
245
246        let output = batch_command(&shim, ["100%coverage%"])
247            .unwrap()
248            .output()
249            .unwrap();
250
251        assert!(output.status.success());
252        assert_eq!(
253            String::from_utf8_lossy(&output.stdout).trim(),
254            "100%coverage%"
255        );
256    }
257
258    #[test]
259    fn launcher_environment_names_are_reserved() {
260        assert!(is_batch_internal_env("AFT_BATCH_COMMAND", 1));
261        assert!(is_batch_internal_env("aft_batch_argument_0", 1));
262        assert!(!is_batch_internal_env("AFT_BATCH_ARGUMENT_1", 1));
263        assert!(!is_batch_internal_env("AFT_BATCH_ARGUMENT_00", 1));
264        assert!(!is_batch_internal_env("AFT_BATCH_OTHER", 1));
265    }
266
267    #[test]
268    fn batch_command_rejects_non_unicode_arguments() {
269        use std::os::windows::ffi::OsStringExt;
270
271        let temp = tempfile::tempdir().unwrap();
272        let shim = temp.path().join("formatter.cmd");
273        let invalid = std::ffi::OsString::from_wide(&[0xd800]);
274
275        let error = batch_command(&shim, [invalid]).unwrap_err();
276
277        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
278    }
279}